muffin 0.2.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: f444194037bfb0ce4da565e15de9365aba611a72
4
+ data.tar.gz: 58ab1e839e36c8070e4f4cb24bc4af5ddbc87b25
5
+ SHA512:
6
+ metadata.gz: f4899b5cf39c11bf4c64561bec040877e71aa43d6a443d8fbe0eae6a1de87aa51d3c3a47df6f549793ea9be76e4ad2bf2fb7ade4d61c235daaa470ef27abd047
7
+ data.tar.gz: 820ec3cb4faf5e037fa565feceb28c83d3fc102de599cd2de0bf831363ef78fd6ca2b2bbeb20d5789932df5c7eee5e09cb28d59e26616766e0a717c9e6f72b26
data/.editorconfig ADDED
@@ -0,0 +1,12 @@
1
+ ; EditorConfig is awesome: http://EditorConfig.org
2
+
3
+ ; top-most EditorConfig file
4
+ root = true
5
+
6
+ ; Unix-style newlines with a newline ending every file
7
+ [*]
8
+ indent_style = spaces
9
+ end_of_line = lf
10
+ insert_final_newline = true
11
+ trim_trailing_whitespace = true
12
+ indent_size = 2
data/.gitignore ADDED
@@ -0,0 +1,13 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ .byebug_history
11
+
12
+ # rspec failure tracking
13
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --color
2
+ --require spec_helper
3
+ --no-profile
data/.rubocop.yml ADDED
@@ -0,0 +1,67 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.4
3
+ DisplayCopNames: true
4
+ DisplayStyleGuide: true
5
+
6
+ require:
7
+ - rubocop/rspec/focused
8
+
9
+ Metrics:
10
+ Enabled: false
11
+
12
+ RSpec/Focused:
13
+ Enabled: true
14
+
15
+ Style/AlignParameters:
16
+ EnforcedStyle: with_fixed_indentation
17
+
18
+ Style/ConditionalAssignment:
19
+ Enabled: false
20
+
21
+ Style/Documentation:
22
+ Enabled: false
23
+
24
+ Style/DoubleNegation:
25
+ Enabled: false
26
+
27
+ Style/EmptyMethod:
28
+ EnforcedStyle: expanded
29
+
30
+ Style/FrozenStringLiteralComment:
31
+ Enabled: false
32
+
33
+ Style/Lambda:
34
+ Enabled: false
35
+
36
+ Style/MethodMissing:
37
+ Enabled: false
38
+
39
+ Style/MultilineMethodCallIndentation:
40
+ EnforcedStyle: indented
41
+
42
+ Style/NilComparison:
43
+ Enabled: false
44
+
45
+ Style/NumericLiterals:
46
+ MinDigits: 15
47
+
48
+ Style/NumericPredicate:
49
+ Enabled: false
50
+
51
+ Style/WordArray:
52
+ EnforcedStyle: brackets
53
+
54
+ Style/SymbolArray:
55
+ EnforcedStyle: brackets
56
+
57
+ Style/Lambda:
58
+ EnforcedStyle: literal
59
+
60
+ Style/RegexpLiteral:
61
+ Enabled: false
62
+
63
+ Style/StringLiterals:
64
+ EnforcedStyle: double_quotes
65
+
66
+ Style/WordArray:
67
+ Enabled: false
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at jens@nerdgeschoss.de. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,35 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in muffin.gemspec
4
+ gemspec
5
+
6
+ group :development, :test do
7
+ gem "activerecord"
8
+ gem "bundler"
9
+ gem "guard-rspec"
10
+ gem "rails"
11
+ gem "rake"
12
+ gem "rspec", "~> 3.0"
13
+ gem "rubocop"
14
+ gem "rubocop-rspec-focused"
15
+ gem "sqlite3"
16
+
17
+ if RUBY_ENGINE == "ruby"
18
+ gem "simplecov" if RUBY_VERSION >= "2.0.0"
19
+
20
+ unless ENV["CI"]
21
+ gem "pry"
22
+
23
+ if RUBY_VERSION < "2.0.0"
24
+ gem "pry-nav"
25
+ else
26
+ gem "pry-byebug"
27
+ end
28
+
29
+ # yard and friends
30
+ gem "github-markup"
31
+ gem "redcarpet"
32
+ gem "yard"
33
+ end
34
+ end
35
+ end
data/Guardfile ADDED
@@ -0,0 +1,10 @@
1
+ guard :rspec, cmd: "bundle exec rspec" do
2
+ require "guard/rspec/dsl"
3
+ dsl = Guard::RSpec::Dsl.new(self)
4
+
5
+ # RSpec files
6
+ rspec = dsl.rspec
7
+ watch(rspec.spec_files)
8
+
9
+ watch(%r{^lib/muffin/(.+)\.rb$}) { |m| "spec/models/#{m[1]}_spec.rb" }
10
+ end
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 nerdgeschoss GmbH
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,286 @@
1
+ # Muffin
2
+
3
+ ## Why form objects?
4
+
5
+ Form objects encapsulate logic to modify data (similar to changesets in Elixir or Mutations in GraphQL). Every non trivial form in rails usually has some custom (and conditional) validation, specific behavior (when update `x`, then remove `y`) and complex association (e.g. `accepts_nested_attributes_for`). This is usually spread all over the model leading to hard to maintain code and tons of conditional validation that is hard to understand. Also it’s not possible to have a form for many objects without having a parent object that is doing the nested_attribute dance.
6
+
7
+ Forms are living in `/app/forms`. They should work independently from controllers (for unit testing) and can (but doesn’t have to!) handle `ActiveRecord` objects.
8
+
9
+ ## Public API
10
+
11
+ ```ruby
12
+ my_form = MyForm.new(request:, params:, scope:) # scope could be the current_user
13
+ my_form.call # 'commits' the form: it validates and calls the internal process method. returns true on success, false when validation fails. Other errors are signaled via Exceptions.
14
+ my_form.call! # same as call, but raises a ValidationError if validation fails
15
+ ```
16
+
17
+ ## Attributes
18
+
19
+ Attributes specify which attribute in the form can be set via a request
20
+
21
+ ```ruby
22
+ class MyForm < Muffin::Base
23
+ attribute :name # type String is implicit
24
+ attribute :age, Integer # second argument defines type if present
25
+ attribute :accepted?, Boolean # boolean is defined for true or false, converts strings like "on" or "off" (from forms) automatically to their boolean value
26
+ attribute :tags, array: true # array of strings
27
+ attribute :tags, [String] # same as above
28
+ end
29
+ ```
30
+
31
+ Forms can contain validations
32
+
33
+ ```ruby
34
+ class MyForm < Muffin::Base
35
+ attribute :name
36
+ validates :name, presence: true
37
+ end
38
+ ```
39
+
40
+ And also give a list of required attributes (useful for html validation and marking them in the UI).
41
+
42
+ ```ruby
43
+ my_form.required_attributes # [:name]
44
+ my_form.valid? # returns true/false
45
+ my_form.errors # returns an error object
46
+ ```
47
+
48
+ Attributes are automatically assigned on init:
49
+
50
+ ```ruby
51
+ my_form = MyForm.new(params: { name: "Superman" }) # assigns the name attribute
52
+ my_form.attributes # { name: "Superman" }
53
+ ```
54
+
55
+ ## Performing Changes
56
+
57
+ When `call` is invoked, the form performs validation steps. If those steps are successful, `perform` is called. `perform` is invoked inside of a transaction.
58
+
59
+ ```ruby
60
+ class MyForm < Muffin::Base
61
+ attribute :name
62
+
63
+ def perform
64
+ Model.find(5).update! name: name
65
+ end
66
+ end
67
+ ```
68
+
69
+ The form does not make any assumptions about what perform does except for needing all validations to be successful.
70
+
71
+ ## Nesting forms
72
+
73
+ Attributes can be nested (this replaces `accepts_nested_attributes_for` and is compatible with its helpers, e.g. in forms).
74
+
75
+ ```ruby
76
+ class WishlistForm < Muffin::Base
77
+ attribute :children_name
78
+ attribute :wishes do
79
+ attribute :name
80
+ validates :name, presence: true
81
+ end
82
+ end
83
+
84
+ WishlistForm.new(params: { children_name: "Klaus", wishes: [{ name: "some cookies}])
85
+ ```
86
+
87
+ ## Manually assigning parameters
88
+
89
+ Sometimes it's necessary to manually assign attributes after initialization. In this case `assign_attributes` can be overriden (a call to super is optional and will invoke the normal behaviour).
90
+
91
+ ```ruby
92
+ class MyForm < Form
93
+ attribute :name
94
+
95
+ def assign_attributes
96
+ self.name = params[:name].downcase
97
+ end
98
+ end
99
+
100
+ MyForm.new(params: { name: "Klaus" }).name # "klaus"
101
+ ```
102
+
103
+ ## Creating / updating active record objects
104
+
105
+ In the most simple case of a form mapping 1:1 to an active record object, the form object should be as simple as possible:
106
+
107
+ ```ruby
108
+ class Object < ActiveRecord::Base
109
+ # has a :name
110
+ end
111
+
112
+ class ObjectUpdateForm < Muffin::Base
113
+ attribute :id
114
+ attribute :name
115
+
116
+ validates :name, presence: true
117
+
118
+ def model
119
+ @model ||= Object.find(params[:id])
120
+ end
121
+
122
+ private
123
+
124
+ def assign_attributes
125
+ self.name = model.name
126
+ super # assigns the params hash
127
+ end
128
+
129
+ def perform
130
+ model.update!(attributes.slice(:name))
131
+ end
132
+ end
133
+
134
+ Post.first.name # "My Post" from Post 1
135
+ form = ObjectUpdateForm.new(params: { id: 1, name: "Updated Post" })
136
+ form.call
137
+ Post.first.name # "Updated Post"
138
+ ```
139
+
140
+ ## Updating nested active record objects
141
+
142
+ ```ruby
143
+ class User < ActiveRecord::Base
144
+ has_many :comments
145
+ end
146
+
147
+ class Comment < ActiveRecord::Base
148
+ belongs_to :user
149
+ end
150
+
151
+ class MyForm < Muffin::Base
152
+ attribute :id, Integer
153
+ attribute :comments do
154
+ attribute :id, Integer
155
+ attribute :_destroy, Boolean
156
+ attribute :text
157
+ end
158
+
159
+ def user
160
+ @user ||= User.find(params[:id])
161
+ end
162
+
163
+ def assign_attributes
164
+ self.attributes = user.attributes.merge(comments: user.comments.map(&:attributes))
165
+ super
166
+ end
167
+
168
+ def perform
169
+ update_nested! user.comments, comments
170
+ end
171
+ end
172
+ ```
173
+
174
+ `update_nested` will create new comments, update existing comments and destroy comments where `_destroy` is true. If no `:id` is present, it will create a new object always. If you don’t want to allow deleting, don’t add a `:_destroy` attribute.
175
+
176
+ ## Integrating with policies
177
+
178
+ Policies are integrated with form objects.
179
+
180
+ ```ruby
181
+ class MyForm < Muffin::Base
182
+ attribute :name
183
+ permitted? { scope.admin? }
184
+ end
185
+
186
+ form = MyForm.new(params: { name: "Klaus"}, scope: normal_user)
187
+ form.permitted? # false
188
+ form.call # raises NotPermitted
189
+ ```
190
+
191
+ You can also permit single attributes depending on the user (which works as a replacement for strong attributes):
192
+
193
+ ```ruby
194
+ class MyForm < Muffin::Base
195
+ attribute :name, permit: -> { scope.admin? }
196
+ end
197
+
198
+ form = MyForm.new(params: { name: "Klaus"}, scope: normal_user)
199
+ form.name # nil
200
+ form.permitted? # true
201
+ form.attributes # { }, will not include non permitted attributes
202
+ form.attribute_permitted?(:name) # false
203
+ ```
204
+
205
+ If permission should happen depending on the actual value of an attribute, this is possible, too.
206
+
207
+ ```ruby
208
+ class MyForm < Muffin::Base
209
+ attribute :role, permitted_values: -> { scope.admin? ? ["user", "admin"] : ["user"] }
210
+ end
211
+
212
+ form = MyForm.new(params: { role: "admin"}, scope: normal_user)
213
+ # will raise NotPermitted
214
+ form = MyForm.new(params: { role: "user"}, scope: normal_user)
215
+ form.attribute_permitted?(:role) # true
216
+ form.attribute_value_permitted?(:role, "admin") # false
217
+ form.permitted_values(:role) # ["user"]
218
+ ```
219
+ ## Integration with controllers
220
+
221
+ A form object should be easy to create from a controller with a special helper (inspired by Trailblazer).
222
+
223
+ ```ruby
224
+ def create
225
+ @form = prepare MyForm
226
+ if @form.call
227
+ redirect_to @form.model
228
+ else
229
+ render :new
230
+ end
231
+ end
232
+ ```
233
+
234
+ This will instantiate a form object, hand over the params and the context (e.g. the currently logged in user or auth scope) and performs depending on the method, which is roughly equivalent to
235
+
236
+ ```ruby
237
+ def prepare(klass)
238
+ scope = try(:form_auth_scope) || try(:current_user)
239
+ processed_params = params[klass.model_name.underscore].permit!.to_h.map {...} # extract params from hash and clean up keys, e.g. comments_attributes -> comments
240
+ klass.new params: processed_params, request: request, scope: scope
241
+ end
242
+ ```
243
+
244
+ ## Integration with Views
245
+
246
+ Form objects work with Rails' form helpers automatically.
247
+
248
+ ```ruby
249
+ class SurveyForm < Form
250
+ attribute :email
251
+ attribute :answers do
252
+ attribute :question_id, Integer
253
+ attribute :answer
254
+
255
+ validates :answer, presence: true
256
+ end
257
+
258
+ validates :email, presence: true
259
+ end
260
+
261
+ def new
262
+ @survey = prepare SurveyForm
263
+ end
264
+
265
+
266
+ = form_for @survey do |f|
267
+ = f.email_field :email
268
+ = f.fields_for :answers do |ff|
269
+ = ff.hidden_field :question_id
270
+ = ff.text_field :answer
271
+ = f.submit
272
+ ```
273
+
274
+ ## Development
275
+
276
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
277
+
278
+ 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`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
279
+
280
+ ## Contributing
281
+
282
+ Bug reports and pull requests are welcome on GitHub at https://github.com/nerdgeschoss/muffin. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
283
+
284
+ ## License
285
+
286
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task default: :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "muffin"
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(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/circle.yml ADDED
@@ -0,0 +1,24 @@
1
+ version: 2
2
+ executorType: docker
3
+ containerInfo:
4
+ - image: ruby:2.3.3
5
+ stages:
6
+ build:
7
+ working_directory: /root/muffin
8
+ steps:
9
+ - type: checkout
10
+ - type: cache-restore
11
+ key: gemfile-{{ checksum "muffin.gemspec" }}
12
+ - type: shell
13
+ name: Install Ruby Dependencies
14
+ command: bundle check --path=vendor/bundle || bundle install --path=vendor/bundle --jobs=4 --retry=3
15
+ - type: cache-save
16
+ key: gemfile-{{ checksum "muffin.gemspec" }}
17
+ paths:
18
+ - vendor/bundle
19
+ - type: shell
20
+ name: Run Tests
21
+ command: bundle exec rspec --format documentation
22
+ - type: shell
23
+ name: Lint Code
24
+ command: bundle exec rubocop
data/lib/muffin.rb ADDED
@@ -0,0 +1,8 @@
1
+ require "active_support"
2
+ require "active_support/core_ext"
3
+ require "muffin/version"
4
+
5
+ module Muffin
6
+ require_relative "./muffin/base"
7
+ require_relative "./muffin/rails/controller_additions"
8
+ end
@@ -0,0 +1,49 @@
1
+ module Muffin
2
+ class Attribute
3
+ def initialize(name:, type:, array:, default:, permit:, permitted_values:, block:)
4
+ array = true if array == nil && (type&.is_a?(Array) || block)
5
+ array ||= false
6
+ type = type.first if type&.is_a? Array
7
+ @name = name
8
+ @type = type
9
+ @array = array
10
+ @default = default
11
+ @permit = permit
12
+ @permitted_values = permitted_values
13
+ end
14
+
15
+ attr_reader :name, :type, :default, :permit, :permitted_values
16
+
17
+ def array?
18
+ @array
19
+ end
20
+
21
+ def coercise(value)
22
+ convert value
23
+ end
24
+
25
+ private
26
+
27
+ def convert(value, access_array: false)
28
+ return convert(default) if value == nil && default
29
+ return (value || []).map { |e| convert(e, access_array: true) } if array? && !access_array
30
+ if type <= Integer
31
+ value&.to_i
32
+ elsif type <= Float
33
+ value&.to_f
34
+ elsif type <= String
35
+ value&.to_s
36
+ elsif type <= Symbol
37
+ value.class <= Integer ? value.to_s.to_sym : value&.to_sym
38
+ elsif type <= BigDecimal
39
+ type.new(value) if value.present?
40
+ elsif type <= Hash
41
+ type.new.merge!(value&.to_h&.deep_dup) if value.present?
42
+ elsif type <= Muffin::Boolean
43
+ type.new(value).to_bool
44
+ else
45
+ type.new(value || {})
46
+ end
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,29 @@
1
+ require_relative "frostings/attributes"
2
+ require_relative "frostings/validation"
3
+ require_relative "frostings/execution"
4
+ require_relative "frostings/policy"
5
+ require_relative "frostings/sync"
6
+
7
+ module Muffin
8
+ class Base
9
+ include ActiveModel::Conversion
10
+ include ActiveModel::Naming
11
+ include Attributes
12
+ include Validation
13
+ include Execution
14
+ include Policy
15
+ include Sync
16
+
17
+ attr_reader :request, :params, :scope
18
+
19
+ validates_with Muffin::Validation::NestedAttributesValidator
20
+
21
+ def initialize(request: nil, params: nil, scope: nil)
22
+ @request = request
23
+ @params = params || {}
24
+ @scope = scope
25
+
26
+ assign_attributes
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,20 @@
1
+ module Muffin
2
+ class Boolean
3
+ def initialize(value)
4
+ @value = value
5
+ end
6
+
7
+ attr_reader :value
8
+
9
+ def to_bool
10
+ case value
11
+ when nil
12
+ nil
13
+ when "0", "false"
14
+ false
15
+ else
16
+ !!value
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,4 @@
1
+ module Muffin
2
+ class NotPermittedError < StandardError
3
+ end
4
+ end
@@ -0,0 +1,81 @@
1
+ require_relative "../attribute"
2
+ require_relative "../boolean"
3
+ require_relative "policy"
4
+ require_relative "validation"
5
+
6
+ module Muffin
7
+ module Attributes
8
+ module ClassMethods
9
+ def attribute(name, type = String, default: nil, array: nil, permit: nil, permitted_values: nil, &block)
10
+ type = define_class name, block if block
11
+ attributes[name] = Muffin::Attribute.new name: name, type: type, default: default, array: array, permit: permit, permitted_values: permitted_values, block: block
12
+ define_method name do
13
+ attributes && attributes[name]
14
+ end
15
+ define_method "#{name}=" do |value|
16
+ @attributes ||= {}
17
+ value = self.class.attributes[name].coercise(value)
18
+ attributes[name] = value if permit_attribute!(name, value)
19
+ end
20
+ end
21
+
22
+ def attributes
23
+ @attributes ||= {}
24
+ end
25
+
26
+ def introspect(name)
27
+ attributes[name]
28
+ end
29
+
30
+ private
31
+
32
+ def define_class(name, block)
33
+ class_name = name.to_s.split("_").map(&:capitalize).join
34
+ return const_get class_name if const_defined? class_name
35
+ klass = const_set class_name, Class.new(Muffin::NestedAttribute)
36
+ klass.instance_eval(&block)
37
+ klass
38
+ end
39
+ end
40
+
41
+ attr_reader :attributes
42
+
43
+ def attributes=(value)
44
+ self.class.attributes.keys.map { |e| [e, nil] }.to_h.merge(value.to_h).each do |k, v|
45
+ send("#{k}=", v) if self.class.attributes[k.to_sym]
46
+ end
47
+ end
48
+
49
+ def assign_attributes
50
+ self.attributes = params
51
+ end
52
+
53
+ def self.included(base)
54
+ base.extend ClassMethods
55
+ end
56
+
57
+ def persisted?
58
+ attributes[:id].present?
59
+ end
60
+
61
+ # fields_for checks wether an object responds to [foo_attributes=]
62
+ def respond_to_missing?(method_name, include_private = false)
63
+ return true if method_name.to_s[/_attributes=\Z/]
64
+ super
65
+ end
66
+
67
+ Boolean = Muffin::Boolean.freeze
68
+ end
69
+
70
+ class NestedAttribute
71
+ include Attributes
72
+ include Policy
73
+ include Validation
74
+
75
+ validates_with Muffin::Validation::NestedAttributesValidator
76
+
77
+ def initialize(attributes)
78
+ self.attributes = attributes
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,15 @@
1
+ module Muffin
2
+ module Execution
3
+ def call
4
+ return false unless valid?
5
+ permit!
6
+ perform if respond_to? :perform
7
+ end
8
+
9
+ def call!
10
+ validate!
11
+ permit!
12
+ perform if respond_to? :perform
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,52 @@
1
+ require_relative "../error"
2
+
3
+ module Muffin
4
+ module Policy
5
+ module ClassMethods
6
+ attr_reader :permission_block
7
+
8
+ def permitted?(&block)
9
+ @permission_block = block
10
+ end
11
+ end
12
+
13
+ def permit!
14
+ raise NotPermittedError unless permitted?
15
+ end
16
+
17
+ def permitted?
18
+ return true unless self.class.permission_block
19
+ instance_eval(&self.class.permission_block)
20
+ end
21
+
22
+ def attribute_permitted?(name)
23
+ block = self.class.attributes[name]&.permit
24
+ return instance_exec(&block) if block
25
+ true
26
+ end
27
+
28
+ def permit_attribute!(name, value)
29
+ return false unless attribute_permitted?(name)
30
+ permitted = attribute_value_permitted?(name, value)
31
+ return false if value == nil && !permitted
32
+ raise NotPermittedError unless permitted
33
+ true
34
+ end
35
+
36
+ def permitted_values(name)
37
+ block = self.class.attributes[name]&.permitted_values
38
+ return instance_exec(&block) if block
39
+ nil
40
+ end
41
+
42
+ def attribute_value_permitted?(name, value)
43
+ block = self.class.attributes[name]&.permitted_values
44
+ return true unless block
45
+ instance_exec(&block).include? value
46
+ end
47
+
48
+ def self.included(base)
49
+ base.extend ClassMethods
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,47 @@
1
+ module Muffin
2
+ module Sync
3
+ private
4
+
5
+ def update_nested!(relation, entities = [self])
6
+ entities = Array.wrap(entities)
7
+
8
+ # load all (available) records upfront to avoid fetching them one by one in the loop
9
+ records = (relation.is_a?(ActiveRecord::Base) ? relation.class : relation)
10
+ .where(id: entities.map(&:id).compact)
11
+ .each_with_object({}) { |record, hash| hash[record.id] = record }
12
+
13
+ entities.each do |entity|
14
+ association_attributes = {}
15
+ model_attributes = {}
16
+ record = nil
17
+
18
+ entity.attributes.except(:_destroy).each do |k, v|
19
+ if Array.wrap(v).any? { |e| e.is_a?(Muffin::NestedAttribute) }
20
+ association_attributes[k] = v
21
+ else
22
+ model_attributes[k] = v
23
+ end
24
+ end
25
+
26
+ if entity.try(:id).presence
27
+ record = records[entity.id]
28
+
29
+ if entity.try(:_destroy).presence
30
+ record.destroy
31
+ else
32
+ record.assign_attributes(model_attributes)
33
+ record.save! if record.changed?
34
+ end
35
+ else
36
+ record = relation.create!(model_attributes)
37
+ end
38
+
39
+ association_attributes.each do |k, v|
40
+ update_nested!(record.send(k), v)
41
+ end
42
+ end
43
+
44
+ relation.reload # avoid caching effects like "stale" attributes after updates
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,29 @@
1
+ require "active_model"
2
+
3
+ module Muffin
4
+ module Validation
5
+ class NestedAttributesValidator < ActiveModel::Validator
6
+ def validate(entity)
7
+ entity.attributes.try(:each) do |k, v|
8
+ Array.wrap(v).each do |e|
9
+ if e.is_a?(Muffin::NestedAttribute)
10
+ e.validate
11
+ entity.errors[k] << :nested_validation_failed if e.errors.present?
12
+ end
13
+ end
14
+ end
15
+ end
16
+ end
17
+
18
+ def self.included(base)
19
+ base.include ActiveModel::Validations
20
+ end
21
+
22
+ def required_attributes
23
+ @required_attributes ||= self.class.validators
24
+ .select { |e| e.is_a? ActiveModel::Validations::PresenceValidator }
25
+ .flat_map(&:attributes)
26
+ .uniq
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,29 @@
1
+ module Muffin
2
+ module Rails
3
+ SCOPE_ACCESSOR = :operation_auth_scope
4
+
5
+ module ControllerAdditions
6
+ def prepare(operation, params: nil, request: nil, scope: nil)
7
+ if params.blank? && respond_to?(:params) && operation.respond_to?(:model_name)
8
+ if self.params.key?(operation.model_name.underscore)
9
+ params = self.params[operation.model_name.underscore].deep_dup.permit!.to_h
10
+ params.deep_transform_keys! do |key|
11
+ if key.to_s[/.+_attributes\Z/]
12
+ new_key = key.to_s.sub(/_attributes\Z/, "")
13
+ key.is_a?(Symbol) ? new_key.to_sym : new_key
14
+ else
15
+ key
16
+ end
17
+ end
18
+ end
19
+ end
20
+
21
+ request ||= try(:request)
22
+
23
+ scope ||= try(Muffin::Rails::SCOPE_ACCESSOR) || try(:current_user)
24
+
25
+ operation.new(params: params, request: request, scope: scope)
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,3 @@
1
+ module Muffin
2
+ VERSION = "0.2.0".freeze
3
+ end
data/muffin.gemspec ADDED
@@ -0,0 +1,25 @@
1
+ # coding: utf-8
2
+
3
+ lib = File.expand_path("../lib", __FILE__)
4
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5
+ require "muffin/version"
6
+
7
+ Gem::Specification.new do |spec|
8
+ spec.name = "muffin"
9
+ spec.version = Muffin::VERSION
10
+ spec.authors = ["Jens Ravens", "Michael Sievers"]
11
+ spec.email = ["jens@nerdgeschoss.de", "michael@nerdgeschoss.de"]
12
+
13
+ spec.summary = "Simple operations with optional icing on top."
14
+ spec.homepage = "https://github.com/nerdgeschoss/muffin"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
18
+ f.match(%r{^(test|spec|features)/})
19
+ end
20
+
21
+ spec.require_paths = ["lib"]
22
+
23
+ spec.add_dependency "activemodel"
24
+ spec.add_dependency "activesupport"
25
+ end
metadata ADDED
@@ -0,0 +1,100 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: muffin
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ platform: ruby
6
+ authors:
7
+ - Jens Ravens
8
+ - Michael Sievers
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2017-07-26 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: activemodel
16
+ requirement: !ruby/object:Gem::Requirement
17
+ requirements:
18
+ - - ">="
19
+ - !ruby/object:Gem::Version
20
+ version: '0'
21
+ type: :runtime
22
+ prerelease: false
23
+ version_requirements: !ruby/object:Gem::Requirement
24
+ requirements:
25
+ - - ">="
26
+ - !ruby/object:Gem::Version
27
+ version: '0'
28
+ - !ruby/object:Gem::Dependency
29
+ name: activesupport
30
+ requirement: !ruby/object:Gem::Requirement
31
+ requirements:
32
+ - - ">="
33
+ - !ruby/object:Gem::Version
34
+ version: '0'
35
+ type: :runtime
36
+ prerelease: false
37
+ version_requirements: !ruby/object:Gem::Requirement
38
+ requirements:
39
+ - - ">="
40
+ - !ruby/object:Gem::Version
41
+ version: '0'
42
+ description:
43
+ email:
44
+ - jens@nerdgeschoss.de
45
+ - michael@nerdgeschoss.de
46
+ executables: []
47
+ extensions: []
48
+ extra_rdoc_files: []
49
+ files:
50
+ - ".editorconfig"
51
+ - ".gitignore"
52
+ - ".rspec"
53
+ - ".rubocop.yml"
54
+ - CODE_OF_CONDUCT.md
55
+ - Gemfile
56
+ - Guardfile
57
+ - LICENSE.txt
58
+ - README.md
59
+ - Rakefile
60
+ - bin/console
61
+ - bin/setup
62
+ - circle.yml
63
+ - lib/muffin.rb
64
+ - lib/muffin/attribute.rb
65
+ - lib/muffin/base.rb
66
+ - lib/muffin/boolean.rb
67
+ - lib/muffin/error.rb
68
+ - lib/muffin/frostings/attributes.rb
69
+ - lib/muffin/frostings/execution.rb
70
+ - lib/muffin/frostings/policy.rb
71
+ - lib/muffin/frostings/sync.rb
72
+ - lib/muffin/frostings/validation.rb
73
+ - lib/muffin/rails/controller_additions.rb
74
+ - lib/muffin/version.rb
75
+ - muffin.gemspec
76
+ homepage: https://github.com/nerdgeschoss/muffin
77
+ licenses:
78
+ - MIT
79
+ metadata: {}
80
+ post_install_message:
81
+ rdoc_options: []
82
+ require_paths:
83
+ - lib
84
+ required_ruby_version: !ruby/object:Gem::Requirement
85
+ requirements:
86
+ - - ">="
87
+ - !ruby/object:Gem::Version
88
+ version: '0'
89
+ required_rubygems_version: !ruby/object:Gem::Requirement
90
+ requirements:
91
+ - - ">="
92
+ - !ruby/object:Gem::Version
93
+ version: '0'
94
+ requirements: []
95
+ rubyforge_project:
96
+ rubygems_version: 2.6.8
97
+ signing_key:
98
+ specification_version: 4
99
+ summary: Simple operations with optional icing on top.
100
+ test_files: []