Sha256: 77961668ffc1a00f6c7e52a6e87b4196a336b2f2a133ccc4f4d2b07d9a6885c8

Contents?: true

Size: 1.68 KB

Versions: 1

Compression:

Stored size: 1.68 KB

Contents

require "cgi"

module Fortnox
  module API
    module Repository
      module Loaders

        def all()
          response_hash = get( self.class::URI )
          instansiate_collection_response( response_hash )
        end

        def only( filter )
          response_hash = get( "#{ self.class::URI }?filter=#{ filter }" )
          instansiate_collection_response( response_hash )
        end

        def search( hash )
          attribute, value = hash.first
          response_hash = get( "#{ self.class::URI }?#{ attribute }=#{ value }" )
          instansiate_collection_response( response_hash )
        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( "#{ self.class::URI }#{ id }" )
          instansiate( @mapper.wrapped_json_hash_to_entity_hash( response_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

        private

          def instansiate_collection_response( response_hash )
            entities_hash = @mapper.wrapped_json_collection_to_entities_hash( response_hash )
            entities_hash.map do |entity_hash|
              instansiate( entity_hash )
            end
          end

      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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