Class: JsonApiResource::Resource

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Conversions

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

Constructor Details

#initialize(opts = {}) ⇒ Resource

Returns a new instance of Resource.



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

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

  self.attributes = opts
  self.errors = ActiveModel::Errors.new(self)
  self.populate_missing_fields
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



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

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)
    connection.execute( method, *args ).data
  else
    super
  end
end

Instance Attribute Details

#cache_expires_inObject

Returns the value of attribute cache_expires_in.



28
29
30
# File 'lib/json_api_resource/resource.rb', line 28

def cache_expires_in
  @cache_expires_in
end

#clientObject

Returns the value of attribute client.



28
29
30
# File 'lib/json_api_resource/resource.rb', line 28

def client
  @client
end

Instance Method Details

#attributes=(attr = {}) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
# File 'lib/json_api_resource/resource.rb', line 49

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 ||= self.client_class.new(self.schema)
    self.client.attributes = attr
  end
end

#new_record?Boolean

Returns:



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

def new_record?
  self.id.nil?
end

#persisted?Boolean

Returns:



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

def persisted?
  !new_record?
end