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.



31
32
33
34
# File 'lib/active_model_serializers/model.rb', line 31

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

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



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

def errors
  @errors
end

#updated_atObject

When no set, defaults to the time the file was modified. See NOTE by attr_writer :updated_at



56
57
58
# File 'lib/active_model_serializers/model.rb', line 56

def updated_at
  defined?(@updated_at) ? @updated_at : File.mtime(__FILE__)
end

Class Method Details

.attributes(*names) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/active_model_serializers/model.rb', line 14

def self.attributes(*names)
  self.attribute_names |= names.map(&:to_sym)
  # Silence redefinition of methods warnings
  ActiveModelSerializers.silence_warnings do
    attr_accessor(*names)
  end
end

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

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



62
63
64
# File 'lib/active_model_serializers/model.rb', line 62

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

.lookup_ancestorsObject



66
67
68
# File 'lib/active_model_serializers/model.rb', line 66

def self.lookup_ancestors
  [self]
end

Instance Method Details

#attributesObject

The the fields in attribute_names determines the returned hash. attributes are returned frozen to prevent any expectations that mutation affects the actual values in the model.



39
40
41
42
43
# File 'lib/active_model_serializers/model.rb', line 39

def attributes
  attribute_names.each_with_object({}) do |attribute_name, result|
    result[attribute_name] = public_send(attribute_name).freeze
  end.with_indifferent_access.freeze
end

#cache_keyObject

To customize model behavior, this method must be redefined. However, there are other ways of setting the cache_key a serializer uses.



47
48
49
50
51
52
# File 'lib/active_model_serializers/model.rb', line 47

def cache_key
  ActiveSupport::Cache.expand_cache_key([
    self.class.model_name.name.downcase,
    "#{id}-#{updated_at.strftime('%Y%m%d%H%M%S%9N')}"
  ].compact)
end