Sha256: 4a1818410194b7979b3cd10182b1cec8c09210f3253b4001e6654b6a99bd2a33

Contents?: true

Size: 1.27 KB

Versions: 8

Compression:

Stored size: 1.27 KB

Contents

module Whatser
  class Resource
    attr_accessor :json
    
    class << self   
      def client
        @client
      end
      
      def set(client)
        @client = client
        self
      end
      
      def api_request(verb, path, params={}, opts={})
        res = client.request(verb, path, params)
        res.data = convert_data_to_model( res.data, opts)
        return res
      end

      def convert_data_to_model(data, opts={})
        return data if data.blank?
        opts ||= {}

        data = if data.is_a?(Array)
          data.inject([]) {|result,d| result << from_hash_to_model(d, opts[:model]) }
        else
          from_hash_to_model(data, opts[:model])
        end
        data
      end
      
      def from_hash_to_model(hash, model=nil)
        hash ||= {}
        hash = hash.size == 1 ? hash.first.last : hash
        mod = model.blank? ? new : model.new
        hash.each do |k,v|
          mod.send("#{k}=", v) if mod.respond_to?(k)
        end
        mod.json = hash.to_json
        return mod
      end
    end
    
    def initialize(params={})
      params.each_pair { |k,v| send("#{k}=", v) if respond_to?(k) }
    end
    
    def api_request(verb, path, params={}, opts={})
      self.class.api_request(verb, path, params, opts)
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
whatser-0.6.1 lib/whatser/resources/resource.rb
whatser-0.6.0 lib/whatser/resources/resource.rb
whatser-0.5.0 lib/whatser/resources/resource.rb
whatser-0.4.0 lib/whatser/resources/resource.rb
whatser-0.3.2 lib/whatser/resources/resource.rb
whatser-0.3.1 lib/whatser/resources/resource.rb
whatser-0.3.0 lib/whatser/resources/resource.rb
whatser-0.2.0 lib/whatser/resources/resource.rb