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, #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, #identifier_hash, #links_hash, #parse_for_includes, #self_link_path, #to_hash

Constructor Details

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

Returns a new instance of Resource.



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

def initialize(model, options={})
  options.stringify_keys!
  @_model = model
  @includes = Array.wrap(options.fetch('include', [])).map(&:to_s)
  build_object_graph # base module method
end

Instance Attribute Details

#_modelObject

Returns the value of attribute _model.



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

def _model
  @_model
end

#includesObject (readonly)

Returns the value of attribute includes.



47
48
49
# File 'lib/json_api_ruby/resource.rb', line 47

def includes
  @includes
end

Class Method Details

.inherited(subclass) ⇒ Object



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

def self.inherited(subclass)
  subclass.send(:id_field, :id)
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


41
42
43
# File 'lib/json_api_ruby/resource.rb', line 41

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