Class: ApiResource::Base
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
#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 = {})
super(attributes)
self.class.load_resource_definition
self.attributes = attributes
end
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(meth, *args, &block) ⇒ Object
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)
if self.class.resource_definition_is_invalid?
self.class.reload_resource_definition
end
if self.respond_to?(meth)
return self.send(meth, *args, &block)
else
super
end
end
|
Class Attribute Details
.collection_name ⇒ Object
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_name ⇒ Object
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?
"#{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.) 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)
Event.create(:name => 'Free Concert', :location => 'Community Center')
my_event = Event.find(:first)
Event.delete(my_event.id)
Event.delete(params[:id])
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 prefix(prefix_options) =~ /\/\/$/
"/#{collection_name}/#{URI.escape id.to_s}.#{format.extension}#{query_string(query_options)}"
else
"#{prefix(prefix_options)}#{collection_name}/#{URI.escape id.to_s}.#{format.extension}#{query_string(query_options)}"
end
end
|
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
|
241
242
243
244
245
|
# File 'lib/api_resource/base.rb', line 241
def
{}.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)
super
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_definition ⇒ Object
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)
@resource_load_time = Time.now
@resource_definition = true
self.set_class_attributes_upon_load
return true
end
false
end
|
.new_element_path(prefix_options = {}) ⇒ Object
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_source ⇒ Object
254
255
256
257
|
# File 'lib/api_resource/base.rb', line 254
def prefix_source
prefix
prefix_source
end
|
.reload_resource_definition ⇒ Object
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
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_connection ⇒ Object
142
143
144
|
# File 'lib/api_resource/base.rb', line 142
def reset_connection
remove_instance_variable(:@connection) if @connection.present?
end
|
.resource_definition ⇒ Object
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
348
349
350
351
352
353
354
355
|
# File 'lib/api_resource/base.rb', line 348
def resource_definition_is_invalid?
return false if @resource_definition.is_a?(Hash)
return true if @resource_load_time.nil?
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
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_load ⇒ Object
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.
)
if resource_definition["attributes"]
define_attributes(
*(resource_definition["attributes"]["public"] || [])
)
define_protected_attributes(
*(resource_definition["attributes"]["protected"] || [])
)
end
if resource_definition["scopes"]
resource_definition["scopes"].each_pair do |scope_name, opts|
self.scope(scope_name, opts)
end
end
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
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
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)
old_site = self.site.to_s.clone
@connection = nil
if site.nil?
self.site_without_connection_reset = nil
return site
else
self.site_without_connection_reset = create_site_uri_from(site)
end
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
|
#destroy ⇒ Object
469
470
471
|
# File 'lib/api_resource/base.rb', line 469
def destroy
connection.delete(element_path(self.id), self.class.)
end
|
#dup ⇒ Object
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
444
445
446
|
# File 'lib/api_resource/base.rb', line 444
def eql?(other)
self == other
end
|
#hash ⇒ Object
448
449
450
|
# File 'lib/api_resource/base.rb', line 448
def hash
id.hash
end
|
#id ⇒ Object
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?
422
423
424
|
# File 'lib/api_resource/base.rb', line 422
def new?
id.blank?
end
|
#persisted? ⇒ Boolean
427
428
429
|
# File 'lib/api_resource/base.rb', line 427
def persisted?
!new?
end
|
#prefix_attribute_names ⇒ Object
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_options ⇒ Object
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
|
#reload ⇒ Object
477
478
479
480
481
482
483
484
485
486
487
|
# File 'lib/api_resource/base.rb', line 477
def reload
reloaded = self.class.find(self.id)
@attributes_cache = HashWithIndifferentAccess.new
@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 options[:include_extras].include?(key.to_sym)
accum.merge(key => val)
elsif options[:except].include?(key.to_sym)
accum
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
ret = self.association_names.inject(ret) do |accum, assoc_name|
id_method = self.class.association_foreign_key_field(assoc_name)
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
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_param ⇒ Object
489
490
491
492
493
|
# File 'lib/api_resource/base.rb', line 489
def to_param
id && id.to_s
end
|
#to_s ⇒ Object
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
|