Class: ApiResource::Base

Inherits:
Object
  • Object
show all
Extended by:
ActiveModel::Naming
Includes:
AssociationActivation, Attributes, Callbacks, Conditions, Finders, ModelErrors, Observing, Scopes, Typecast
Defined in:
lib/api_resource/base.rb,
lib/api_resource/base.rb

Direct Known Subclasses

Local

Constant Summary

Constants included from Typecast

Typecast::FALSE_VALUES, Typecast::ISO_DATE, Typecast::ISO_DATETIME, Typecast::TRUE_VALUES

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Scopes

#scope?, #scope_attributes, #scopes

Methods included from Callbacks

#create_with_callbacks, #destroy_with_callbacks, #save_with_callbacks, #update_with_callbacks

Methods included from Observing

#notify_observers

Methods included from Attributes

#attribute?, #attributes, #attributes=, #protected_attribute?, #read_attribute, #reset_attribute_changes, #respond_to?, #save_with_dirty_tracking, #set_attributes_as_current, #write_attribute

Methods included from ModelErrors

#errors, #load_remote_errors, #save_with_validations, #valid?

Constructor Details

#initialize(attributes = {}) ⇒ Base

Returns a new instance of Base.



412
413
414
415
416
417
418
419
420
# File 'lib/api_resource/base.rb', line 412

def initialize(attributes = {})
  # call super's initialize to set up any variables that we need
  super(attributes)
  # if we initialize this class, load the attributes
  self.class.load_resource_definition
  # Now we can make a call to setup the inheriting 
  # klass with its attributes
  self.attributes = attributes
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &block) ⇒ Object (protected)



604
605
606
607
608
609
610
611
612
613
614
615
# File 'lib/api_resource/base.rb', line 604

def method_missing(meth, *args, &block)
  # make one attempt to load remote attrs
  if self.class.resource_definition_is_invalid?
    self.class.reload_resource_definition
  end
  # see if we respond to the method now
  if self.respond_to?(meth)
    return self.send(meth, *args, &block)
  else
    super
  end
end

Class Attribute Details

.collection_nameObject

collection_name with default



283
284
285
# File 'lib/api_resource/base.rb', line 283

def collection_name
  @collection_name ||= ActiveSupport::Inflector.pluralize(self.element_name)
end

.element_nameObject

element_name with default



279
280
281
# File 'lib/api_resource/base.rb', line 279

def element_name
  @element_name ||= self.model_name.element
end

Class Method Details

.build(attributes = {}) ⇒ Object



320
321
322
# File 'lib/api_resource/base.rb', line 320

def build(attributes = {})
  self.new(attributes)
end

.collection_path(prefix_options = {}, query_options = nil) ⇒ Object



313
314
315
316
317
318
# File 'lib/api_resource/base.rb', line 313

def collection_path(prefix_options = {}, query_options = nil)
  prefix_options, query_options = split_options(prefix_options) if query_options.nil?

  # Fall back on this rather than search without the id
  "#{prefix(prefix_options)}#{collection_name}.#{format.extension}#{query_string(query_options)}"
end

.connection(refresh = false) ⇒ Object



235
236
237
238
239
# File 'lib/api_resource/base.rb', line 235

def connection(refresh = false)
  @connection = Connection.new(self.site, self.format, self.headers) if refresh || @connection.nil?
  @connection.timeout = self.timeout
  @connection
end

.create(attributes = {}) ⇒ Object



324
325
326
# File 'lib/api_resource/base.rb', line 324

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

.delete(id, options = {}) ⇒ Object

Deletes the resources with the ID in the id parameter.

Options

All options specify prefix and query parameters.

Examples

Event.delete(2) # sends DELETE /events/2

Event.create(:name => 'Free Concert', :location => 'Community Center')
my_event = Event.find(:first) # let's assume this is event with ID 7
Event.delete(my_event.id) # sends DELETE /events/7

# Let's assume a request to events/5/cancel.xml
Event.delete(params[:id]) # sends DELETE /events/5


