mirror of
https://github.com/stripe/stripe-ruby.git
synced 2025-06-03 00:01:47 -04:00
Add question mark helpers (e.g. #paid?) for boolean object values
This patch adds question marks helpers (e.g. #paid?) for any values in a StripeObject that are a boolean. This is fairly idiomatic Ruby in that it behaves similarly to other libraries like ActiveRecord. Note that a caveat here is that nullable booleans will not get a helper added for them if their current value is null. For this reason, we should eventually prefer to derive these methods from some sort of programmatic API manifest. Replaces #257 and #274.
This commit is contained in:
parent
a6a2664746
commit
c301c6c0f6
@ -47,7 +47,7 @@ module Stripe
|
||||
|
||||
instance_eval do
|
||||
remove_accessors(removed)
|
||||
add_accessors(added)
|
||||
add_accessors(added, values)
|
||||
end
|
||||
|
||||
removed.each do |k|
|
||||
@ -216,7 +216,7 @@ module Stripe
|
||||
end
|
||||
end
|
||||
|
||||
def add_accessors(keys)
|
||||
def add_accessors(keys, values)
|
||||
metaclass.instance_eval do
|
||||
keys.each do |k|
|
||||
next if @@permanent_attributes.include?(k)
|
||||
@ -232,6 +232,11 @@ module Stripe
|
||||
@values[k] = v
|
||||
@unsaved_values.add(k)
|
||||
end
|
||||
|
||||
if [FalseClass, TrueClass].include?(values[k].class)
|
||||
k_bool = :"#{k}?"
|
||||
define_method(k_bool) { @values[k] }
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -240,7 +245,10 @@ module Stripe
|
||||
# TODO: only allow setting in updateable classes.
|
||||
if name.to_s.end_with?('=')
|
||||
attr = name.to_s[0...-1].to_sym
|
||||
add_accessors([attr])
|
||||
|
||||
# the second argument is only required when adding boolean accessors
|
||||
add_accessors([attr], {})
|
||||
|
||||
begin
|
||||
mth = method(name)
|
||||
rescue NameError
|
||||
|
@ -31,5 +31,12 @@ module Stripe
|
||||
expected_hash = { :id => 1, :nested => nested_hash, :list => [nested_hash] }
|
||||
assert_equal expected_hash, obj.to_hash
|
||||
end
|
||||
|
||||
should "assign question mark accessors for booleans" do
|
||||
obj = Stripe::StripeObject.construct_from({ :id => 1, :bool => true, :not_bool => 'bar' })
|
||||
assert obj.respond_to?(:bool?)
|
||||
assert obj.bool?
|
||||
refute obj.respond_to?(:not_bool?)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
Loading…
x
Reference in New Issue
Block a user