Class: JsonApiResource::Resource

Inherits:
Object
  • Object
show all
Extended by:
ActiveModel::Callbacks, ActiveSupport::Callbacks
Includes:
ActiveModel::Model, ActiveModel::Validations, Cacheable, Clientable, Conversions, Queryable, Requestable, Schemable
Defined in:
lib/json_api_resource/resource.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Cacheable

#cache_key

Methods included from Conversions

#ApiErrors, #ApiResource, #Boolean, #Date, #DateTime

Constructor Details

#initialize(opts = {}) ⇒ Resource

Returns a new instance of Resource.



31
32
33
34
35
36
37
# File 'lib/json_api_resource/resource.rb', line 31

def initialize(opts={})
  raise( JsonApiResourceError, class: self.class, message: "A resource must have a client class" ) unless client_class.present?

  self.client = self.client_class.new(self.schema)
  self.errors = ActiveModel::Errors.new(self)
  self.attributes = opts
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object (protected)



60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/json_api_resource/resource.rb', line 60

def method_missing(method, *args, &block)
  if match = method.to_s.match(/^(.*=)$/)
    self.client.send(match[0], args.first)
  elsif self.client.respond_to?(method.to_sym)
    self.client.send(method, *args)
  else
    super
  end

rescue JsonApiClient::Errors::ServerError => e
  add_error e
rescue ArgumentError => e
  raise JsonApiResourceError, class: self.class, message: "#{method}: #{e.message}"
end

Instance Attribute Details

#cache_expires_inObject

Returns the value of attribute cache_expires_in.



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

def cache_expires_in
  @cache_expires_in
end

#clientObject

Returns the value of attribute client.



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

def client
  @client
end

Instance Method Details

#attributes=(attr = {}) ⇒ Object



47
48
49
50
51
52
53
54
55
56
# File 'lib/json_api_resource/resource.rb', line 47

def attributes=(attr = {})
  client_params = attr.delete(:client)
  if attr.is_a? self.client_class
    self.client = attr
  elsif client_params
    self.client = client_params
  else
    self.client.attributes = attr
  end
end

#new_record?Boolean

Returns:



39
40
41
# File 'lib/json_api_resource/resource.rb', line 39

def new_record?
  self.id.nil?
end

#persisted?Boolean

Returns:



43
44
45
# File 'lib/json_api_resource/resource.rb', line 43

def persisted?
  !new_record?
end