Class: JsonApiClient::Resource

Inherits:
Object
  • Object
show all
Extended by:
ActiveModel::Naming, ActiveModel::Translation, Forwardable
Includes:
ActiveModel::Conversion, ActiveModel::Serialization, ActiveModel::Validations, Associations::BelongsTo, Associations::HasMany, Associations::HasOne, Helpers::Dirty, Helpers::DynamicAttributes
Defined in:
lib/json_api_client/resource.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Helpers::Dirty

#attribute_change, #attribute_changed?, #attribute_was, #attribute_will_change!, #changed, #changed?, #changed_attributes, #clear_changes_information, #set_all_attributes_dirty, #set_attribute_was

Methods included from Helpers::DynamicAttributes

#[], #[]=, #attributes, #attributes=

Constructor Details

#initialize(params = {}) ⇒ Resource

Instantiate a new resource object

Parameters:

  • params (Hash) (defaults to: {})

    Attributes, links, and relationships



260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/json_api_client/resource.rb', line 260

def initialize(params = {})
  self.links = self.class.linker.new(params.delete("links") || {})
  self.relationships = self.class.relationship_linker.new(params.delete("relationships") || {})
  self.class.associations.each do |association|
    if params.has_key?(association.attr_name.to_s)
      set_attribute(association.attr_name, association.parse(params[association.attr_name.to_s]))
    end
  end
  self.attributes = params.merge(self.class.default_attributes)
  self.class.schema.each_property do |property|
    attributes[property.name] = property.default unless attributes.has_key?(property.name) || property.default.nil?
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'lib/json_api_client/resource.rb', line 405

def method_missing(method, *args)
  association = association_for(method)

  return super unless association || (relationships && relationships.has_attribute?(method))

  return nil unless relationship_definitions = relationships[method]

  # look in included data
  data = last_result_set.included.data_for(method, relationship_definitions)
  return data if data

  if association = association_for(method)
    # look for a defined relationship url
    if relationship_definitions["links"] && url = relationship_definitions["links"]["related"]
      return association.data(url)
    end
  end
  nil
end

Instance Attribute Details

#last_result_setObject

Returns the value of attribute last_result_set.



16
17
18
# File 'lib/json_api_client/resource.rb', line 16

def last_result_set
  @last_result_set
end

Returns the value of attribute links.



16
17
18
# File 'lib/json_api_client/resource.rb', line 16

def links
  @links
end

#relationshipsObject

Returns the value of attribute relationships.



16
17
18
# File 'lib/json_api_client/resource.rb', line 16

def relationships
  @relationships
end

Class Method Details

.connection(rebuild = false, &block) ⇒ Connection

Return/build a connection object

Returns:

  • (Connection)

    The connection to the json api server



80
81
82
83
# File 'lib/json_api_client/resource.rb', line 80

def connection(rebuild = false, &block)
  _build_connection(rebuild, &block)
  connection_object
end

.create(attributes = {}) ⇒ Resource

Create a new instance of this resource class

Parameters:

  • attributes (Hash) (defaults to: {})

    The attributes to create this resource with

Returns:

  • (Resource)

    The instance you tried to create. You will have to check the persisted state or errors on this object to see success/failure.



112
113
114
115
116
# File 'lib/json_api_client/resource.rb', line 112

def create(attributes = {})
  new(attributes).tap do |resource|
    resource.save
  end
end

.custom_headersHash

The current custom headers to send with any request made by this resource class

Returns:

  • (Hash)

    Headers



134
135
136
# File 'lib/json_api_client/resource.rb', line 134

def custom_headers
  _header_store.to_h
end

.default_attributesHash

Default attributes that every instance of this resource should be intialized with. Optionally, override this method in a subclass.

Returns:

  • (Hash)

    Default attributes



149
150
151
# File 'lib/json_api_client/resource.rb', line 149

def default_attributes
  {type: table_name}
end

.load(params) ⇒ Resource

Load a resource object from attributes and consider it persisted

Returns:

  • (Resource)

    Persisted resource object



70
71
72
73
74
75
# File 'lib/json_api_client/resource.rb', line 70

def load(params)
  new(params).tap do |resource|
    resource.mark_as_persisted!
    resource.clear_changes_information
  end
end

.path(params = nil) ⇒ Object

Return the path or path pattern for this resource



94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/json_api_client/resource.rb', line 94

def path(params = nil)
  parts = [table_name]
  if params
    path_params = params.delete(:path) || params
    parts.unshift(_prefix_path % path_params.symbolize_keys)
  else
    parts.unshift(_prefix_path)
  end
  parts.reject!{|part| part == "" }
  File.join(*parts)
rescue KeyError
  raise ArgumentError, "Not all prefix parameters specified"
end

.prefix_paramsArray

Param names that will be considered path params. They will be used to build the resource path rather than treated as attributes

Returns:

  • (Array)

    Param name symbols of parameters that will be treated as path parameters



89
90
91
# File 'lib/json_api_client/resource.rb', line 89

def prefix_params
  _belongs_to_associations.map(&:param)
end

.requestorRequestor

Returns the requestor for this resource class

Returns:

  • (Requestor)

    The requestor for this resource class



141
142
143
# File 'lib/json_api_client/resource.rb', line 141

def requestor
  @requestor ||= requestor_class.new(self)
end

.resource_nameString

The name of a single resource. i.e. Article -> article, Person -> person

Returns:

  • (String)


63
64
65
# File 'lib/json_api_client/resource.rb', line 63

