Module: ActiveModel::Serializer::Attributes::ClassMethods

Defined in:
lib/active_model/serializer/concerns/attributes.rb

Instance Method Summary collapse

Instance Method Details

#_attributesObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

keys of attributes

See Also:

  • Serializer::attribute


64
65
66
# File 'lib/active_model/serializer/concerns/attributes.rb', line 64

def _attributes
  _attributes_data.keys
end

#_attributes_keysObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

maps attribute value to explicit key name

See Also:

  • Serializer::attribute
  • FragmentCache#fragment_serializer


72
73
74
75
76
77
78
# File 'lib/active_model/serializer/concerns/attributes.rb', line 72

def _attributes_keys
  _attributes_data
    .each_with_object({}) do |(key, attr), hash|
      next if key == attr.name
      hash[attr.name] = { key: key }
    end
end

#attribute(attr, options = {}, &block) ⇒ Object

Examples:

class AdminAuthorSerializer < ActiveModel::Serializer
  attributes :id, :recent_edits
  attribute :name, key: :title

  attribute :full_name do
    "#{object.first_name} #{object.last_name}"
  end

  def recent_edits
    object.edits.last(5)
  end


56
57
58
59
# File 'lib/active_model/serializer/concerns/attributes.rb', line 56

def attribute(attr, options = {}, &block)
  key = options.fetch(:key, attr)
  _attributes_data[key] = Attribute.new(attr, options, block)
end

#attributes(*attrs) ⇒ Object

Examples:

class AdminAuthorSerializer < ActiveModel::Serializer
  attributes :id, :name, :recent_edits


36
37
38
39
40
41
42
# File 'lib/active_model/serializer/concerns/attributes.rb', line 36

def attributes(*attrs)
  attrs = attrs.first if attrs.first.class == Array

  attrs.each do |attr|
    attribute(attr)
  end
end

#inherited(base) ⇒ Object



28
29
30
31
# File 'lib/active_model/serializer/concerns/attributes.rb', line 28

def inherited(base)
  super
  base._attributes_data = _attributes_data.dup
end