mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
c81af6ae72
We sometimes say "✂️ newline after `private`" in a code review (e.g. https://github.com/rails/rails/pull/18546#discussion_r23188776, https://github.com/rails/rails/pull/34832#discussion_r244847195). Now `Layout/EmptyLinesAroundAccessModifier` cop have new enforced style `EnforcedStyle: only_before` (https://github.com/rubocop-hq/rubocop/pull/7059). That cop and enforced style will reduce the our code review cost.
104 lines
2.2 KiB
Ruby
104 lines
2.2 KiB
Ruby
# frozen_string_literal: true
|
|
|
|
require "active_support/core_ext/object/deep_dup"
|
|
require "active_model/attribute_set/builder"
|
|
require "active_model/attribute_set/yaml_encoder"
|
|
|
|
module ActiveModel
|
|
class AttributeSet # :nodoc:
|
|
delegate :each_value, :fetch, :except, to: :attributes
|
|
|
|
def initialize(attributes)
|
|
@attributes = attributes
|
|
end
|
|
|
|
def [](name)
|
|
attributes[name] || Attribute.null(name)
|
|
end
|
|
|
|
def []=(name, value)
|
|
attributes[name] = value
|
|
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 keys
|
|
attributes.each_key.select { |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 write_cast_value(name, value)
|
|
attributes[name] = self[name].with_cast_value(value)
|
|
end
|
|
|
|
def freeze
|
|
@attributes.freeze
|
|
super
|
|
end
|
|
|
|
def deep_dup
|
|
self.class.allocate.tap do |copy|
|
|
copy.instance_variable_set(:@attributes, attributes.deep_dup)
|
|
end
|
|
end
|
|
|
|
def initialize_dup(_)
|
|
@attributes = attributes.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 accessed
|
|
attributes.select { |_, attr| attr.has_been_read? }.keys
|
|
end
|
|
|
|
def map(&block)
|
|
new_attributes = attributes.transform_values(&block)
|
|
AttributeSet.new(new_attributes)
|
|
end
|
|
|
|
def ==(other)
|
|
attributes == other.attributes
|
|
end
|
|
|
|
protected
|
|
attr_reader :attributes
|
|
|
|
private
|
|
def initialized_attributes
|
|
attributes.select { |_, attr| attr.initialized? }
|
|
end
|
|
end
|
|
end
|