Class: JsonApi::Resource

Inherits:
Object
  • Object
show all
Extended by:
JsonApi::Resources::DSL
Includes:
JsonApi::Resources::Base
Defined in:
lib/json_api_ruby/resource.rb

Instance Attribute Summary collapse

Attributes included from JsonApi::Resources::DSL

#_id_field, #_type, #_use_links, #fields, #relationships

Attributes included from JsonApi::Resources::Base

#relationships

Class Method Summary collapse

Instance Method Summary collapse

Methods included from JsonApi::Resources::DSL

attribute, attributes, has_many, has_one, id_field

Methods included from JsonApi::Resources::Base

#attributes_hash, #build_object_graph, #fields_array, #identifier_hash, #links_hash, #relationships_array, #self_link_path, #to_hash

Constructor Details

#initialize(model, options = {}) ⇒ Resource

Returns a new instance of Resource.



61
62
63
64
65
66
# File 'lib/json_api_ruby/resource.rb', line 61

def initialize(model, options={})
  options.stringify_keys!
  @_model = model
  @includes = options.fetch('include', Includes.new)
  build_object_graph # base module method
end

Instance Attribute Details

#_modelObject

The model that is used to fill out the data and attributes objects



54
55
56
# File 'lib/json_api_ruby/resource.rb', line 54

def _model
  @_model
end

#includesObject (readonly)

Includes can be passed in from a request See:

http://jsonapi.org/format/#fetching-includes


59
60
61
# File 'lib/json_api_ruby/resource.rb', line 59

def includes
  @includes
end

Class Method Details

.inherited(subclass) ⇒ Object



9
10
11
12
# File 'lib/json_api_ruby/resource.rb', line 9

def self.inherited(subclass)
  subclass.id_field(@_id_field || :id)
  subclass.use_links(@_use_links || JsonApi.configuration.use_links)
end

Instance Method Details

#idObject

Can be set using ‘id_field` in the created resource class like so:

class ObjectResource < JsonApi::Resource
  id_field :uuid
end

defaults to :id



21
22
23
# File 'lib/json_api_ruby/resource.rb', line 21

def id
  object.public_send(self.class._id_field).to_s
end

#objectObject

Makes the underlying object available to subclasses so we can do things like

class PersonResource < JsonApi::Resource
  attribute :email
  attribute :full_name

  def full_name
    "#{object.first_name} #{object.last_name}"
  end
end


49
50
51
# File 'lib/json_api_ruby/resource.rb', line 49

def object
  _model
end

#typeObject

Can be overridden in a subclass



26
27
28
29
30
31
32
# File 'lib/json_api_ruby/resource.rb', line 26

def type
  if self.class._type
    self.class._type
  else
    @type ||= _model.class.to_s.underscore.pluralize
  end
end


34
35
36
# File 'lib/json_api_ruby/resource.rb', line 34

def use_links
  self.class._use_links
end