Sha256: ddd925a009fb6e804d5139bdd0eee75b6e319f33970df8cee4fe7f8e815c02e8

Contents?: true

Size: 1.44 KB

Versions: 4

Compression:

Stored size: 1.44 KB

Contents

module Almodovar
  class Resource
    include HttpAccessor

    undef_method :id if instance_methods.include?("id")
    undef_method :type if instance_methods.include?("type")

    delegate :inspect, :to => :get!

    def self.from_xml(xml, auth = nil)
      new(nil, auth, Nokogiri::XML.parse(xml).root)
    end

    def initialize(url, auth, xml = nil, options = {})
      @url = url
      @auth = auth
      @xml = xml
      @options = options
    end

    def method_missing(meth, *args, &blk)
      resource_object(meth).send(meth, *args, &blk)
    end

    def respond_to?(meth)
      super || resource_object(meth).respond_to?(meth)
    end

    private

    def get!
      klass = xml['type'] == 'array' ? ResourceCollection : SingleResource
      @resource_object = klass.new(@url, @auth, @xml, @options)
    end

    def collection_call?(meth, *args)
      ([].respond_to?(meth) && !["delete", "id", "[]"].include?(meth.to_s)) ||
      ResourceCollection.instance_methods(false).map(&:to_s).include?(meth.to_s) ||
      (meth.to_s == "[]" && args.size == 1 && args.first.is_a?(Fixnum))
    end

    def resource_object(meth)
      @resource_object ||= resource_class(meth).new(@url, @auth, @xml, @options)
    end

    def resource_class(meth, *args)
      @resource_class ||= collection_call?(meth, *args) ? ResourceCollection : SingleResource
    end

  end

  def self.Resource(url, auth = nil, params = {})
    Resource.new(url, auth, nil, params)
  end

end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
almodovar-1.5.1 lib/almodovar/resource.rb
almodovar-1.5.0 lib/almodovar/resource.rb
almodovar-1.4.0 lib/almodovar/resource.rb
almodovar-1.3.0 lib/almodovar/resource.rb