Class: JsonApiClient::Resource

Inherits:
Object
  • Object
show all
Extended by:
ActiveModel::Naming, ActiveModel::Translation, Forwardable
Includes:
ActiveModel::Conversion, ActiveModel::Serialization, ActiveModel::Validations, Helpers::Associatable, 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::Associatable

#_cached_associations, #_cached_relationship, #_clear_cached_relationship, #_clear_cached_relationships

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



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/json_api_client/resource.rb', line 315

def initialize(params = {})
  params = params.symbolize_keys
  @persisted = nil
  @destroyed = nil
  self.links = self.class.linker.new(params.delete(:links) || {})
  self.relationships = self.class.relationship_linker.new(self.class, params.delete(:relationships) || {})
  self.attributes = self.class.default_attributes.merge(params)

  setup_default_properties

  self.class.associations.each do |association|
    if params.has_key?(association.attr_name.to_s)
      set_attribute(association.attr_name, params[association.attr_name.to_s])
    end
  end
  self.request_params = self.class.request_params_class.new(self.class)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



534
535
536
537
538
539
540
# File 'lib/json_api_client/resource.rb', line 534

def method_missing(method, *args)
  relationship_definition = relationship_definition_for(method)

  return super unless relationship_definition

  relationship_data_for(method, relationship_definition)
end

Instance Attribute Details

#last_result_setObject

Returns the value of attribute last_result_set.



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

def last_result_set
  @last_result_set
end

Returns the value of attribute links.



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

def links
  @links
end

#relationshipsObject

Returns the value of attribute relationships.



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

def relationships
  @relationships
end

#request_paramsObject

Returns the value of attribute request_params.



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

def request_params
  @request_params
end

Class Method Details

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

Return/build a connection object

Returns:

  • (Connection)

    The connection to the json api server



107
108
109
110
# File 'lib/json_api_client/resource.rb', line 107

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.



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

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



161
162
163
164
165
# File 'lib/json_api_client/resource.rb', line 161

def custom_headers
  return _header_store.to_h if superclass == Object

  superclass.custom_headers.merge(_header_store.to_h)
end

.default_attributesHash

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

Returns:

  • (Hash)

    Default attributes



178
179
180
# File 'lib/json_api_client/resource.rb', line 178

def default_attributes
  {type: type}
end

.key_formatterObject



189
190
191
# File 'lib/json_api_client/resource.rb', line 189

def key_formatter
  JsonApiClient::Formatter.formatter_for(json_key_format)
end

.load(params) ⇒ Resource

Load a resource object from attributes and consider it persisted

Returns:

  • (Resource)

    Persisted resource object



97
98
99
100
101
102
# File 'lib/json_api_client/resource.rb', line 97

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



121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/json_api_client/resource.rb', line 121

def path(params = nil)
  parts = [resource_path]
  if params && _prefix_path.present?
    path_params = params.delete(:path) || params
    parts.unshift(_set_prefix_path(path_params.symbolize_keys))
  else
    parts.unshift(_prefix_path)
  end
  parts.reject!(&:blank?)
  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



116
117
118
# File 'lib/json_api_client/resource.rb', line 116

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



170
171
172
# File 'lib/json_api_client/resource.rb', line 170

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

.resource_nameString

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

Returns:

  • (String)


74
75
76
# File 'lib/json_api_client/resource.rb', line 74

def resource_name
  name.demodulize.underscore
end

.resource_pathString

Specifies the relative path that should be used for this resource; by default, this is inferred from the resource class name.

Returns:

  • (String)

    Resource path



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

def resource_path
  table_name
end

.route_formatterObject



193
194
195
# File 'lib/json_api_client/resource.rb', line 193

def route_formatter
  JsonApiClient::Formatter.formatter_for(route_format)
end

.schemaSchema

Returns the schema for this resource class

Returns:

  • (Schema)

    The schema for this resource class



185
186
187
# File 'lib/json_api_client/resource.rb', line 185

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



67
68
69
# File 'lib/json_api_client/resource.rb', line 67

def table_name
  route_formatter.format(resource_name.pluralize)
end

.typeString

Specifies the JSON API resource type. By default this is inferred from the resource class name.