343
344
345
# File 'lib/api_resource/base.rb', line 343

def delete(id, options = {})
  connection.delete(element_path(id, options))
end

.element_path(id, prefix_options = {}, query_options = nil) ⇒ Object

alias_method :set_prefix, :prefix= alias_method :set_element_name, :element_name= alias_method :set_collection_name, :collection_name=



291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/api_resource/base.rb', line 291

def element_path(id, prefix_options = {}, query_options = nil)
  prefix_options, query_options = split_options(prefix_options) if query_options.nil?

  # If we have a prefix, we need a foreign key id
  # This regex detects '//', which means no foreign key id is present.
  if prefix(prefix_options) =~ /\/\/$/
    "/#{collection_name}/#{URI.escape id.to_s}.#{format.extension}#{query_string(query_options)}"
  else
    # Fall back on this rather than search without the id
    "#{prefix(prefix_options)}#{collection_name}/#{URI.escape id.to_s}.#{format.extension}#{query_string(query_options)}"
  end
end

.format_with_mimetype_or_format_set=(mime_type_or_format) ⇒ Object



213
214
215
216
217
# File 'lib/api_resource/base.rb', line 213

def format_with_mimetype_or_format_set=(mime_type_or_format)
  format = mime_type_or_format.is_a?(Symbol) ? ApiResource::Formats[mime_type_or_format] : mime_type_or_format
  self.format_without_mimetype_or_format_set = format
  self.connection.format = format if self.site
end

.headersObject



241
242
243
244
245
# File 'lib/api_resource/base.rb', line 241

def headers
  {}.tap do |ret|
    ret['Lifebooker-Token'] = self.token if self.token.present?
  end
end

.inherited(klass) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/api_resource/base.rb', line 62

def inherited(klass)
  # Call the methods of the superclass to make sure inheritable accessors and the like have been inherited
  super
  # Now we need to define the inherited method on the klass that's doing the inheriting
  # it calls super which will allow the chaining effect we need
  klass.instance_eval "    def inherited(klass)\n      klass.send(:define_singleton_method, :collection_name, lambda {self.superclass.collection_name})\n      super(klass)\n    end\n  EOE\n  true\nend\n", __FILE__, __LINE__ + 1

.load_resource_definitionObject



153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/api_resource/base.rb', line 153

def load_resource_definition
  unless instance_variable_defined?(:@resource_definition)
    # the last time we checked
    @resource_load_time = Time.now
  
    # set to not nil so we don't get an infinite loop
    @resource_definition = true
    self.set_class_attributes_upon_load
    return true
  end
  # we didn't do anything
  false
end

.new_element_path(prefix_options = {}) ⇒ Object

path to find



305
306
307
308
309
310
311
# File 'lib/api_resource/base.rb', line 305

def new_element_path(prefix_options = {})
  File.join(
    self.prefix(prefix_options), 
    self.collection_name, 
    "new.#{format.extension}"
  )
end

.open_timeout_with_connection_reset=(timeout) ⇒ Object



228
229
230
231
# File 'lib/api_resource/base.rb', line 228

def open_timeout_with_connection_reset=(timeout)
  @connection = nil
  self.open_timeout_without_connection_reset = timeout
end

.prefix(options = {}) ⇒ Object



247
248
249
250
251
252
# File 'lib/api_resource/base.rb', line 247

def prefix(options = {})
  default = (self.site ? self.site.path : '/')
  default << '/' unless default[-1..-1] == '/'
  self.prefix = default
  prefix(options)
end

.prefix=(value = '/') ⇒ Object



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/api_resource/base.rb', line 259

def prefix=(value = '/')
  prefix_call = value.gsub(/:\w+/) { |key| 
    "\#{URI.escape options[#{key}].to_s}"
  }
  @prefix_parameters = nil
  silence_warnings do
    instance_eval "      def prefix_source() \"\#{value}\" end\n      def prefix(options={}) \n        ret = \"\#{prefix_call}\"\n        ret =~ Regexp.new(Regexp.escape(\"//\")) ? \"/\" : ret\n      end\n    EOE\n  end\nrescue Exception => e\n  logger.error \"Couldn't set prefix: \#{e}\\n \#{code}\" if logger\n  raise\nend\n", __FILE__, __LINE__ + 1

