lib/yammer/base.rb in yammer-client-0.1.2 vs lib/yammer/base.rb in yammer-client-0.1.3
- old
+ new
@@ -1,8 +1,9 @@
module Yammer
class Base
class << self
+ include ApiHandler
# Returns the non-qualified class name
# @!scope class
def base_name
@base_name ||= begin
@@ -30,11 +31,11 @@
# @!scope class
def fetch(id)
return unless identity_map
attributes = identity_map.get("#{base_name}_#{id}")
unless attributes
- result = Yammer.send("get_#{base_name}", id)
+ result = api_handler.send("get_#{base_name}", id)
attributes = result.empty? ? nil : result.body
unless attributes.empty?
identity_map.put("#{base_name}_#{id}", attributes)
end
end
@@ -46,20 +47,20 @@
@identity_map ||= Yammer::IdentityMap.new
end
# Returns a hash of all attributes that are meant to trigger an HTTP request
# @!scope class
- def fetchable_attrs
- @fetchable_keys ||= {}
+ def model_attributes
+ @model_attributes ||= {}
end
protected
def attr_accessor_deffered(*symbols)
symbols.each do |key|
- # track attributes the trigger fetch
- fetchable_attrs[key] = false
+ # track attributes that should trigger a fetch
+ model_attributes[key] = false
# getter
define_method(key.to_s) do
load_deferred_attribute!(key)
instance_variable_get("@#{key}")
@@ -80,20 +81,27 @@
end
attr_reader :id, :attrs
def initialize(props={})
+ @klass = self.class
@modified_attributes = {}
@new_record = true
@loaded = false
@attrs = props
self.id = @attrs.delete(:id)
self.update(@attrs)
+
+ yield self if block_given?
end
+ def api_handler
+ @klass.api_handler
+ end
+
def base_name
- self.class.base_name
+ @klass.base_name
end
def new_record?
@new_record
end
@@ -113,11 +121,11 @@
def loaded?
@loaded
end
def load!
- @attrs = self.class.fetch(@id)
+ @attrs = @klass.fetch(@id)
@loaded = true
update(@attrs)
self
end
@@ -128,21 +136,21 @@
def save
return self if ((persisted? && @modified_attributes.empty?) || @attrs.empty?)
result = if new_record?
- Yammer.send("create_#{base_name}", @attrs)
+ api_handler.send("create_#{base_name}", @attrs)
else
- Yammer.send("update_#{base_name}", @id, @modified_attributes)
+ api_handler.send("update_#{base_name}", @id, @modified_attributes)
end
@modified_attributes = {}
self
end
def delete!
return if new_record?
- result = Yammer.send("delete_#{base_name}", @id)
+ result = api_handler.send("delete_#{base_name}", @id)
result.success?
end
private
@@ -175,10 +183,10 @@
def update(attrs={})
attrs.each do |key, value|
send("#{key}=", value)
end
if persisted? && !loaded?
- @loaded = self.class.fetchable_attrs.keys.inject(true) do |result, key|
+ @loaded = @klass.model_attributes.keys.inject(true) do |result, key|
result && @attrs.has_key?(key)
end
end
end
end
\ No newline at end of file