diff --git a/lib/turbo_boost/commands/attribute_set.rb b/lib/turbo_boost/commands/attribute_set.rb index 8759b64a..652cd248 100644 --- a/lib/turbo_boost/commands/attribute_set.rb +++ b/lib/turbo_boost/commands/attribute_set.rb @@ -21,8 +21,8 @@ def initialize(attributes = {}, prefix: nil) name.delete_prefix!("#{prefix}_") unless prefix.blank? # type casting - value = value.to_i if value.is_a?(String) && value.match?(/\A-?\d+\z/) - value = value == "true" if value.is_a?(String) && value.match?(/\A(true|false)\z/i) + value = value.to_i if cast_to_integer?(value) + value = value == "true" if cast_to_boolean?(value) begin next if instance_variable_defined?(:"@#{name}") @@ -75,4 +75,18 @@ def method_missing(name, *args) return false if name.end_with?("?") nil end + + private + + def cast_to_integer?(value) + return false unless value.is_a?(String) + return false unless value.match?(/\A-?\d+\z/) + return false if value.size > 1 && value.start_with?("0") + true + end + + def cast_to_boolean?(value) + return false unless value.is_a?(String) + value.match?(/\A(true|false)\z/i) + end end diff --git a/test/attribute_set_test.rb b/test/attribute_set_test.rb index 532c3ae2..70f5b96c 100644 --- a/test/attribute_set_test.rb +++ b/test/attribute_set_test.rb @@ -36,6 +36,14 @@ class AttributeSetTest < ActiveSupport::TestCase assert_equal 54872, attrs.a end + test "type coercion with number containg a leading 0 remains a string" do + attributes = {test: "00000"} + attrs = TurboBoost::Commands::AttributeSet.new(attributes) + assert attrs.test? + assert attrs.test.is_a? String + assert_equal "00000", attrs.test + end + test "implicit hydration" do attributes = {test_a: "value", data: {locals: {user: User.first}}}.with_indifferent_access dehydrated = dehydrate(attributes)