.prefix_sourceObject



254
255
256
257
# File 'lib/api_resource/base.rb', line 254

def prefix_source
  prefix
  prefix_source
end

.reload_resource_definitionObject Also known as: reload_class_attributes



167
168
169
170
171
172
173
174
175
# File 'lib/api_resource/base.rb', line 167

def reload_resource_definition
  # clear the public_attribute_names, protected_attribute_names
  if instance_variable_defined?(:@resource_definition)
    remove_instance_variable(:@resource_definition)
    self.clear_attributes
    self.clear_related_objects
  end
  self.load_resource_definition
end

.reset_connectionObject



142
143
144
# File 'lib/api_resource/base.rb', line 142

def reset_connection
  remove_instance_variable(:@connection) if @connection.present?
end

.resource_definitionObject



76
77
78
# File 'lib/api_resource/base.rb', line 76

def resource_definition
  @resource_definition
end

.resource_definition_is_invalid?Boolean

do we have an invalid resource

Returns:

  • (Boolean)


348
349
350
351
352
353
354
355
# File 'lib/api_resource/base.rb', line 348

def resource_definition_is_invalid?
  # if we have a Hash, it's valid
  return false if @resource_definition.is_a?(Hash)
  # if we have no recheck time, it's invalid
  return true if @resource_load_time.nil?
  # have we checked in the last minute?
  return @resource_load_time < Time.now - 1.minute
end

.respond_to?(*args) ⇒ Boolean

load our resource definition to make sure we know what this class responds to

Returns:

  • (Boolean)


148
149
150
151
# File 'lib/api_resource/base.rb', line 148

def respond_to?(*args)
  self.load_resource_definition
  super
end

.set_class_attributes_upon_loadObject

This makes a request to new_element_path



81
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/api_resource/base.rb', line 81

def set_class_attributes_upon_load
  return true if self == ApiResource::Base
  begin
    @resource_definition = self.connection.get(
      self.new_element_path, self.headers
    )
    # Attributes go first
    if resource_definition["attributes"]
      
      define_attributes(
        *(resource_definition["attributes"]["public"] || [])
      )
      define_protected_attributes(
        *(resource_definition["attributes"]["protected"] || [])
      ) 
      
    end
    # Then scopes
    if resource_definition["scopes"]
      resource_definition["scopes"].each_pair do |scope_name, opts|
        self.scope(scope_name, opts)
      end
    end
    # Then associations
    if resource_definition["associations"]
      resource_definition["associations"].each_pair do |key, hash|
        hash.each_pair do |assoc_name, assoc_options|
          self.send(key, assoc_name, assoc_options)
        end
      end
    end
    
    # This is provided by ActiveModel::AttributeMethods, it should
    # define the basic methods but we need to override all the setters 
    # so we do dirty tracking
    attrs = []
    if resource_definition["attributes"] && resource_definition["attributes"]["public"]
      attrs += resource_definition["attributes"]["public"].collect{|v| 
        v.is_a?(Array) ? v.first : v
      }.flatten
    end
    if resource_definition["associations"]
      attrs += resource_definition["associations"].values.collect(&:keys).flatten
    end
    
  # Swallow up any loading errors because the site may be incorrect
  rescue Exception => e
    if ApiResource.raise_missing_definition_error
      raise e 
    end
    ApiResource.logger.warn(
      "#{self} accessing #{self.new_element_path}"
    )
    ApiResource.logger.warn(
      "#{self}: #{e.message[0..60].gsub(/[\n\r]/, '')} ...\n"
    )
    ApiResource.logger.debug(e.backtrace.pretty_inspect)
    return e.respond_to?(:request) ? e.request : nil
  end
end

.site_with_connection_reset=(site) ⇒ Object



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/api_resource/base.rb', line 189

