Class: JsonApiResource::Resource

Inherits:
Object
  • Object
show all
Extended by:
ActiveModel::Callbacks, ActiveSupport::Callbacks
Includes:
ActiveModel::Model, ActiveModel::Validations, Associatable, Cacheable, Clientable, Conversions, ErrorHandleable, Errors, 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.



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

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

  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)



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

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.



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

def cache_expires_in
  @cache_expires_in
end

#clientObject

Returns the value of attribute client.



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

def client
  @client
end

Instance Method Details

#attributes=(attr = {}) ⇒ Object



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

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:



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

def new_record?
  self.id.nil?
end

#persisted?Boolean

Returns:



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

def persisted?
  !new_record?
end