Class: Api::Base

Inherits:
Object
  • Object
show all
Defined in:
app/models/api/base.rb

Class Method Summary collapse

Class Method Details

.attributes_from_json(params) ⇒ Object


229
230
231
# File 'app/models/api/base.rb', line 229

def attributes_from_json(params)
  convert_json_attributes_to_attributes(params[model_class.name.underscore])
end

.convert_json_attributes_to_attributes(json_attributes) ⇒ Object


233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'app/models/api/base.rb', line 233

def convert_json_attributes_to_attributes(json_attributes)
  return {} if json_attributes.blank?

  attributes = {}
  attribute_to_json_attribute_mappings.each do |attribute, json_attribute|
    attributes[attribute] = json_attributes[json_attribute] if json_attributes.key?(json_attribute)
  end
  associations.each do |association, helper|
    if helper.performs_lookup?
      helper.lookup_associated_record_from(json_attributes) do |associated_record|
        attributes[:"#{association}_id"] = associated_record.try(:id)
      end
    else
      association_attributes = helper.convert_json_attributes_to_attributes(json_attributes)
      attributes[:"#{association}_attributes"] = association_attributes unless association_attributes.empty?
    end
  end
  attributes
end

.create!(params) ⇒ Object


12
13
14
# File 'app/models/api/base.rb', line 12

def create!(params)
  model_class.create!(attributes_from_json(params))
end

.default_objectObject

Returns the default object to use (by default this is 'nil') and can be overridden by passing ':if_nil_use => :some_function_that_returns_default_object' to with_association.


161
162
163
# File 'app/models/api/base.rb', line 161

def self.default_object
  nil
end

.extra_json_attributes(&block) ⇒ Object


223
224
225
226
# File 'app/models/api/base.rb', line 223

def self.extra_json_attributes(&block)
  self.extra_json_attribute_handlers = Array.new if extra_json_attribute_handlers.empty?
  extra_json_attribute_handlers.push(block)
end

.json_attribute_for_attribute(attribute_or_association, *rest) ⇒ Object

Raises:

  • (StandardError)

253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'app/models/api/base.rb', line 253

def json_attribute_for_attribute(attribute_or_association, *rest)
  json_attribute = attribute_to_json_attribute_mappings[attribute_or_association.to_sym]
  if json_attribute.blank?
    # If we have reached the end of the line, and the attribute_or_association is for what looks like
    # an association, then we'll look it up without the '_id' and return that value.
    if attribute_or_association.to_s =~ /_id$/ and rest.empty?
      association = associations[attribute_or_association.to_s.sub(/_id$/, '').to_sym]
      raise StandardError, "Unexpected association #{attribute_or_association.inspect}" if association.nil?

      return association.json_attribute_for_attribute(:name)
    end
    json_attribute = associations[attribute_or_association.to_sym].json_attribute_for_attribute(*rest)
  end
  raise StandardError, "Unexpected attribute #{attribute_or_association.inspect} does not appear to be mapped" if json_attribute.blank?

  json_attribute
end

.lookup_associated_record_from(json_attributes) {|association.to_s.classify.constantize.find_by(search_parameters)| ... } ⇒ Object

Yields:

  • (association.to_s.classify.constantize.find_by(search_parameters))

200
201
202
203
204
205
206
# File 'app/models/api/base.rb', line 200

def self.lookup_associated_record_from(json_attributes)
  attributes = convert_json_attributes_to_attributes(json_attributes)
  return unless attributes.key?(lookup_by)

  search_parameters = { lookup_by => attributes[lookup_by] }
  yield(association.to_s.classify.constantize.find_by(search_parameters))
end

.map_attribute_to_json_attribute(attribute, json_attribute = attribute) ⇒ Object

TODO: Need to warn about 'id' not being 'internal_id'


131
132
133
# File 'app/models/api/base.rb', line 131

def self.map_attribute_to_json_attribute(attribute, json_attribute = attribute)
  self.attribute_to_json_attribute_mappings = attribute_to_json_attribute_mappings.merge(attribute.to_sym => json_attribute.to_s)
end

.map_attribute_to_json_attribute_in_errors(attribute_errors) ⇒ Object

Maps the attribute names in the errors to their JSON counterparts, so that the end user gets the correct information.


22
23
24
# File 'app/models/api/base.rb', line 22

def map_attribute_to_json_attribute_in_errors(attribute_errors)
  Hash[attribute_errors.map { |a, v| [json_attribute_for_attribute(*a.to_s.split('.')), v] }]
end

.newer_than(object, timestamp) {|timestamp| ... } ⇒ Object

Yields:

  • (timestamp)

143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'app/models/api/base.rb', line 143

def self.newer_than(object, timestamp)
  return if object.nil? or timestamp.nil?

  modified, object_timestamp = false, ((object.respond_to?(:updated_at) ? object.updated_at : timestamp) || timestamp)
  timestamp, modified = object_timestamp, true if object_timestamp > timestamp
  associations.each do |_association, helper|
    helper.newer_than(helper.target(object), timestamp) { |t| timestamp, modified = t, true }
  end
  nested_has_many_associations.each do |_association, helper|
    helper.target(object).each do |child|
      helper.newer_than(child, timestamp) { |t| timestamp, modified = t, true }
    end
  end
  yield(timestamp) if modified
