Skip to content

Commit

Permalink
Merge pull request #595 from stripe/ob-fix-524
Browse files Browse the repository at this point in the history
Call Object#method if method accessor is called with arguments
  • Loading branch information
brandur-stripe authored Oct 16, 2017
2 parents 517c1f0 + 4406f8e commit cfa6c2b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
11 changes: 10 additions & 1 deletion lib/stripe/stripe_object.rb
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,16 @@ def add_accessors(keys, values)
next if protected_fields.include?(k)
next if @@permanent_attributes.include?(k)

define_method(k) { @values[k] }
if k == :method
# Object#method is a built-in Ruby method that accepts a symbol
# and returns the corresponding Method object. Because the API may
# also use `method` as a field name, we check the arity of *args
# to decide whether to act as a getter or call the parent method.
define_method(k) { |*args| args.empty? ? @values[k] : super(*args) }
else
define_method(k) { @values[k] }
end

define_method(:"#{k}=") do |v|
if v == ""
raise ArgumentError, "You cannot set #{k} to an empty string. " \
Expand Down
12 changes: 12 additions & 0 deletions test/stripe/stripe_object_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -432,5 +432,17 @@ class TestObject < Stripe::StripeObject; end
expected_hash = { api_key: "apikey" }
assert_equal expected_hash, m.instance_variable_get("@opts")
end

context "#method" do
should "act as a getter is not argument is provided" do
obj = Stripe::StripeObject.construct_from(id: 1, method: "foo")
assert_equal "foo", obj.method
end

should "call Object#method if an argument is provided" do
obj = Stripe::StripeObject.construct_from(id: 1, method: "foo")
assert obj.method(:id).is_a?(Method)
end
end
end
end

0 comments on commit cfa6c2b

Please sign in to comment.