lib/abiquo.rb in abiquo-0.1.0 vs lib/abiquo.rb in abiquo-0.1.2
- old
+ new
@@ -1,25 +1,43 @@
require 'resourceful'
require 'nokogiri'
-require 'active_support'
+require File.expand_path('../active_support/inflections', __FILE__)
require File.expand_path('../core_ext', __FILE__)
require File.expand_path('../to_xml', __FILE__)
require 'uri'
module Abiquo
+
+ class NotAllowed < RuntimeError
+ def initialize(method, url)
+ @method = method
+ @url = url
+ end
+
+ def message
+ "Method #{@method} not allowed for #{@url}"
+ end
+ end
class BasicAuth < Resourceful::BasicAuthenticator
def can_handle?(request); true; end
-
end
module HttpAccessor
def xml
@xml ||= begin
response = http.resource(url_with_params).get
- Nokogiri.parse(response.body).root
+ doc = Nokogiri.parse(response.body)
+ # HACK: collections have link and totalSize entities we
+ # don't want here
+ if not doc.search('/*/totalSize').empty?
+ doc.search('/*/totalSize | /*/link').each do |node|
+ node.remove
+ end
+ end
+ doc.root
end
end
private
@@ -31,10 +49,17 @@
end
def http
Resourceful::HttpAccessor.new(:authenticator => @auth)
end
+
+ def rest_options
+ @rest_options ||= begin
+ response = http.resource(@url).options
+ response.header['Allow'].map {|m| m.to_sym }
+ end
+ end
end
class SingleResource
@@ -48,15 +73,17 @@
@xml = xml
@options = options
end
def update(attrs = {})
+ raise Abiquo::NotAllowed.new(:PUT, url) unless rest_options.include?(:PUT)
response = http.resource(url).put(attrs.to_xml(:root => object_type), :content_type => "application/xml")
@xml = Nokogiri.parse(response.body).root
end
def delete
+ raise Abiquo::NotAllowed.new(:DELETE, url) unless rest_options.include?(:DELETE)
http.resource(url).delete
end
def url
@url ||= xml.at_xpath("./link[@rel='edit']").try(:[], "href")
@@ -109,12 +136,14 @@
@xml = xml if options.empty?
@options = options
end
def create(attrs = {})
+ raise Abiquo::NotAllowed.new(:POST, url) unless rest_options.include?(:POST)
response = http.resource(url_with_params).post(attrs.to_xml(:root => object_type, :convert_links => true), :content_type => "application/xml")
- Resource.new(nil, @auth, Nokogiri.parse(response.body).root)
+ doc = Nokogiri.parse(response.body)
+ Resource.new(nil, @auth, doc.root)
end
private
def object_type
@@ -133,14 +162,16 @@
class Resource
include HttpAccessor
undef id
+ undef type
delegate :inspect, :to => :get!
def self.from_xml(xml, auth = nil)
- new(nil, auth, Nokogiri.parse(xml).root)
+ doc = Nokogiri.parse(xml)
+ new(nil, auth, doc.root)
end
def initialize(url, auth, xml = nil, options = {})
@url = url
@auth = auth