end

.performs_lookup?Boolean

Returns:

  • (Boolean)

196
197
198
# File 'app/models/api/base.rb', line 196

def self.performs_lookup?
  !!lookup_by
end

.render_class_for_model(model) ⇒ Object

The default behaviour for any model I/O is to write out all of the columns as they appear. Some of the columns are ignored, a few manipulated, but mostly it's a direct copy.


82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'app/models/api/base.rb', line 82

def render_class_for_model(model)
  render_class = Class.new(self)

  # NOTE: It's quite annoying that you don't have any access to the inheritable class attributes from
  # within the Class.new block above, so we have to do a separate instance_eval to get it to work.
  render_class.instance_eval do
    self.model_class = model

    model.column_names.each do |column|
      map_attribute_to_json_attribute(column, column) unless [:descriptor_fields].include?(column.to_sym)
    end

    # TODO[xxx]: It's better that some of these are decided at generation, rather than execution, time.
    extra_json_attributes do |object, json_attributes|
      json_attributes['uuid'] = object.uuid if object.respond_to?(:uuid)

      # Users and roles
      if object.respond_to?(:user)
        json_attributes['user'] = object.user.nil? ? 'unknown' : object.user.
      end
      if object.respond_to?(:roles)
        object.roles.each do |role|
          json_attributes[role.name.underscore] = role.users.map do |user|
            {
              login: user.,
              email: user.email,
              name: user.name
            }
          end
        end
      end
    end
  end
  render_class
end

.renders_model(model) ⇒ Object


122
123
124
# File 'app/models/api/base.rb', line 122

def self.renders_model(model)
  self.model_class = model
end

.to_hash(object) ⇒ Object


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'app/models/api/base.rb', line 32

def to_hash(object)
  # If the object is nil we get a chance to use the 'default' object that was specified.  By
  # default the "default" object is nil, but you can override it for associations through the
  # with_association(:name, :if_nil_use => :some_method).
  object ||= default_object
  return {} if object.nil?

  json_attributes = {}
  json_attributes['deleted_at'] = Time.now if object.destroyed?

  attribute_to_json_attribute_mappings.each do |attribute, json_attribute|
    json_attributes[json_attribute] = object.send(attribute)
  end
  associations.each do |_association, helper|
    value = helper.target(object)
    json_attributes.update(helper.to_hash(value))
    helper.newer_than(value, json_attributes['updated_at']) { |timestamp| json_attributes['updated_at'] = timestamp }
  end
  nested_has_many_associations.each do |_association, helper|
    values = helper.target(object)
    all_targets = values.map do |value|
      helper.newer_than(value, json_attributes['updated_at']) { |timestamp| json_attributes['updated_at'] = timestamp }
      helper.to_hash(value)
    end
    json_attributes.update(helper.alias.to_s => all_targets)
  end
  extra_json_attribute_handlers.each do |handler|
    handler.call(object, json_attributes)
  end
  json_attributes
end

.to_hash_for_list(object) ⇒ Object

Raises:

  • (StandardError)

64
65
66
67
68
69
70
71
72
# File 'app/models/api/base.rb', line 64

def to_hash_for_list(object)
  raise StandardError, 'The object is nil, which is highly unexpected!' if object.nil?

  json_attributes = {}
  attribute_to_json_attribute_mappings_for_list.each do |attribute, json_attribute|
    json_attributes[json_attribute] = object.send(attribute)
  end
  json_attributes
end

.update!(object, params) ⇒ Object


16
17
18
# File 'app/models/api/base.rb', line 16

def update!(object, params)
  object.update!(attributes_from_json(params))
end

.with_association(association, options = {}, &block) ⇒ Object


165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'app/models/api/base.rb', line 165

def self.with_association(association, options = {}, &block)
  association_helper = Class.new(Api::Base)
  association_helper.class_eval(&block)
  association_helper.singleton_class.class_eval do
    alias_method(:default_object, options[:if_nil_use]) if options.key?(:if_nil_use)
    define_method(:lookup_by) { options[:lookup_by] }
    define_method(:association) { association }
    define_method(:target) do |parent|
      target_object = parent.send(association)
      options[:decorator] && target_object ? options[:decorator].new(target_object) : target_object
    end
  end
  self.associations = Hash.new if associations.empty?
  associations[association.to_sym] = association_helper
end

.with_nested_has_many_association(association, options = {}, &block) ⇒ Object


181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'app/models/api/base.rb', line 181

def self.with_nested_has_many_association(association, options = {}, &block)
  association_helper = Class.new(Api::Base)
  association_helper.class_eval(&block)
  association_helper.singleton_class.class_eval do
    define_method(:association) { association }
    define_method(:alias) { options[:as] || association }
    define_method(:target) do |parent|
      target_object = parent.send(association)
      options[:decorator] && target_object ? options[:decorator].new(target_object) : target_object
    end
  end
  self.nested_has_many_associations = Hash.new if nested_has_many_associations.empty?
  nested_has_many_associations[association.to_sym] = association_helper
end