Class: JSONAPI::Serializable::Resource

Inherits:
Object
  • Object
show all
Extended by:
DSL
Defined in:
lib/jsonapi/serializable/resource.rb,
lib/jsonapi/serializable/resource/dsl.rb,
lib/jsonapi/serializable/resource/key_format.rb,
lib/jsonapi/serializable/resource/conditional_fields.rb

Defined Under Namespace

Modules: ConditionalFields, DSL, KeyFormat

Instance Method Summary collapse

Methods included from DSL

attribute, attributes, extended, id, inherited, link, meta, relationship, type

Constructor Details

#initialize(exposures = {}) ⇒ Resource

rubocop:disable Metrics/AbcSize, Metrics/MethodLength


20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/jsonapi/serializable/resource.rb', line 20

def initialize(exposures = {})
  @_exposures = {
    _resource_builder: JSONAPI::Serializable::ResourceBuilder.new
  }.merge(exposures)
  @_exposures.each { |k, v| instance_variable_set("@#{k}", v) }

  @_id = instance_eval(&self.class.id_block).to_s
  @_type = if (b = self.class.type_block)
             instance_eval(&b).to_sym
           else
             self.class.type_val || :unknown
           end
  @_attributes = {}
  @_relationships = self.class.relationship_blocks
                        .each_with_object({}) do |(k, v), h|
    opts = self.class.relationship_options[k] || {}
    h[k] = Relationship.new(@_exposures, opts, &v)
  end
  @_links = self.class.link_blocks.each_with_object({}) do |(k, v), h|
    h[k] = Link.as_jsonapi(@_exposures, &v)
  end
  @_meta = if (b = self.class.meta_block)
             instance_eval(&b)
           else
             self.class.meta_val
           end

  freeze
end

Instance Method Details

#as_jsonapi(fields: nil, include: []) ⇒ Object

rubocop:disable Metrics/AbcSize, Metrics/MethodLength


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/jsonapi/serializable/resource.rb', line 52

def as_jsonapi(fields: nil, include: [])
  attrs = requested_attributes(fields).each_with_object({}) do |(k, v), h|
    h[k] = instance_eval(&v)
  end
  rels = requested_relationships(fields)
         .each_with_object({}) do |(k, v), h|
    h[k] = v.as_jsonapi(include.include?(k))
  end
  {}.tap do |hash|
    hash[:id]   = @_id
    hash[:type] = @_type
    hash[:attributes]    = attrs if attrs.any?
    hash[:relationships] = rels  if rels.any?
    hash[:links] = @_links if @_links.any?
    hash[:meta]  = @_meta  unless @_meta.nil?
  end
end

#jsonapi_idObject


75
76
77
# File 'lib/jsonapi/serializable/resource.rb', line 75

def jsonapi_id
  @_id
end

79
80
81
82
83
# File 'lib/jsonapi/serializable/resource.rb', line 79

def jsonapi_related(include)
  @_relationships
    .select { |k, _| include.include?(k) }
    .each_with_object({}) { |(k, v), h| h[k] = v.related_resources }
end

#jsonapi_typeObject

rubocop:enable Metrics/AbcSize, Metrics/MethodLength


71
72
73
# File 'lib/jsonapi/serializable/resource.rb', line 71

def jsonapi_type
  @_type
end