module ActiveModel::Attributes::ClassMethods

Public Instance Methods

attribute(name, type = Type::Value.new, **options) click to toggle source
# File lib/active_model/attributes.rb, line 18
def attribute(name, type = Type::Value.new, **options)
  name = name.to_s
  if type.is_a?(Symbol)
    type = ActiveModel::Type.lookup(type, **options.except(:default))
  end
  self.attribute_types = attribute_types.merge(name => type)
  define_default_attribute(name, options.fetch(:default, NO_DEFAULT_PROVIDED), type)
  define_attribute_method(name)
end

Private Instance Methods

define_default_attribute(name, value, type) click to toggle source
# File lib/active_model/attributes.rb, line 47
def define_default_attribute(name, value, type)
  self._default_attributes = _default_attributes.deep_dup
  if value == NO_DEFAULT_PROVIDED
    default_attribute = _default_attributes[name].with_type(type)
  else
    default_attribute = Attribute::UserProvidedDefault.new(
      name,
      value,
      type,
      _default_attributes.fetch(name.to_s) { nil },
    )
  end
  _default_attributes[name] = default_attribute
end
define_method_attribute=(name) click to toggle source
# File lib/active_model/attributes.rb, line 30
        def define_method_attribute=(name)
          safe_name = name.unpack("h*".freeze).first
          ActiveModel::AttributeMethods::AttrNames.set_name_cache safe_name, name

          generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
            def __temp__#{safe_name}=(value)
              name = ::ActiveModel::AttributeMethods::AttrNames::ATTR_#{safe_name}
              write_attribute(name, value)
            end
            alias_method #{(name + '=').inspect}, :__temp__#{safe_name}=
            undef_method :__temp__#{safe_name}=
          STR
        end