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.



128
129
130
# File 'lib/jsonapi/resource.rb', line 128

def _allowed_filters
  @_allowed_filters
end

._associationsObject

Returns the value of attribute _associations.



128
129
130
# File 'lib/jsonapi/resource.rb', line 128

def _associations
  @_associations
end

._attributesObject

Returns the value of attribute _attributes.



128
129
130
# File 'lib/jsonapi/resource.rb', line 128

def _attributes
  @_attributes
end

._typeObject

Returns the value of attribute _type.



128
129
130
# File 'lib/jsonapi/resource.rb', line 128

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)


332
333
334
# File 'lib/jsonapi/resource.rb', line 332

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

._as_parent_keyObject



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

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

._association(type) ⇒ Object



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

def _association(type)
  type = type.to_sym
  @_associations[type]
end

._attribute_options(attr) ⇒ Object

quasi private class methods



272
273
274
# File 'lib/jsonapi/resource.rb', line 272

def _attribute_options(attr)
  default_attribute_options.merge(@_attributes[attr])
end

._has_association?(type) ⇒ Boolean

Returns:

  • (Boolean)


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

def _has_association?(type)
  type = type.to_s
  @_associations.has_key?(type.singularize.to_sym) || @_associations.has_key?(type.pluralize.to_sym)
end

._keyObject



301
302
303
# File 'lib/jsonapi/resource.rb', line 301

def _key
  @_key ||= :id
end

._model_nameObject



297
298
299
# File 'lib/jsonapi/resource.rb', line 297

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

._resource_name_from_type(type) ⇒ Object



313
314
315
316
317
318
319
320
# File 'lib/jsonapi/resource.rb', line 313

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

._updateable_associationsObject



276
277
278
279
280
281
282
283
284
285
# File 'lib/jsonapi/resource.rb', line 276

def _updateable_associations
  associations = []

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

.attribute(attr, options = {}) ⇒ Object



145
146
147
148
149
150
151
152
153
154
# File 'lib/jsonapi/resource.rb', line 145

def attribute(attr, options = {})
  @_attributes[attr] = options
  define_method attr do
    @object.send(attr)
  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



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

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

.createable_fields(context) ⇒ Object

Override in your resource to filter the createable keys



190
191
192
# File 'lib/jsonapi/resource.rb', line 190

def createable_fields(context)
  _updateable_associations | _attributes.keys
end

.default_attribute_optionsObject



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

def default_attribute_options
  {format: :default}
end

.fieldsObject



194
195
196
# File 'lib/jsonapi/resource.rb', line 194

def fields
  _associations.keys | _attributes.keys
end

.filter(attr) ⇒ Object



176
177
178
# File 'lib/jsonapi/resource.rb', line 176

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

.filters(*attrs) ⇒ Object



172
173
174
# File 'lib/jsonapi/resource.rb', line 172

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



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/jsonapi/resource.rb', line 199

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)
        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



224
225
226
227
228
229
230
# File 'lib/jsonapi/resource.rb', line 224

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



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

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

.has_one(*attrs) ⇒ Object



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

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

.inherited(base) ⇒ Object



115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/jsonapi/resource.rb', line 115

def inherited(base)
  base._attributes = (_attributes || {}).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)


241
242
243
# File 'lib/jsonapi/resource.rb', line 241

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

.key(key) ⇒ Object



180
181
182
# File 'lib/jsonapi/resource.rb', line 180

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

.model_name(model) ⇒ Object



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

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

.routing_options(options) ⇒ Object



130
131
132
# File 'lib/jsonapi/resource.rb', line 130

def routing_options(options)
  @_routing_resource_options = options
end

.routing_resource_optionsObject



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

def routing_resource_options
  @_routing_resource_options ||= {}
end

.updateable_fields(context) ⇒ Object

Override in your resource to filter the updateable keys



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

def updateable_fields(context)
  _updateable_associations | _attributes.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



267
268
269
# File 'lib/jsonapi/resource.rb', line 267

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

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

override to allow for custom filters



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

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

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



245
246
247
248
249
250
251
252
253
254
# File 'lib/jsonapi/resource.rb', line 245

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



232
233
234
235
236
237
238
239
# File 'lib/jsonapi/resource.rb', line 232

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



257
258
259
# File 'lib/jsonapi/resource.rb', line 257

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

Instance Method Details

#_model_classObject



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

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


25
26
27
28
29
30
31
32
33
34
35
36
# 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.type).find_by_key(association_key_value, context)

  # ToDo: Add option to skip relations that already exist instead of returning an error?
  relation = @object.send(association.type).where(association.primary_key => association_key_value).first
  if relation.nil?
    @object.send(association.type) << related_resource.object
  else
    raise JSONAPI::Exceptions::HasManyRelationExists.new(association_key_value)
  end
end


44
45
46
47
48
49
50
51
52
53
54
# File 'lib/jsonapi/resource.rb', line 44

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

  # ToDo: Add option to skip relations that already exist instead of returning an error?
  relation = @object.send("#{association.key}")
  if relation.nil?
    @object.send("#{association.key}=", association_key_value)
  else
    raise JSONAPI::Exceptions::HasOneRelationExists.new
  end
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_fields(context) ⇒ Object

Override this on a resource instance to override the fetchable keys



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

def fetchable_fields(context)
  self.class.fields
end

#remove(context) ⇒ Object



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

def remove(context)
  @object.destroy
end


62
63
64
65
66
# File 'lib/jsonapi/resource.rb', line 62

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

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


68
69
70
71
72
# File 'lib/jsonapi/resource.rb', line 68

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



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

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


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

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


56
57
58
59
60
# File 'lib/jsonapi/resource.rb', line 56

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

#save(context) ⇒ Object



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

def save(context)
  @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