Skip to content

Commit

Permalink
Update attribute type casting (#141)
Browse files Browse the repository at this point in the history
  • Loading branch information
hopsoft authored Jun 11, 2024
1 parent 464ed30 commit 7722281
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
18 changes: 16 additions & 2 deletions lib/turbo_boost/commands/attribute_set.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Expand Down Expand Up @@ -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
8 changes: 8 additions & 0 deletions test/attribute_set_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 7722281

Please sign in to comment.