diff options
author | David Heinemeier Hansson <david@loudthinking.com> | 2006-06-25 14:44:22 +0000 |
---|---|---|
committer | David Heinemeier Hansson <david@loudthinking.com> | 2006-06-25 14:44:22 +0000 |
commit | 99d268c8534ad398c6c60a4978ef94699cbb8ada (patch) | |
tree | 70a65800284217eef66405826748c8588504e666 /activeresource/lib/active_resource/base.rb | |
parent | a55265132b37c6fb8ac15a96b44e64a64bcd4c45 (diff) | |
download | rails-99d268c8534ad398c6c60a4978ef94699cbb8ada.tar.gz rails-99d268c8534ad398c6c60a4978ef94699cbb8ada.tar.bz2 rails-99d268c8534ad398c6c60a4978ef94699cbb8ada.zip |
Initial check-in of Active Resourse
git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@4492 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
Diffstat (limited to 'activeresource/lib/active_resource/base.rb')
-rw-r--r-- | activeresource/lib/active_resource/base.rb | 99 |
1 files changed, 99 insertions, 0 deletions
diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb new file mode 100644 index 0000000000..2d4025e5dd --- /dev/null +++ b/activeresource/lib/active_resource/base.rb @@ -0,0 +1,99 @@ +require 'active_resource/connection' + +module ActiveResource + class Base + class << self + def site=(site) + @@site = URI.parse(site) + end + + def site + @@site + end + + def connection(refresh = false) + @connection = Connection.new(site) if refresh || @connection.nil? + @connection + end + + def element_name + self.to_s.underscore + end + + def collection_name + element_name.pluralize + end + + def element_path(id) + "/#{collection_name}/#{id}.xml" + end + + def collection_path + "/#{collection_name}.xml" + end + + def find(*arguments) + scope = arguments.slice!(0) + + case scope + when Fixnum + # { :person => person1 } + new(connection.get(element_path(scope)).values.first) + when :all + # { :people => { :person => [ person1, person2 ] } } + connection.get(collection_path).values.first.values.first.collect { |element| new(element) } + when :first + find(:all, *arguments).first + end + end + end + + attr_accessor :attributes + + def initialize(attributes = {}) + @attributes = attributes + end + + def id + attributes["id"] + end + + def id=(id) + attributes["id"] = id + end + + def save + update + end + + def destroy + connection.delete(self.class.element_path(id)) + end + + def to_xml + attributes.to_xml(:root => self.class.element_name) + end + + protected + def connection(refresh = false) + self.class.connection(refresh) + end + + def update + connection.put(self.class.element_path(id), to_xml) + end + + def method_missing(method_symbol, *arguments) + method_name = method_symbol.to_s + + case method_name.last + when "=" + attributes[method_name.first(-1)] = arguments.first + when "?" + # TODO + else + attributes[method_name] || super + end + end + end +end
\ No newline at end of file |