Class: AbcJsonapi::Relationship
- Inherits:
-
Object
- Object
- AbcJsonapi::Relationship
- Defined in:
- lib/abc_jsonapi/relationship.rb
Instance Attribute Summary collapse
-
#block ⇒ Object
readonly
Returns the value of attribute block.
-
#model ⇒ Object
readonly
Returns the value of attribute model.
-
#relationship ⇒ Object
readonly
Returns the value of attribute relationship.
-
#type ⇒ Object
readonly
Returns the value of attribute type.
Instance Method Summary collapse
-
#initialize(model:, relationship:, type:, block:) ⇒ Relationship
constructor
A new instance of Relationship.
- #serializable_hash ⇒ Object
- #serialize_belongs_to ⇒ Object
- #serialize_has_many ⇒ Object
- #serialize_has_one ⇒ Object
Constructor Details
#initialize(model:, relationship:, type:, block:) ⇒ Relationship
Returns a new instance of Relationship.
5 6 7 8 9 10 |
# File 'lib/abc_jsonapi/relationship.rb', line 5 def initialize(model:, relationship:, type:, block:) @model = model @relationship = relationship @type = type @block = block end |
Instance Attribute Details
#block ⇒ Object (readonly)
Returns the value of attribute block.
3 4 5 |
# File 'lib/abc_jsonapi/relationship.rb', line 3 def block @block end |
#model ⇒ Object (readonly)
Returns the value of attribute model.
3 4 5 |
# File 'lib/abc_jsonapi/relationship.rb', line 3 def model @model end |
#relationship ⇒ Object (readonly)
Returns the value of attribute relationship.
3 4 5 |
# File 'lib/abc_jsonapi/relationship.rb', line 3 def relationship @relationship end |
#type ⇒ Object (readonly)
Returns the value of attribute type.
3 4 5 |
# File 'lib/abc_jsonapi/relationship.rb', line 3 def type @type end |
Instance Method Details
#serializable_hash ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/abc_jsonapi/relationship.rb', line 12 def serializable_hash case type when :has_one { data: serialize_has_one } when :has_many { data: serialize_has_many } when :belongs_to { data: serialize_belongs_to } else { data: nil } end end |
#serialize_belongs_to ⇒ Object
45 46 47 48 49 50 51 52 |
# File 'lib/abc_jsonapi/relationship.rb', line 45 def serialize_belongs_to data = {} id = model.public_send("#{relationship}_id") return if id.blank? data[:id] = id.to_s data[:type] = Helpers.pluralize_if_necessary(relationship.to_s).to_sym data end |
#serialize_has_many ⇒ Object
34 35 36 37 38 39 40 41 42 43 |
# File 'lib/abc_jsonapi/relationship.rb', line 34 def serialize_has_many rels = block.present? ? block.call(model) : model.public_send(relationship) data = rels.map do |relation| { id: relation.id.to_s, type: Helpers.pluralize_if_necessary(relationship.to_s).to_sym } end data end |
#serialize_has_one ⇒ Object
25 26 27 28 29 30 31 32 |
# File 'lib/abc_jsonapi/relationship.rb', line 25 def serialize_has_one data = {} rel = model.public_send(relationship) return if rel.nil? data[:id] = rel.id.to_s data[:type] = Helpers.pluralize_if_necessary(relationship.to_s).to_sym data end |