Call Object#method if method accessor is called with arguments

This commit is contained in:
Olivier Bellone 2017-10-14 23:00:40 +02:00
parent f628a1eff5
commit 4406f8e258
No known key found for this signature in database
GPG Key ID: 11E77E3AA0C40303
2 changed files with 22 additions and 1 deletions

View File

@ -241,7 +241,16 @@ module Stripe
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. " \

View File

@ -423,5 +423,17 @@ module Stripe
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