Skip to content

Commit

Permalink
Update attribute type casting
Browse files Browse the repository at this point in the history
  • Loading branch information
hopsoft committed Jun 10, 2024
1 parent 464ed30 commit 76df081
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 "integer type coercion with leading 0" do
attributes = {test_a: "00000"}
attrs = TurboBoost::Commands::AttributeSet.new(attributes, prefix: :test)
assert attrs.a?
assert attrs.a.is_a? String
assert_equal "00000", attrs.a
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 76df081

Please sign in to comment.