Skip to content

Instantly share code, notes, and snippets.

@ahawkins
Created May 11, 2012 14:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahawkins/2659869 to your computer and use it in GitHub Desktop.
Save ahawkins/2659869 to your computer and use it in GitHub Desktop.
My take on ActiveResource using OpenStruct delegating to a HTTP class.
module RadiumIo
class WebObject < OpenStruct
def initialize(attrs = {}, &block)
super
yield self if block_given?
end
def self.create(attributes = {}, &block)
account = new attributes, &block
account.save
account
end
def self.find(id)
record = new :id => id
record.reload
record
end
def self.all(params = {})
json = connection.get collection_url, params
json.symbolize_keys[collection].collect do |attributes|
new attributes
end
end
def id
attributes[:id]
end
def attributes
marshal_dump
end
def save
if new_record?
create ; true
else
update ; true
end
end
def destroy
delete
end
def reload
json = connection.get resource_url
marshal_load json.symbolize_keys[resource]
true
end
private
def new_record?
id.blank?
end
def self.collection
to_s.demodulize.pluralize.underscore.to_sym
end
def self.collection_url
"/#{collection}"
end
def resource
self.class.to_s.demodulize.underscore.to_sym
end
def resource_url
"/#{self.class.collection}/#{id}"
end
def resource_url
"/#{self.class.collection}/#{id}"
end
def server_attributes
attributes.except(:id)
end
def create
json = connection.post(self.class.collection_url, resource => server_attributes)
marshal_load json.symbolize_keys[resource]
end
def update
json = connection.post(resource_url, resource => server_attributes)
marshal_load json.symbolize_keys[resource]
end
def delete
connection.delete resource_url
freeze
end
def self.connection
RadiumIo.connection
end
def connection
self.class.connection
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment