Class: JSONAPI::Resource

Inherits:
Object
  • Object
show all
Includes:
ResourceFor
Defined in:
lib/jsonapi/resource.rb

Constant Summary collapse

@@resource_types =
{}

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ResourceFor

included

Constructor Details

#initialize(object = create_new_object) ⇒ Resource

Returns a new instance of Resource.



13
14
15
# File 'lib/jsonapi/resource.rb', line 13

def initialize(object = create_new_object)
  @object = object
end

Class Attribute Details

._allowed_filtersObject

Returns the value of attribute _allowed_filters.



110
111
112
# File 'lib/jsonapi/resource.rb', line 110

def _allowed_filters
  @_allowed_filters
end

._associationsObject

Returns the value of attribute _associations.



110
111
112
# File 'lib/jsonapi/resource.rb', line 110

def _associations
  @_associations
end

._attributesObject

Returns the value of attribute _attributes.



110
111
112
# File 'lib/jsonapi/resource.rb', line 110

def _attributes
  @_attributes
end

._typeObject

Returns the value of attribute _type.



110
111
112
# File 'lib/jsonapi/resource.rb', line 110

def _type
  @_type
end

Instance Attribute Details

#objectObject (readonly)

Returns the value of attribute object.



11
12
13
# File 'lib/jsonapi/resource.rb', line 11

def object
  @object
end

Class Method Details

._allowed_filter?(filter) ⇒ Boolean

Returns:

  • (Boolean)


353
354
355
# File 'lib/jsonapi/resource.rb', line 353

def _allowed_filter?(filter)
  _allowed_filters.include?(filter.to_sym)
end

._as_parent_keyObject



326
327
328
# File 'lib/jsonapi/resource.rb', line 326

def _as_parent_key
  @_as_parent_key ||= "#{_serialize_as.to_s.singularize}_#{_key}"
end

._association(type) ⇒ Object



309
310
311
312
# File 'lib/jsonapi/resource.rb', line 309

def _association(type)
  type = type.to_sym unless type.is_a?(Symbol)
  @_associations[type]
end

._has_association?(type) ⇒ Boolean

Returns:

  • (Boolean)


305
306
307
# File 'lib/jsonapi/resource.rb', line 305

def _has_association?(type)
  @_associations.has_key?(type)
end

._keyObject



322
323
324
# File 'lib/jsonapi/resource.rb', line 322

def _key
  @_key ||= :id
end

._model_nameObject



314
315
316
# File 'lib/jsonapi/resource.rb', line 314

def _model_name
  @_model_name ||= self.name.demodulize.sub(/Resource$/, '')
end

._resource_name_from_type(type) ⇒ Object



334
335
336
337
338
339
340
341
# File 'lib/jsonapi/resource.rb', line 334

def _resource_name_from_type(type)
  class_name = @@resource_types[type]
  if class_name.nil?
    class_name = type.to_s.singularize.camelize + 'Resource'
    @@resource_types[type] = class_name
  end
  return class_name
end

._serialize_asObject



318
319
320
# File 'lib/jsonapi/resource.rb', line 318

def _serialize_as
  @_serialize_as ||= self._type
end

._updateable_associationsObject

quasi private class methods



294
295
296
297
298
299
300
301
302
303
# File 'lib/jsonapi/resource.rb', line 294

def _updateable_associations
  associations = []

  @_associations.each do |key, association|
    if association.is_a?(JSONAPI::Association::HasOne) || association.treat_as_set
      associations.push(key)
    end
  end
  associations
end

._validate_field(field) ⇒ Object



357
358
359
# File 'lib/jsonapi/resource.rb', line 357

def _validate_field(field)
  _attributes.include?(field) || _associations.key?(field)
end

.attribute(attr) ⇒ Object



128
129
130
131
132
133
134
135
136
137
# File 'lib/jsonapi/resource.rb', line 128

def attribute(attr)
  @_attributes.add attr
  define_method attr do
    @object.method(attr).call
  end unless method_defined?(attr)

  define_method "#{attr}=" do |value|
    @object.send "#{attr}=", value
  end unless method_defined?("#{attr}=")
end

.attributes(*attrs) ⇒ Object

Methods used in defining a resource class



121
122
123
124
125
126
# File 'lib/jsonapi/resource.rb', line 121

def attributes(*attrs)
  @_attributes.merge attrs
  attrs.each do |attr|
    attribute(attr)
  end
end

.createable(keys, context = nil) ⇒ Object

Override in your resource to filter the createable keys



169
170
171
# File 'lib/jsonapi/resource.rb', line 169

def createable(keys, context = nil)
  keys
end

.filter(attr) ⇒ Object



155
156
157
# File 'lib/jsonapi/resource.rb', line 155

def filter(attr)
  @_allowed_filters.add(attr.to_sym)
end

.filters(*attrs) ⇒ Object



151
152
153
# File 'lib/jsonapi/resource.rb', line 151

def filters(*attrs)
  @_allowed_filters.merge(attrs)
end

.find(filters, context = nil) ⇒ Object

Override this method if you have more complex requirements than this basic find method provides



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/jsonapi/resource.rb', line 174

def find(filters, context = nil)
  includes = []
  where_filters = {}

  filters.each do |filter, value|
    if _associations.include?(filter)
      if _associations[filter].is_a?(JSONAPI::Association::HasMany)
        includes.push(filter.to_sym)
        where_filters["#{filter}.#{_associations[filter].primary_key}"] = value
      else
        where_filters["#{_associations[filter].key}"] = value
      end
    else
      where_filters[filter] = value
    end
  end

  resources = []
  _model_class.where(where_filters).includes(includes).each do |object|
    resources.push self.new(object)
  end

  return resources
end

.find_by_key(key, context = nil) ⇒ Object



199
200
201
202
203
204
205
# File 'lib/jsonapi/resource.rb', line 199

def find_by_key(key, context = nil)
  obj = _model_class.where({_key => key}).first
  if obj.nil?
    raise JSONAPI::Exceptions::RecordNotFound.new(key)
  end
  self.new(obj)
end

.has_many(*attrs) ⇒ Object



143
144
145
# File 'lib/jsonapi/resource.rb', line 143

def has_many(*attrs)
  _associate(Association::HasMany, *attrs)
end

.has_one(*attrs) ⇒ Object



139
140
141
# File 'lib/jsonapi/resource.rb', line 139

def has_one(*attrs)
  _associate(Association::HasOne, *attrs)
end

.inherited(base) ⇒ Object



97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/jsonapi/resource.rb', line 97

def inherited(base)
  base._attributes = (_attributes || Set.new).dup
  base._associations = (_associations || {}).dup
  base._allowed_filters = (_allowed_filters || Set.new).dup

  type = base.name.demodulize.sub(/Resource$/, '').underscore
  base._type = type.pluralize.to_sym
  # If eager loading is on this is how all the resource types are setup
  # If eager loading is off some resource types will be initialized in
  # _resource_name_from_type
  @@resource_types[base._type] ||= base.name.demodulize
end

.is_filter_association?(filter) ⇒ Boolean

Returns:

  • (Boolean)


263
264
265
# File 'lib/jsonapi/resource.rb', line 263

def is_filter_association?(filter)
  filter == _serialize_as || _associations.include?(filter)
end

.key(key) ⇒ Object



159
160
161
# File 'lib/jsonapi/resource.rb', line 159

def key(key)
  @_key = key.to_sym
end

.model_name(model) ⇒ Object



147
148
149
# File 'lib/jsonapi/resource.rb', line 147

def model_name(model)
  @_model_name = model.to_sym
end

.routing_options(options) ⇒ Object



112
113
114
# File 'lib/jsonapi/resource.rb', line 112

def routing_options(options)
  @_routing_resource_options = options
end

.routing_resource_optionsObject



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

def routing_resource_options
  @_routing_resource_options ||= {}
end

.updateable(keys, context = nil) ⇒ Object

Override in your resource to filter the updateable keys



164
165
166
# File 'lib/jsonapi/resource.rb', line 164

def updateable(keys, context = nil)
  keys
end

.verify_association_filter(filter, raw, context = nil) ⇒ Object

override to allow for custom association logic, such as uuids, multiple keys or permission checks on keys



289
290
291
# File 'lib/jsonapi/resource.rb', line 289

def verify_association_filter(filter, raw, context = nil)
  return filter, raw
end

.verify_create_params(object_params, context = nil) ⇒ Object



207
208
209
# File 'lib/jsonapi/resource.rb', line 207

def verify_create_params(object_params, context = nil)
  verify_params(object_params, createable(_updateable_associations | _attributes.to_a), context)
end

.verify_custom_filter(filter, value, context = nil) ⇒ Object

override to allow for custom filters



284
285
286
# File 'lib/jsonapi/resource.rb', line 284

def verify_custom_filter(filter, value, context = nil)
  return filter, value
end

.verify_filter(filter, raw, context = nil) ⇒ Object



267
268
269
270
271
272
273
274
275
276
# File 'lib/jsonapi/resource.rb', line 267

def verify_filter(filter, raw, context = nil)
  filter_values = []
  filter_values += CSV.parse_line(raw) unless raw.nil? || raw.empty?

  if is_filter_association?(filter)
    verify_association_filter(filter, filter_values, context)
  else
    verify_custom_filter(filter, filter_values, context)
  end
end

.verify_filters(filters, context = nil) ⇒ Object



254
255
256
257
258
259
260
261
# File 'lib/jsonapi/resource.rb', line 254

def verify_filters(filters, context = nil)
  verified_filters = {}
  filters.each do |filter, raw_value|
    verified_filter = verify_filter(filter, raw_value, context)
    verified_filters[verified_filter[0]] = verified_filter[1]
  end
  verified_filters
end

.verify_key(key, context = nil) ⇒ Object

override to allow for key processing and checking



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

def verify_key(key, context = nil)
  return key
end

.verify_params(object_params, allowed_params, context) ⇒ Object



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/jsonapi/resource.rb', line 215

def verify_params(object_params, allowed_params, context)
  # push links into top level param list with attributes in order to check for invalid params
  if object_params[:links]
    object_params[:links].each do |link, value|
      object_params[link] = value
    end
    object_params.delete(:links)
  end
  verify_permitted_params(object_params, allowed_params)

  checked_attributes = {}
  checked_has_one_associations = {}
  checked_has_many_associations = {}

  object_params.each do |key, value|
    param = key.to_sym

    association = _associations[param]

    if association.is_a?(JSONAPI::Association::HasOne)
      checked_has_one_associations[param.to_sym] = resource_for(association.serialize_type_name).verify_key(value, context)
    elsif association.is_a?(JSONAPI::Association::HasMany)
      keys = []
      value.each do |value|
        keys.push(resource_for(association.serialize_type_name).verify_key(value, context))
      end
      checked_has_many_associations[param.to_sym] = keys
    else
      checked_attributes[param] = value
    end
  end

  return {
      attributes: checked_attributes,
      has_one: checked_has_one_associations,
      has_many: checked_has_many_associations
  }
end

.verify_update_params(object_params, context = nil) ⇒ Object



211
212
213
# File 'lib/jsonapi/resource.rb', line 211

def verify_update_params(object_params, context = nil)
  verify_params(object_params, updateable(_updateable_associations | _attributes.to_a), context)
end

Instance Method Details

#_model_classObject



344
345
346
# File 'lib/jsonapi/resource.rb', line 344

def _model_class
  @model ||= Object.const_get(_model_name)
end


25
26
27
28
29
30
# File 'lib/jsonapi/resource.rb', line 25

def create_has_many_link(association_type, association_key_value, context)
  association = self.class._associations[association_type]
  related_resource = self.class.resource_for(association.serialize_type_name).find_by_key(association_key_value, context)

  @object.send(association.serialize_type_name) << related_resource.object
end

#create_new_objectObject



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

def create_new_object
  self.class._model_class.new
end

#fetchable(keys, context = nil) ⇒ Object

Override this on a resource instance to override the fetchable keys



92
93
94
# File 'lib/jsonapi/resource.rb', line 92

def fetchable(keys, context = nil)
  keys
end

#remove(context) ⇒ Object



21
22
23
# File 'lib/jsonapi/resource.rb', line 21

def remove(context)
  @object.destroy
end


44
45
46
47
48
# File 'lib/jsonapi/resource.rb', line 44

def remove_has_many_link(association_type, key, context)
  association = self.class._associations[association_type]

  @object.send(association.serialize_type_name).delete(key)
end


50
51
52
53
54
# File 'lib/jsonapi/resource.rb', line 50

def remove_has_one_link(association_type, context)
  association = self.class._associations[association_type]

  @object.send("#{association.key}=", nil)
end

#replace_fields(field_data, context) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/jsonapi/resource.rb', line 56

def replace_fields(field_data, context)
  field_data[:attributes].each do |attribute, value|
    send "#{attribute}=", value
  end

  field_data[:has_one].each do |association_type, value|
    if value.nil?
      remove_has_one_link(association_type, context)
    else
      replace_has_one_link(association_type, value, context)
    end
  end if field_data[:has_one]

  field_data[:has_many].each do |association_type, values|
    replace_has_many_links(association_type, values, context)
  end if field_data[:has_many]
end


32
33
34
35
36
# File 'lib/jsonapi/resource.rb', line 32

def replace_has_many_links(association_type, association_key_values, context)
  association = self.class._associations[association_type]

  @object.send("#{association.key}=", association_key_values)
end


38
39
40
41
42
# File 'lib/jsonapi/resource.rb', line 38

def replace_has_one_link(association_type, association_key_value, context)
  association = self.class._associations[association_type]

  @object.send("#{association.key}=", association_key_value)
end

#saveObject



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/jsonapi/resource.rb', line 74

def save
  @object.save!
rescue ActiveRecord::RecordInvalid => e
  errors = []
  e.record.errors.messages.each do |element|
    element[1].each do |message|
      errors.push(JSONAPI::Error.new(
                      code: JSONAPI::VALIDATION_ERROR,
                      status: :bad_request,
                      title: "#{element[0]} - #{message}",
                      detail: "can't be blank",
                      path: "\\#{element[0]}"))
    end
  end
  raise JSONAPI::Exceptions::ValidationErrors.new(errors)
end