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 19
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
attribute_names() click to toggle source

Returns an array of attribute names as strings

class Person
  include ActiveModel::Attributes

  attribute :name, :string
  attribute :age, :integer
end

Person.attribute_names
# => ["name", "age"]
# File lib/active_model/attributes.rb, line 40
def attribute_names
  attribute_types.keys
end

Private Instance Methods

define_default_attribute(name, value, type) click to toggle source
# File lib/active_model/attributes.rb, line 59
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, owner:) click to toggle source
# File lib/active_model/attributes.rb, line 45
def define_method_attribute=(name, owner:)
  ActiveModel::AttributeMethods::AttrNames.define_attribute_accessor_method(
    owner, name, writer: true,
  ) do |temp_method_name, attr_name_expr|
    owner <<
      "def #{temp_method_name}(value)" <<
      "  _write_attribute(#{attr_name_expr}, value)" <<
      "end"
  end
end