Class: Jserializer::Association
- Inherits:
-
Object
- Object
- Jserializer::Association
- Defined in:
- lib/jserializer/association.rb
Instance Attribute Summary collapse
-
#id_only ⇒ Object
readonly
Returns the value of attribute id_only.
-
#relation_type ⇒ Object
readonly
Returns the value of attribute relation_type.
-
#serializer ⇒ Object
readonly
Returns the value of attribute serializer.
Instance Method Summary collapse
-
#access_name ⇒ Object
The method name to access the data of the attribute.
-
#initialize(name, relation_type, key:, serializer:, id_only:, embed_key:) ⇒ Association
constructor
A new instance of Association.
- #key ⇒ Object
- #serialize(record) ⇒ Object
Constructor Details
#initialize(name, relation_type, key:, serializer:, id_only:, embed_key:) ⇒ Association
Returns a new instance of Association.
5 6 7 8 9 10 11 12 |
# File 'lib/jserializer/association.rb', line 5 def initialize(name, relation_type, key:, serializer:, id_only:, embed_key:) @attribute_name = name.to_s @relation_type = relation_type @key = key @serializer = serializer @id_only = id_only || false @embed_key = || :id end |
Instance Attribute Details
#id_only ⇒ Object (readonly)
Returns the value of attribute id_only.
3 4 5 |
# File 'lib/jserializer/association.rb', line 3 def id_only @id_only end |
#relation_type ⇒ Object (readonly)
Returns the value of attribute relation_type.
3 4 5 |
# File 'lib/jserializer/association.rb', line 3 def relation_type @relation_type end |
#serializer ⇒ Object (readonly)
Returns the value of attribute serializer.
3 4 5 |
# File 'lib/jserializer/association.rb', line 3 def serializer @serializer end |
Instance Method Details
#access_name ⇒ Object
The method name to access the data of the attribute
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/jserializer/association.rb', line 25 def access_name return @attribute_name unless @id_only # for simplicity without guessing # the access method is post_ids for posts if associated with has_many # and post.id for post if associated with has_one # This also means for serializing a Hash object with has_one association # It must provide access key like "post.id" to get data case @relation_type when :has_many "#{singularize_attribute_name}_#{@embed_key}s" when :has_one "#{@attribute_name}.#{@embed_key}" else @attribute_name end end |
#key ⇒ Object
14 15 16 17 18 19 20 21 22 |
# File 'lib/jserializer/association.rb', line 14 def key return @key if @key || !@id_only case @relation_type when :has_many :"#{singularize_attribute_name}_ids" when :has_one :"#{@attribute_name}_id" end end |
#serialize(record) ⇒ Object
42 43 44 45 46 47 48 |
# File 'lib/jserializer/association.rb', line 42 def serialize(record) return nil if record.nil? return [] if relation_type == :has_many && record.empty? return serialize_collection(record) if relation_type == :has_many return serialize_one(record) if relation_type == :has_one raise "Unable to serialize association type: #{relation_type}" end |