Sha256: 79eb6ece470d0268822b4685425694889799be0c4c192c97ebffb213451cf30b

Contents?: true

Size: 1.49 KB

Versions: 4

Compression:

Stored size: 1.49 KB

Contents

require 'active_record/attribute_set/builder'

module ActiveRecord
  class AttributeSet # :nodoc:
    delegate :keys, to: :initialized_attributes

    def initialize(attributes)
      @attributes = attributes
    end

    def [](name)
      attributes[name] || Attribute.null(name)
    end

    def values_before_type_cast
      attributes.transform_values(&:value_before_type_cast)
    end

    def to_hash
      initialized_attributes.transform_values(&:value)
    end
    alias_method :to_h, :to_hash

    def key?(name)
      attributes.key?(name) && self[name].initialized?
    end

    def fetch_value(name, &block)
      self[name].value(&block)
    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
      @attributes.freeze
      super
    end

    def initialize_dup(_)
      @attributes = attributes.transform_values(&:dup)
      super
    end

    def initialize_clone(_)
      @attributes = attributes.clone
      super
    end

    def reset(key)
      if key?(key)
        write_from_database(key, nil)
      end
    end

    def ensure_initialized(key)
      unless self[key].initialized?
        write_from_database(key, nil)
      end
    end

    protected

    attr_reader :attributes

    private

    def initialized_attributes
      attributes.select { |_, attr| attr.initialized? }
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
activerecord-4.2.0.beta4 lib/active_record/attribute_set.rb
activerecord-4.2.0.beta3 lib/active_record/attribute_set.rb
activerecord-4.2.0.beta2 lib/active_record/attribute_set.rb
activerecord-4.2.0.beta1 lib/active_record/attribute_set.rb