inflorm 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: d695f0a82e3f0f6c2efdc498261063ba56f1d924
4
+ data.tar.gz: 581f6187ef37d2e14dec68dfd827b54d13441b6e
5
+ SHA512:
6
+ metadata.gz: 3e56cdff307f20cf309b456bd2b0a9e36896a36bca05b33242363126ca540d8c18d99520e134564a91950a57d8a5c0c108bd73635ccf1babfed35ed572805de0
7
+ data.tar.gz: ae4eeef4bfff80668cda0154787f82b4147a1149d33b15f83d6b7f97bca9c8f0db431dbd812cb9cdfbfea0bd799b8ec344fdc748d1ab09e256e1dc916f874934
data/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /spec/examples.txt
10
+ /tmp/
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,3 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.2.2
@@ -0,0 +1,13 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
4
+
5
+ We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, age, or religion.
6
+
7
+ Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
8
+
9
+ Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
10
+
11
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
12
+
13
+ This Code of Conduct is adapted from the [Contributor Covenant](http:contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in inflorm.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 Brad Robertson
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,182 @@
1
+ # Inflorm
2
+
3
+ *Simple Form Objects with validations and associations making no assumptions about persistence*
4
+
5
+ This is so little code you almost can't call it a library. It's simply a wrapper around Virtus
6
+ and ActiveModel validations, with an extra validation to allow for validating associations. I hesistated
7
+ to even make it a gem, but it's a pattern we use across multiple apps so it kind of made sense.
8
+
9
+ ## Philosophy
10
+
11
+ After working on many massive rails apps, it's become clear that model validations can cause a lot
12
+ of headaches, particularly when you get into custom validations and conditional validations. At
13
+ Influitive, we now consider these types of validations on the model an anti-pattern and stick purely
14
+ to validations that support underlying database constraints. Validations such as `NOT NULL` and `UNIQUE`
15
+ make sense on the model. Validations such as `validate property x if it's a full moon` do NOT
16
+ make sense in the model as these are contextual to a particular use case. This use case should be
17
+ wrapped up in its own object and used to validate input *before* it hits your persistence layer.
18
+
19
+ ## Why another form object library?
20
+
21
+ Again, I hardly consider this a library on its own, it's just a thin wrapper. We worked with
22
+ both [Reform](https://github.com/apotonick/reform) and [ActiveType](https://github.com/makandra/active_type)
23
+ and both always felt awkward to use and required a new dsl to understand.
24
+
25
+ - Reform feels weird to me because I generally just want params in and params out with validations
26
+ and param whitelisting. It requires however an underlying model to be passed in, then validated with
27
+ params separately passed in. It has a whole DSL for persistence which I never fully grasped, though
28
+ as the author states, it's optional to use.
29
+ - ActiveType is very much ActiveRecord dependent. It also unfortunately sticks to the Rails
30
+ `accepts_nested_attributes` paradigm which requires nesting to be done with a `{association_name}_attributes` key which I find annoying. (your public interface should NOT be determined by the framework you use under the hood).
31
+ Futhermore, for associations, it instantiates raw models as the children, as opposed to other form objects, which to me defeats the purpose of a form object library.
32
+
33
+ This is not to speak badly about either library. They both obviously suit the use-cases of the authors,
34
+ they just didn't suit our use-case.
35
+
36
+ ## Usage
37
+
38
+ Since inflorm is nothing more than a thin wrapper over [Virtus](https://github.com/solnic/virtus)
39
+ and [ActiveModel::Validations](http://guides.rubyonrails.org/active_model_basics.html#validations).
40
+ As such, you can find advanced documentation on this sites, but a simple example would look like this:
41
+
42
+ ```ruby
43
+ class ParentForm
44
+ include Inflorm
45
+
46
+ attribute :name, String
47
+ attribute :title, String
48
+
49
+ attribute :child, ChildForm # has_one association
50
+ attribute :pets, Array[PetForm] # has_many association
51
+
52
+ validates :name, presence: true
53
+ validates :child, associated: true
54
+ validates :pets, associated: true
55
+ end
56
+
57
+ class ChildForm
58
+ include Inflorm
59
+
60
+ attribute :age, Integer
61
+
62
+ validates :age, presence: true
63
+ end
64
+
65
+ class PetForm
66
+ include Inflorm
67
+
68
+ attribute :name, String
69
+ attribute :species, String
70
+
71
+ validates :name, presence: true
72
+ validates :species, presence: true
73
+ end
74
+ ```
75
+
76
+ Using those classes like so:
77
+
78
+ ```ruby
79
+ # Simple object
80
+ p = Parent.new name: ''
81
+ p.valid? # => false
82
+
83
+ # Object with has_one association
84
+ p = Parent.new name: 'x', child: {age: 123}
85
+ p.child.class # => ChildForm
86
+ p.valid? # => true
87
+
88
+ # Object with has_many association
89
+ p = Parent.new pets: [{species: 'dog', name: 'George'}, {species: 'cat', name: 'Fluffy'}]
90
+ p.pets.class # => Array
91
+ p.pets[0].class # => PetForm
92
+ p.valid? # => true
93
+ ```
94
+
95
+ ## Persistence
96
+
97
+ Inflorm doesn't care about persistence. That's what your ORM is for (or appropriate
98
+ [Command](http://rom-rb.org/guides/basics/commands/),
99
+ [Repository](http://lotusrb.org/guides/models/repositories/) etc). Since it's just params in and
100
+ params out, you can just call `to_h` on your form object to get the validated, whitelisted params.
101
+ This means you don't need to use things like `strong_parameters`.
102
+
103
+ ### Rails-like pattern
104
+ A common pattern in the rails world is to do something like:
105
+
106
+ ```ruby
107
+ # some_controller.rb
108
+ if @my_object.save
109
+ # do_something
110
+ else
111
+ # something else
112
+ end
113
+ ```
114
+
115
+ Inflorm includes a very simple implementation of `save` by allowing you to define a `persist!` method
116
+ on your form that will only be called if your form is valid. It looks like this:
117
+
118
+ ```ruby
119
+ def save
120
+ valid? && persist!
121
+ end
122
+ ```
123
+
124
+ So if you define a `persist!` method on your form like so:
125
+
126
+ ```ruby
127
+ def persist!
128
+ MyCommand.persist(to_h)
129
+ end
130
+ ```
131
+
132
+ Then your controller can stick to the above pattern. You might need the underlying model from that
133
+ persistence, so assuming the command above returns that, you can do something like this in your controller
134
+
135
+ ```ruby
136
+ # some_controller.rb
137
+ if model = @my_object.save
138
+ render json: model.to_json
139
+ else
140
+ render json: {errors: model.errors.messages}
141
+ end
142
+ ```
143
+
144
+ ## FAQ
145
+
146
+ > *What's with the name?*
147
+
148
+ > **At Influitive we're known for our very creative [portmanteaus](https://en.wikipedia.org/wiki/Portmanteau). This is the ultimate portmanteau of a portmanteau combining Influitive and Form. Clearly we're not very creative people.**
149
+
150
+ #
151
+ > *Will this ever hook into my persistence layer X?*
152
+
153
+ > **No**
154
+
155
+ #
156
+ > *My association is nil, but my main object still passes validation. How do I prevent this?*
157
+
158
+ > **Inflorm won't validate nil or empty arrays of associations (since there's nothing to validate). If you need to ensure that the association is there, simply validate its presence like so `validates :child, presence: true`. This will ensure that `child` is not nil (or empty in the `has_many` case)**
159
+
160
+ ## TODO
161
+
162
+ 1. `to_h` right now relies on Rails ActiveSupport `Object#as_json` as it will traverse all properties and convert them recursively to an appropriate primitive or hash/array. This isn't possible right now with just Virtus as calling `to_h` on the Virtus object will still nested associations as their defined instance type. I'm really not happy about having to use Rails monkeypatching for this. Apparently Virtus 2.0 [will have better to_h handling](https://github.com/solnic/virtus/issues/290)
163
+ 2. The current association validator pollutes the ruby global constant namespace by defining a `AssociatedValidator` class. There's *got* to be a way to register this validation without doing so. This would be a nice change.
164
+ 3. *Maybe* add `has_one`, `has_many` methods to mimic ActiveRecord associations but for form objects?. I kind of question the extra overhead, although it's not too much cognitive load since most people inherently understand `has_one` / `has_many`
165
+
166
+ ## Credits
167
+
168
+ I really haven't done any significant work to make this gem. It's all thanks to [virtus contributors](https://github.com/solnic/virtus/graphs/contributors) and [activemodel contributors](https://github.com/rails/rails/tree/master/activemodel). So go thank them!
169
+
170
+ ## Development
171
+
172
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `bin/console` for an interactive prompt that will allow you to experiment.
173
+
174
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
175
+
176
+ ## Contributing
177
+
178
+ 1. Fork it ( https://github.com/[my-github-username]/inflorm/fork )
179
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
180
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
181
+ 4. Push to the branch (`git push origin my-new-feature`)
182
+ 5. Create a new Pull Request
data/Rakefile ADDED
@@ -0,0 +1 @@
1
+ require "bundler/gem_tasks"
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "inflorm"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
data/bin/setup ADDED
@@ -0,0 +1,7 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+
5
+ bundle install
6
+
7
+ # Do any other automated setup that you need to do here
data/inflorm.gemspec ADDED
@@ -0,0 +1,28 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'inflorm/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "inflorm"
8
+ spec.version = Inflorm::VERSION
9
+ spec.authors = ["Brad Robertson"]
10
+ spec.email = ["brad@influitive.com"]
11
+
12
+ spec.summary = %q{Simple Form Objects}
13
+ spec.description = %q{Form Objects with no assumptions about persistence and a clean api for associations/validations}
14
+ spec.homepage = "https://github.com/influitive/inflorm"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
18
+ spec.bindir = "exe"
19
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
20
+ spec.require_paths = ["lib"]
21
+
22
+ spec.add_development_dependency "bundler", "~> 1.9"
23
+ spec.add_development_dependency "rake", "~> 10.0"
24
+ spec.add_development_dependency "rspec", "~> 3.0"
25
+
26
+ spec.add_dependency "activemodel", "~> 4.0"
27
+ spec.add_dependency "virtus", "~> 1.0"
28
+ end
data/lib/inflorm.rb ADDED
@@ -0,0 +1,49 @@
1
+ require "inflorm/version"
2
+ require "active_model"
3
+ require "active_support/core_ext/hash/keys"
4
+ require "virtus"
5
+
6
+ require "inflorm/associated_validator"
7
+
8
+ module Inflorm
9
+ def self.included(base)
10
+ base.class_eval do
11
+ include Virtus.model
12
+ include ActiveModel::Validations
13
+
14
+ attribute :id, String
15
+
16
+ # Need to override Virtus.model to_h, but self.included is run *after* our module
17
+ # is included, so we can't define this method below with the others (unless we prepended)
18
+ # Note we're unfortunately relying on rails monkey patching
19
+ # active_support/core_ext/object/json
20
+ # which will recursively call as_json on all nested objs. Apparently Virtus 2.0 will give us
21
+ # these facilities without relying on it.
22
+ def to_h
23
+ as_json.deep_symbolize_keys
24
+ end
25
+ end
26
+ end
27
+
28
+ def persisted?
29
+ id.present?
30
+ end
31
+
32
+ def marked_for_destruction?
33
+ respond_to?(marked_for_destruction_param) && send(marked_for_destruction_param).present?
34
+ end
35
+
36
+ def save
37
+ valid? && persist!
38
+ end
39
+
40
+ protected
41
+
42
+ def marked_for_destruction_param
43
+ "_destroy".freeze
44
+ end
45
+
46
+ def persist!
47
+ raise "Not Implemented"
48
+ end
49
+ end
@@ -0,0 +1,26 @@
1
+ # TODO see if ActiveModel lets you register a validation
2
+ # without polluting global namespace
3
+ class AssociatedValidator < ActiveModel::EachValidator
4
+
5
+ def validate_each(record, attribute, value)
6
+ value.respond_to?(:to_ary) ?
7
+ validate_many(record, attribute, value) :
8
+ validate_one(record, attribute, value)
9
+ end
10
+
11
+ private
12
+
13
+ def validate_one(record, attribute, value)
14
+ return true if value.nil? || value.marked_for_destruction?
15
+
16
+ unless value.valid?
17
+ record.errors.add(attribute, "association error")
18
+ end
19
+ end
20
+
21
+ def validate_many(record, attribute, value)
22
+ unless value.reject(&:marked_for_destruction?).all?(&:valid?)
23
+ record.errors.add(attribute, "association error")
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,3 @@
1
+ module Inflorm
2
+ VERSION = "0.1.0"
3
+ end
metadata ADDED
@@ -0,0 +1,129 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: inflorm
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Brad Robertson
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2015-07-07 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.9'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.9'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: activemodel
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '4.0'
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '4.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: virtus
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '1.0'
76
+ type: :runtime
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '1.0'
83
+ description: Form Objects with no assumptions about persistence and a clean api for
84
+ associations/validations
85
+ email:
86
+ - brad@influitive.com
87
+ executables: []
88
+ extensions: []
89
+ extra_rdoc_files: []
90
+ files:
91
+ - ".gitignore"
92
+ - ".rspec"
93
+ - ".travis.yml"
94
+ - CODE_OF_CONDUCT.md
95
+ - Gemfile
96
+ - LICENSE.txt
97
+ - README.md
98
+ - Rakefile
99
+ - bin/console
100
+ - bin/setup
101
+ - inflorm.gemspec
102
+ - lib/inflorm.rb
103
+ - lib/inflorm/associated_validator.rb
104
+ - lib/inflorm/version.rb
105
+ homepage: https://github.com/influitive/inflorm
106
+ licenses:
107
+ - MIT
108
+ metadata: {}
109
+ post_install_message:
110
+ rdoc_options: []
111
+ require_paths:
112
+ - lib
113
+ required_ruby_version: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - ">="
116
+ - !ruby/object:Gem::Version
117
+ version: '0'
118
+ required_rubygems_version: !ruby/object:Gem::Requirement
119
+ requirements:
120
+ - - ">="
121
+ - !ruby/object:Gem::Version
122
+ version: '0'
123
+ requirements: []
124
+ rubyforge_project:
125
+ rubygems_version: 2.4.6
126
+ signing_key:
127
+ specification_version: 4
128
+ summary: Simple Form Objects
129
+ test_files: []