Skip to content

Commit 7722281

Browse files
authored
Update attribute type casting (#141)
1 parent 464ed30 commit 7722281

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

lib/turbo_boost/commands/attribute_set.rb

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@ def initialize(attributes = {}, prefix: nil)
2121
name.delete_prefix!("#{prefix}_") unless prefix.blank?
2222

2323
# type casting
24-
value = value.to_i if value.is_a?(String) && value.match?(/\A-?\d+\z/)
25-
value = value == "true" if value.is_a?(String) && value.match?(/\A(true|false)\z/i)
24+
value = value.to_i if cast_to_integer?(value)
25+
value = value == "true" if cast_to_boolean?(value)
2626

2727
begin
2828
next if instance_variable_defined?(:"@#{name}")
@@ -75,4 +75,18 @@ def method_missing(name, *args)
7575
return false if name.end_with?("?")
7676
nil
7777
end
78+
79+
private
80+
81+
def cast_to_integer?(value)
82+
return false unless value.is_a?(String)
83+
return false unless value.match?(/\A-?\d+\z/)
84+
return false if value.size > 1 && value.start_with?("0")
85+
true
86+
end
87+
88+
def cast_to_boolean?(value)
89+
return false unless value.is_a?(String)
90+
value.match?(/\A(true|false)\z/i)
91+
end
7892
end

test/attribute_set_test.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,14 @@ class AttributeSetTest < ActiveSupport::TestCase
3636
assert_equal 54872, attrs.a
3737
end
3838

39+
test "type coercion with number containg a leading 0 remains a string" do
40+
attributes = {test: "00000"}
41+
attrs = TurboBoost::Commands::AttributeSet.new(attributes)
42+
assert attrs.test?
43+
assert attrs.test.is_a? String
44+
assert_equal "00000", attrs.test
45+
end
46+
3947
test "implicit hydration" do
4048
attributes = {test_a: "value", data: {locals: {user: User.first}}}.with_indifferent_access
4149
dehydrated = dehydrate(attributes)

0 commit comments

Comments
 (0)