Returns:

  • (String)

    Resource path



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

def type
  table_name
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



150
151
152
153
154
155
# File 'lib/json_api_client/resource.rb', line 150

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

Instance Method Details

#as_jsonObject



401
402
403
404
405
406
407
408
# File 'lib/json_api_client/resource.rb', line 401

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



392
393
394
395
396
397
398
399
# File 'lib/json_api_client/resource.rb', line 392

def as_json_api(*)
  attributes.slice(:id, :type).tap do |h|
    relationships_for_serialization.tap do |r|
      h[:relationships] = self.class.key_formatter.format_keys(r) unless r.empty?
    end
    h[:attributes] = self.class.key_formatter.format_keys(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



384
385
386
# File 'lib/json_api_client/resource.rb', line 384

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



459
460
461
462
463
464
465
466
467
468
469
470
# File 'lib/json_api_client/resource.rb', line 459

def destroy
  self.last_result_set = self.class.requestor.destroy(self)
  if last_result_set.has_errors?
    fill_errors
    false
  else
    mark_as_destroyed!
    self.relationships.last_result_set = nil
    _clear_cached_relationships
    true
  end
end

#destroyed?Boolean

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

Returns:

  • (Boolean)


370
371
372
# File 'lib/json_api_client/resource.rb', line 370

def destroyed?
  !!@destroyed
end

#inspectObject



472
473
474
# File 'lib/json_api_client/resource.rb', line 472

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

#mark_as_destroyed!Object

Mark the record as destroyed



363
364
365
# File 'lib/json_api_client/resource.rb', line 363

def mark_as_destroyed!
  @destroyed = true
end

#mark_as_persisted!Object

Mark the record as persisted



351
352
353
# File 'lib/json_api_client/resource.rb', line 351

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)


377
378
379
# File 'lib/json_api_client/resource.rb', line 377

def new_record?
  !persisted? && !destroyed?
end

#persisted?Boolean

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

Returns:

  • (Boolean)


358
359
360
# File 'lib/json_api_client/resource.rb', line 358

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

#request_includes(*includes) ⇒ Object



476
477
478
479
# File 'lib/json_api_client/resource.rb', line 476

def request_includes(*includes)
  self.request_params.add_includes(includes)
  self
end

#request_select(*fields) ⇒ Object



486
487
488
489
490
491
492
493
# File 'lib/json_api_client/resource.rb', line 486

def request_select(*fields)
  fields_by_type = fields.extract_options!
  fields_by_type[type.to_sym] = fields if fields.any?
  fields_by_type.each do |field_type, field_names|
    self.request_params.set_fields(field_type, field_names)
  end
  self
end

#reset_request_includes!Object



481
482
483
484
# File 'lib/json_api_client/resource.rb', line 481

def reset_request_includes!
  self.request_params.reset_includes!
  self
end

#reset_request_select!(*resource_types) ⇒ Object



495
496
497
498
499
# File 'lib/json_api_client/resource.rb', line 495

def reset_request_select!(*resource_types)
  resource_types = self.request_params.field_types if resource_types.empty?
  resource_types.each { |resource_type| self.request_params.remove_fields(resource_type) }
  self
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



427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
# File 'lib/json_api_client/resource.rb', line 427

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?
    fill_errors
    false
  else
    self.errors.clear if self.errors
    self.request_params.clear unless self.class.keep_request_params
    mark_as_persisted!
    if updated = last_result_set.first
      self.attributes = updated.attributes
      self.links.attributes = updated.links.attributes
      self.relationships.attributes = updated.relationships.attributes
      self.relationships.last_result_set = last_result_set
      clear_changes_information
      self.relationships.clear_changes_information
      _clear_cached_relationships
    end
    true
  end
end

#set_all_dirty!Object

Mark all attributes for this record as dirty



411
412
413
414
# File 'lib/json_api_client/resource.rb', line 411

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



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

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



337
338
339
340
# File 'lib/json_api_client/resource.rb', line 337

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

#valid?(context = nil) ⇒ Boolean

Returns:

  • (Boolean)


416
417
418
419
# File 'lib/json_api_client/resource.rb', line 416

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