diff options
Diffstat (limited to 'activerecord/lib/active_record/attribute_set.rb')
-rw-r--r-- | activerecord/lib/active_record/attribute_set.rb | 54 |
1 files changed, 37 insertions, 17 deletions
diff --git a/activerecord/lib/active_record/attribute_set.rb b/activerecord/lib/active_record/attribute_set.rb index 102ef17e16..65e15b16dd 100644 --- a/activerecord/lib/active_record/attribute_set.rb +++ b/activerecord/lib/active_record/attribute_set.rb @@ -1,13 +1,42 @@ +require 'active_record/attribute_set/builder' + module ActiveRecord class AttributeSet # :nodoc: - delegate :[], :[]=, :fetch, :include?, :keys, :each_with_object, to: :attributes + delegate :[], to: :attributes + delegate :keys, to: :initialized_attributes def initialize(attributes) @attributes = attributes end - def update(other) - attributes.update(other.attributes) + def values_before_type_cast + attributes.each_with_object({}) { |(k, v), h| h[k] = v.value_before_type_cast } + end + + def to_hash + initialized_attributes.each_with_object({}) { |(k, v), h| h[k] = v.value } + end + alias_method :to_h, :to_hash + + def include?(name) + attributes.include?(name) && self[name].initialized? + end + + def fetch_value(name) + attribute = self[name] + if attribute.initialized? || !block_given? + attribute.value + else + yield name + end + end + + def write_from_database(name, value) + attributes[name] = self[name].with_value_from_database(value) + end + + def write_from_user(name, value) + attributes[name] = self[name].with_value_from_user(value) end def freeze @@ -29,23 +58,14 @@ module ActiveRecord super end - class Builder - def initialize(types) - @types = types - end - - def build_from_database(values, additional_types = {}) - attributes = values.each_with_object({}) do |(name, value), hash| - type = additional_types.fetch(name, @types[name]) - hash[name] = Attribute.from_database(value, type) - end - AttributeSet.new(attributes) - end - end - protected attr_reader :attributes + private + + def initialized_attributes + attributes.select { |_, attr| attr.initialized? } + end end end |