Skip to content

Commit

Permalink
Allow adding permitted args on each level of form inheritance
Browse files Browse the repository at this point in the history
Using `class_attrubute :_permitted_args` instead of @_permitted_args = ...
allows inheriting value of `_permitted_args` from a parent form,
and then adding permitted args in a child form.
  • Loading branch information
kryzhovnik committed Apr 12, 2022
1 parent 52d0cc4 commit a36a807
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 5 deletions.
11 changes: 6 additions & 5 deletions lib/active_form_model/permittable.rb
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
# frozen_string_literal: true

require 'active_support/deprecation'
require 'active_support/core_ext/class/attribute'

module ActiveFormModel
module Permittable
extend ActiveSupport::Concern

included do
class_attribute(:_permitted_args, instance_predicate: false, default: [])
end

class_methods do
def new(attrs = nil, &block)
attrs = _permit_attrs(attrs) if attrs
Expand All @@ -14,16 +19,12 @@ def new(attrs = nil, &block)
end

def permit(*args)
@_permitted_args = args
self._permitted_args = _permitted_args | args
end

alias_method :fields, :permit
deprecate fields: :permit, deprecator: ActiveSupport::Deprecation.new('0.6.0', 'ActiveFormModel')

def _permitted_args
@_permitted_args || (superclass.respond_to?(:_permitted_args) && superclass._permitted_args) || []
end

def _permit_attrs(attrs)
attrs.respond_to?(:permit) ? attrs.send(:permit, _permitted_args) : attrs
end
Expand Down
6 changes: 6 additions & 0 deletions test/active_form_model_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ def test_permitted_attrs_for_assign_attributes
assert { @form.valid_attribute == :one }
end

def test_permitted_attrs_for_inhereted_form
@form = UnsafeUserForm.new(@params)
assert { @form.valid_attribute == :one }
assert { @form.invalid_attribute == :two }
end

# def test_permitted_attrs_for_update!
# @form = UserForm.new
# @form.update!(@params)
Expand Down
5 changes: 5 additions & 0 deletions test/support/unsafe_user_form.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# frozen_string_literal: true

class UnsafeUserForm < UserForm
permit :invalid_attribute
end
1 change: 1 addition & 0 deletions test/test_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

require_relative 'support/user'
require_relative 'support/user_form'
require_relative 'support/unsafe_user_form'
require_relative 'support/admin'
require_relative 'support/admin_form'
require_relative 'support/sign_in_form'
Expand Down

0 comments on commit a36a807

Please sign in to comment.