def site_with_connection_reset=(site)
  # store so we can reload attributes if the site changed
  old_site = self.site.to_s.clone
  @connection = nil
  
  if site.nil?
    self.site_without_connection_reset = nil
    # no site, so we'll skip the reload
    return site
  else
    self.site_without_connection_reset = create_site_uri_from(site)
  end
  
  # reset class attributes and try to reload them if the site changed
  unless self.site.to_s == old_site
    self.reload_resource_definition
  end
  
  return site
end

.split_options(options = {}) ⇒ Object

and the other containing the leftovers.



359
360
361
362
363
364
365
366
367
# File 'lib/api_resource/base.rb', line 359

def split_options(options = {})
  prefix_options, query_options = {}, {}
  (options || {}).each do |key, value|
    next if key.blank?
    (prefix_parameters.include?(key.to_sym) ? prefix_options : query_options)[key.to_sym] = value
  end

  [ prefix_options, query_options ]
end

.timeout_with_connection_reset=(timeout) ⇒ Object



221
222
223
224
# File 'lib/api_resource/base.rb', line 221

def timeout_with_connection_reset=(timeout)
  @connection = nil
  self.timeout_without_connection_reset = timeout
end

.token_with_new_token_set=(new_token) ⇒ Object



179
180
181
182
183
184
185
# File 'lib/api_resource/base.rb', line 179

def token_with_new_token_set=(new_token)
  self.token_without_new_token_set = new_token
  self.connection(true)
  self.descendants.each do |child|
    child.send(:token=, new_token)
  end
end

Instance Method Details

#==(other) ⇒ Object



440
441
442
# File 'lib/api_resource/base.rb', line 440

def ==(other)
  other.equal?(self) || (other.instance_of?(self.class) && other.id == self.id)
end

#destroyObject



469
470
471
# File 'lib/api_resource/base.rb', line 469

def destroy
  connection.delete(element_path(self.id), self.class.headers)
end

#dupObject



452
453
454
# File 'lib/api_resource/base.rb', line 452

def dup
  self.class.instantiate_record(self.attributes)
end

#encode(options = {}) ⇒ Object



473
474
475
# File 'lib/api_resource/base.rb', line 473

def encode(options = {})
  self.send("to_#{self.class.format.extension}", options)
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


444
445
446
# File 'lib/api_resource/base.rb', line 444

def eql?(other)
  self == other
end

#hashObject



448
449
450
# File 'lib/api_resource/base.rb', line 448

def hash
  id.hash
end

#idObject



431
432
433
# File 'lib/api_resource/base.rb', line 431

def id
  self.read_attribute(self.class.primary_key)
end

#id=(id) ⇒ Object

Bypass dirty tracking for this field



436
437
438
# File 'lib/api_resource/base.rb', line 436

def id=(id)
  @attributes[self.class.primary_key] = id
end

#new?Boolean Also known as: new_record?

Returns:

  • (Boolean)


422
423
424
# File 'lib/api_resource/base.rb', line 422

def new?
  id.blank?
end

#persisted?Boolean

Returns:

  • (Boolean)


427
428
429
# File 'lib/api_resource/base.rb', line 427

def persisted?
  !new?
end

#prefix_attribute_namesObject



504
505
506
507
# File 'lib/api_resource/base.rb', line 504

def prefix_attribute_names
  return [] unless self.class.prefix_source =~ /\:/
  self.class.prefix_source.scan(/\:(\w+)/).collect{|match| match.first.to_sym}
end

#prefix_optionsObject



495
496
497
498
499
500
501
502
# File 'lib/api_resource/base.rb', line 495

def prefix_options
  return {} unless self.class.prefix_source =~ /\:/
  ret = {}
  self.prefix_attribute_names.each do |name|
    ret[name] = self.send(name)
  end
  ret
end

#reloadObject



477
478
479
480
481
482
483
484
485
486
487
# File 'lib/api_resource/base.rb', line 477

def reload
  # find the record from the remote service
  reloaded = self.class.find(self.id)
  
  # clear out the attributes cache
  @attributes_cache = HashWithIndifferentAccess.new
  # set up our attributes cache on our record
  @attributes = reloaded.instance_variable_get(:@attributes)
  
  reloaded
