Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update attribute type casting #141

Merged
merged 2 commits into from
Jun 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading