diff options
Diffstat (limited to 'activemodel/lib/active_model/type')
-rw-r--r-- | activemodel/lib/active_model/type/immutable_string.rb | 28 | ||||
-rw-r--r-- | activemodel/lib/active_model/type/string.rb | 28 |
2 files changed, 36 insertions, 20 deletions
diff --git a/activemodel/lib/active_model/type/immutable_string.rb b/activemodel/lib/active_model/type/immutable_string.rb new file mode 100644 index 0000000000..cfa4b3fb4b --- /dev/null +++ b/activemodel/lib/active_model/type/immutable_string.rb @@ -0,0 +1,28 @@ +module ActiveModel + module Type + class ImmutableString < Value # :nodoc: + def type + :string + end + + def serialize(value) + case value + when ::Numeric, ActiveSupport::Duration then value.to_s + when true then "t" + when false then "f" + else super + end + end + + private + + def cast_value(value) + case value + when true then "t" + when false then "f" + else value.to_s.freeze + end + end + end + end +end diff --git a/activemodel/lib/active_model/type/string.rb b/activemodel/lib/active_model/type/string.rb index fd1630c751..4c8dc15778 100644 --- a/activemodel/lib/active_model/type/string.rb +++ b/activemodel/lib/active_model/type/string.rb @@ -1,34 +1,22 @@ +require "active_model/type/immutable_string" + module ActiveModel module Type - class String < Value # :nodoc: - def type - :string - end - + class String < ImmutableString # :nodoc: def changed_in_place?(raw_old_value, new_value) if new_value.is_a?(::String) raw_old_value != new_value end end - def serialize(value) - case value - when ::Numeric, ActiveSupport::Duration then value.to_s - when ::String then ::String.new(value) - when true then "t" - when false then "f" - else super - end - end - private def cast_value(value) - case value - when true then "t" - when false then "f" - # String.new is slightly faster than dup - else ::String.new(value.to_s) + result = super + if ::String === result + ::String.new(result) + else + result end end end |