Skip to content

Commit

Permalink
Defined attribute should not expand positional hash argument
Browse files Browse the repository at this point in the history
  • Loading branch information
kamipo committed Jan 20, 2020
1 parent 482f6d6 commit 72cd217
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
8 changes: 4 additions & 4 deletions activemodel/lib/active_model/attribute_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -364,14 +364,13 @@ def attribute_method_matchers_matching(method_name)
# using the given `extra` args. This falls back on `define_method`
# and `send` if the given names cannot be compiled.
def define_proxy_call(include_private, mod, name, target, *extra)
kw = RUBY_VERSION >= "2.7" ? ", **options" : nil
defn = if NAME_COMPILABLE_REGEXP.match?(name)
"def #{name}(*args#{kw})"
"def #{name}(*args)"
else
"define_method(:'#{name}') do |*args#{kw}|"
"define_method(:'#{name}') do |*args|"
end

extra = (extra.map!(&:inspect) << "*args#{kw}").join(", ")
extra = (extra.map!(&:inspect) << "*args").join(", ")

body = if CALL_COMPILABLE_REGEXP.match?(target)
"#{"self." unless include_private}#{target}(#{extra})"
Expand All @@ -383,6 +382,7 @@ def define_proxy_call(include_private, mod, name, target, *extra)
#{defn}
#{body}
end
ruby2_keywords(:'#{name}') if respond_to?(:ruby2_keywords, true)
RUBY
end

Expand Down
22 changes: 20 additions & 2 deletions activemodel/test/cases/attribute_methods_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ def attribute(name)
attributes[name.to_s]
end

alias attribute_test attribute
def attribute_test(name, attrs = {})
attrs[name] = attribute(name)
end

def private_method
"<3 <3"
Expand Down Expand Up @@ -212,9 +214,25 @@ def foo
test "accessing a suffixed attribute" do
m = ModelWithAttributes2.new
m.attributes = { "foo" => "bar" }
attrs = {}

assert_equal "bar", m.foo
assert_equal "bar", m.foo_test
assert_equal "bar", m.foo_test(attrs)
assert_equal "bar", attrs["foo"]
end

test "defined attribute doesn't expand positional hash argument" do
ModelWithAttributes2.define_attribute_methods(:foo)

m = ModelWithAttributes2.new
m.attributes = { "foo" => "bar" }
attrs = {}

assert_equal "bar", m.foo
assert_equal "bar", m.foo_test(attrs)
assert_equal "bar", attrs["foo"]
ensure
ModelWithAttributes2.undefine_attribute_methods
end

test "should not interfere with method_missing if the attr has a private/protected method" do
Expand Down

0 comments on commit 72cd217

Please sign in to comment.