Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Call Object#method if method accessor is called with arguments #595

Merged
merged 1 commit into from
Oct 16, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -423,5 +423,17 @@ class StripeObjectTest < Test::Unit::TestCase
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