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, #_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.



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

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



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

def _model
  @_model
end

#includesObject (readonly)

Includes can be passed in from a request See:

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


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

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


45
46
47
# File 'lib/json_api_ruby/resource.rb', line 45

def object
  _model
end

#typeObject

Can be overridden in a subclass



26
27
28
# File 'lib/json_api_ruby/resource.rb', line 26

def type
  _model.class.to_s.underscore.pluralize
end


30
31
32
# File 'lib/json_api_ruby/resource.rb', line 30

def use_links
  self.class._use_links
end