Class: ActiveModelSerializers::Model

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Model, ActiveModel::Serializers::JSON
Defined in:
lib/active_model_serializers/model.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Model

Returns a new instance of Model.



11
12
13
14
15
# File 'lib/active_model_serializers/model.rb', line 11

def initialize(attributes = {})
  @attributes = attributes && attributes.symbolize_keys
  @errors = ActiveModel::Errors.new(self)
  super
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



9
10
11
# File 'lib/active_model_serializers/model.rb', line 9

def attributes
  @attributes
end

#errorsObject (readonly)

Returns the value of attribute errors.



9
10
11
# File 'lib/active_model_serializers/model.rb', line 9

def errors
  @errors
end

Class Method Details

.human_attribute_name(attr, _options = {}) ⇒ Object

The following methods are needed to be minimally implemented for ActiveModel::Errors :nocov:



42
43
44
# File 'lib/active_model_serializers/model.rb', line 42

def self.human_attribute_name(attr, _options = {})
  attr
end

.lookup_ancestorsObject



46
47
48
# File 'lib/active_model_serializers/model.rb', line 46

def self.lookup_ancestors
  [self]
end

Instance Method Details

#cache_keyObject

Defaults to the downcased model name and updated_at



23
24
25
# File 'lib/active_model_serializers/model.rb', line 23

def cache_key
  attributes.fetch(:cache_key) { "#{self.class.name.downcase}/#{id}-#{updated_at.strftime('%Y%m%d%H%M%S%9N')}" }
end

#idObject

Defaults to the downcased model name.



18
19
20
# File 'lib/active_model_serializers/model.rb', line 18

def id
  attributes.fetch(:id) { self.class.name.downcase }
end

#read_attribute_for_serialization(key) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/active_model_serializers/model.rb', line 32

def read_attribute_for_serialization(key)
  if key == :id || key == 'id'
    attributes.fetch(key) { id }
  else
    attributes[key]
  end
end

#updated_atObject

Defaults to the time the serializer file was modified.



28
29
30
# File 'lib/active_model_serializers/model.rb', line 28

def updated_at
  attributes.fetch(:updated_at) { File.mtime(__FILE__) }
end