end

#save(*args) ⇒ Object



461
462
463
# File 'lib/api_resource/base.rb', line 461

def save(*args)
  new? ? create(*args) : update(*args)
end

#save!(*args) ⇒ Object



465
466
467
# File 'lib/api_resource/base.rb', line 465

def save!(*args)
  save(*args) || raise(ApiResource::ResourceInvalid.new(self))
end

#serializable_hash(options = {}) ⇒ Object

TODO: this method needs to change seriously to fit in with the new typecasting scheme, it should call self.outgoing_attributes which should return the converted versions after calling to_api, that should be implemented in the attributes module though



531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
# File 'lib/api_resource/base.rb', line 531

def serializable_hash(options = {})
  
  action = options[:action]
  
  include_nil_attributes = options[:include_nil_attributes]
  
  options[:include_associations] = options[:include_associations] ? options[:include_associations].symbolize_array : self.changes.keys.symbolize_array.select{|k| self.association?(k)}
  
  options[:include_extras] = options[:include_extras] ? options[:include_extras].symbolize_array : []
  
  options[:except] ||= []
  
  ret = self.attributes.inject({}) do |accum, (key,val)|
    # If this is an association and it's in include_associations then include it
    if options[:include_extras].include?(key.to_sym)
      accum.merge(key => val)
    elsif options[:except].include?(key.to_sym)
      accum
    # this attribute is already accounted for in the URL
    elsif self.prefix_attribute_names.include?(key.to_sym)
      accum
    elsif(!include_nil_attributes && val.nil? && self.changes[key].blank?)
      accum
    else
      !self.attribute?(key) || self.protected_attribute?(key) ? accum : accum.merge(key => val)
    end
  end

  # also add in the _id fields that are changed
  ret = self.association_names.inject(ret) do |accum, assoc_name|
    
    # get the id method for the association
    id_method = self.class.association_foreign_key_field(assoc_name)
     
    # only do this if they are not prefix_attribute_names
    # and we have changes
    if !self.prefix_attribute_names.include?(id_method.to_sym) &&
      self.changes[id_method].present?
      
      accum[id_method] = self.changes[id_method].last
    end
    accum
  end

  options[:include_associations].each do |assoc|
    if self.association?(assoc)
      ret[assoc] = self.send(assoc).serializable_hash({
        :include_id => true, 
        :include_nil_attributes => include_nil_attributes, 
        :action => action
      })
    end
  end
  # include id - this is for nested updates
  ret[:id] = self.id if options[:include_id] && !self.new?
  ret
end

#to_json(options = {}) ⇒ Object



523
524
525
# File 'lib/api_resource/base.rb', line 523

def to_json(options = {})
  self.class.include_root_in_json ? {self.class.element_name => self.serializable_hash(options)}.to_json : self.serializable_hash(options).to_json
end

#to_paramObject



489
490
491
492
493
# File 'lib/api_resource/base.rb', line 489

def to_param
  # Stolen from active_record.
  # We can't use alias_method here, because method 'id' optimizes itself on the fly.
  id && id.to_s # Be sure to stringify the id for routes
end

#to_sObject Also known as: inspect

Override to_s and inspect so they only show attributes and not associations, this prevents force loading of associations when we call to_s or inspect on a descendent of base but allows it if we try to evaluate an association directly



513
514
515
# File 'lib/api_resource/base.rb', line 513

def to_s
  return "#<#{self.class}:#{(self.object_id * 2).to_s(16)} @attributes=#{self.attributes}"
end

#to_xml(options = {}) ⇒ Object

Methods for serialization as json or xml, relying on the serializable_hash method



519
520
521
# File 'lib/api_resource/base.rb', line 519

def to_xml(options = {})
  self.serializable_hash(options).to_xml(:root => self.class.element_name)
end

#update_attributes(attrs) ⇒ Object



456
457
458
459
# File 'lib/api_resource/base.rb', line 456

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