def resource_name
  name.demodulize.underscore
end

.schemaSchema

Returns the schema for this resource class

Returns:

  • (Schema)

    The schema for this resource class



156
157
158
# File 'lib/json_api_client/resource.rb', line 156

def schema
  @schema ||= Schema.new
end

.table_nameString

The table name for this resource. i.e. Article -> articles, Person -> people

Returns:

  • (String)

    The table name for this resource



56
57
58
# File 'lib/json_api_client/resource.rb', line 56

def table_name
  resource_name.pluralize
end

.with_headers(headers) ⇒ Object

Within the given block, add these headers to all requests made by the resource class

Parameters:

  • headers (Hash)

    The headers to send along

  • block (Block)

    The block where headers will be set for



123
124
125
126
127
128
# File 'lib/json_api_client/resource.rb', line 123

def with_headers(headers)
  self._custom_headers = headers
  yield
ensure
  self._custom_headers = {}
end

Instance Method Details

#as_jsonObject



330
331
332
333
334
335
336
337
# File 'lib/json_api_client/resource.rb', line 330

def as_json(*)
  attributes.slice(:id, :type).tap do |h|
    relationships.as_json.tap do |r|
      h[:relationships] = r unless r.empty?
    end
    h[:attributes] = attributes.except(:id, :type).as_json
  end
end

#as_json_apiHash

When we represent this resource for serialization (create/update), we do so with this implementation

Returns:

  • (Hash)

    Representation of this object as JSONAPI object



321
322
323
324
325
326
327
328
# File 'lib/json_api_client/resource.rb', line 321

def as_json_api(*)
  attributes.slice(:id, :type).tap do |h|
    relationships_for_serialization.tap do |r|
      h[:relationships] = r unless r.empty?
    end
    h[:attributes] = attributes_for_serialization
  end
end

#as_relationHash

When we represent this resource as a relationship, we do so with id & type

Returns:

  • (Hash)

    Representation of this object as a relation



313
314
315
# File 'lib/json_api_client/resource.rb', line 313

def as_relation
  attributes.slice(:type, self.class.primary_key)
end

#destroyBoolean

Try to destroy this resource

Returns:

  • (Boolean)

    Whether or not the destroy succeeded



389
390
391
392
393
394
395
396
397
# File 'lib/json_api_client/resource.rb', line 389

def destroy
  self.last_result_set = self.class.requestor.destroy(self)
  if !last_result_set.has_errors?
    self.attributes.clear
    true
  else
    false
  end
end

#inspectObject



399
400
401
# File 'lib/json_api_client/resource.rb', line 399

def inspect
  "#<#{self.class.name}:@attributes=#{attributes.inspect}>"
end

#mark_as_persisted!Object

Mark the record as persisted



292
293
294
# File 'lib/json_api_client/resource.rb', line 292

def mark_as_persisted!
  @persisted = true
end

#new_record?Boolean

Returns true if this is a new record (never persisted to the database)

Returns:

  • (Boolean)


306
307
308
# File 'lib/json_api_client/resource.rb', line 306

def new_record?
  !persisted?
end

#persisted?Boolean

Whether or not this record has been persisted to the database previously

Returns:

  • (Boolean)


299
300
301
# File 'lib/json_api_client/resource.rb', line 299

def persisted?
  !!@persisted && has_attribute?(self.class.primary_key)
end

#saveBoolean

Commit the current changes to the resource to the remote server. If the resource was previously loaded from the server, we will try to update the record. Otherwise if it’s a new record, then we will try to create it

Returns:

  • (Boolean)

    Whether or not the save succeeded



356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
# File 'lib/json_api_client/resource.rb', line 356

def save
  return false unless valid?

  self.last_result_set = if persisted?
    self.class.requestor.update(self)
  else
    self.class.requestor.create(self)
  end

  if last_result_set.has_errors?
    last_result_set.errors.each do |error|
      if error.source_parameter
        errors.add(error.source_parameter, error.title)
      else
        errors.add(:base, error.title)
      end
    end
    false
  else
    self.errors.clear if self.errors
    mark_as_persisted!
    if updated = last_result_set.first
      self.attributes = updated.attributes
      self.relationships.attributes = updated.relationships.attributes
      clear_changes_information
    end
    true
  end
end

#set_all_dirty!Object

Mark all attributes for this record as dirty



340
341
342
343
# File 'lib/json_api_client/resource.rb', line 340

def set_all_dirty!
  set_all_attributes_dirty
  relationships.set_all_attributes_dirty if relationships
end

#update(attrs = {}) ⇒ Boolean

Alias to update_attributes

Parameters:

  • attrs (Hash) (defaults to: {})

    Attributes to update

Returns:

  • (Boolean)

    Whether the update succeeded or not



287
288
289
# File 'lib/json_api_client/resource.rb', line 287

def update(attrs = {})
  update_attributes(attrs)
end

#update_attributes(attrs = {}) ⇒ Boolean

Set the current attributes and try to save them

Parameters:

  • attrs (Hash) (defaults to: {})

    Attributes to update

Returns:

  • (Boolean)

    Whether the update succeeded or not



278
279
280
281
# File 'lib/json_api_client/resource.rb', line 278

def update_attributes(attrs = {})
  self.attributes = attrs
  save
end

#valid?(context = nil) ⇒ Boolean

Returns:

  • (Boolean)


345
346
347
348
# File 'lib/json_api_client/resource.rb', line 345

def valid?(context = nil)
  context ||= (new_record? ? :create : :update)
  super(context)
end