Class: Fars::BaseModelSerializer
- Inherits:
-
BaseObjectSerializer
- Object
- BaseObjectSerializer
- Fars::BaseModelSerializer
- Defined in:
- lib/fars/base_model_serializer.rb
Overview
Class: BaseModelSerializer
Naming convention: <Name of Model, singular!>Serializer
Ways to use:
- create new instance, call to_json
- create new instance, add objects to serialize one by one.
This lets you reuse it without determining known data
Class Method Summary collapse
-
.model_methods ⇒ Object
Returns: Array with names of Model methods.
-
.model_relations ⇒ Object
Returns: Array with names of Model relations.
Instance Method Summary collapse
Methods inherited from BaseObjectSerializer
all_attributes, api_version, attributes, #call, #initialize, serializer_methods, #to_json, #with_object
Constructor Details
This class inherits a constructor from Fars::BaseObjectSerializer
Class Method Details
.model_methods ⇒ Object
Returns: Array with names of Model methods. Consists of Symbols Filtrated by #all_attributes
17 18 19 |
# File 'lib/fars/base_model_serializer.rb', line 17 def model_methods @model_methods ||= ((model.attribute_names.map(&:to_sym) | model.instance_methods) - model_relations - serializer_methods) & all_attributes end |
.model_relations ⇒ Object
Returns: Array with names of Model relations. Consists of Symbols. Filtrated by #all_attributes
25 26 27 |
# File 'lib/fars/base_model_serializer.rb', line 25 def model_relations @model_relations ||= (model.reflect_on_all_associations.map { |r| r.name.to_sym } - serializer_methods) & all_attributes end |
Instance Method Details
#as_json ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/fars/base_model_serializer.rb', line 30 def as_json # as we can re-use one class of serializer for # many objects, we need to re-evaluate list # of available_attributes for each of them all_attrs = available_attributes item = {} (requested_model_methods & all_attrs).each do |attr| item[attr] = object.public_send(attr) end (requested_serializer_methods & all_attrs).each do |meth| item[meth] = self.public_send(meth) end (requested_model_relations & all_attrs).each do |rel| item[rel] = serialize_relation(rel) end hash = { root_key => item } hash[:_metadata] = if hash end |