Sha256: 322b0bd4e8804b5a64b600d86aeae5723dfd90b2758263cc72f4325e6a2f4b0c

Contents?: true

Size: 1.42 KB

Versions: 1

Compression:

Stored size: 1.42 KB

Contents

require "cgi"

module Fortnox
  module API
    module Repository
      module Loaders

        def all()
          response_hash = get( @options.uri )
          entities_hash = response_hash[ @options.json_collection_wrapper ]
          entities_hash.map do |entity_hash|
            hash_to_entity( entity_hash )
          end
        end

        def only( filter )
          response_hash = get( @options.uri + "?filter=#{ filter }" )
          entities_hash = response_hash[ @options.json_collection_wrapper ]
          entities_hash.map do |entity_hash|
            hash_to_entity( entity_hash )
          end
        end

        def find( id_or_hash )
          return find_all_by( id_or_hash ) if id_or_hash.is_a? Hash

          id = Integer( id_or_hash )
          find_one_by( id )

        rescue ArgumentError
          raise ArgumentError, "find only accepts a number or hash as argument"
        end

        def find_one_by( id )
          response_hash = get( "#{@options.uri}#{id}" )
          entity_hash = response_hash[ @options.json_entity_wrapper ]
          hash_to_entity( entity_hash )
        end

        # def find_all_by( hash )

        # end

        def to_query( hash )
          hash.collect do |key, value|
            escape( key, value )
          end.sort * '&'
        end

        def escape( key, value )
          "#{CGI.escape(key.to_s)}=#{CGI.escape(value.to_s)}"
        end

      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
fortnox-api-0.1.0 lib/fortnox/api/repositories/base/loaders.rb