Sha256: d53b184a4c6f5fa672e874d767f15db2e7e6decb2feb76d7bfbb2244669970f2

Contents?: true

Size: 1.57 KB

Versions: 12

Compression:

Stored size: 1.57 KB

Contents

module VkontakteApi
  # A module that handles method result processing.
  # 
  # It implements method blocks support, result typecasting and raises `VkontakteApi::Error` in case of an error response.
  module Result
    class << self
      # The main method result processing.
      # @param [Hashie::Mash] response The server response in mash format.
      # @param [Symbol] type The expected result type (`:boolean` or `:anything`).
      # @param [Proc] block A block passed to the API method.
      # @return [Array, Hashie::Mash] The processed result.
      # @raise [VkontakteApi::Error] raised when VKontakte returns an error response.
      def process(response, type, block)
        result = extract_result(response)
        
        if result.respond_to?(:each)
          # enumerable result receives :map with a block when called with a block
          # or is returned untouched otherwise
          block.nil? ? result : result.map(&block)
        else
          # non-enumerable result is typecasted
          # (and yielded if block_given?)
          result = typecast(result, type)
          block.nil? ? result : block.call(result)
        end
      end
      
    private
      def extract_result(response)
        if response.error?
          raise VkontakteApi::Error.new(response.error)
        else
          response.response
        end
      end
      
      def typecast(parameter, type)
        case type
        when :boolean
          # '1' becomes true, '0' becomes false
          !parameter.to_i.zero?
        else
          parameter
        end
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
vkontakte_api-1.3.1 lib/vkontakte_api/result.rb
vkontakte_api-1.3 lib/vkontakte_api/result.rb
vkontakte_api-1.2 lib/vkontakte_api/result.rb
vkontakte_api-1.1 lib/vkontakte_api/result.rb
vkontakte_api-1.0.4 lib/vkontakte_api/result.rb
vkontakte_api-1.0.3 lib/vkontakte_api/result.rb
vkontakte_api-1.0.2 lib/vkontakte_api/result.rb
vkontakte_api-1.0.1 lib/vkontakte_api/result.rb
vkontakte_api-1.0 lib/vkontakte_api/result.rb
vkontakte_api-1.0.rc3 lib/vkontakte_api/result.rb
vkontakte_api-1.0.rc2 lib/vkontakte_api/result.rb
vkontakte_api-1.0.rc lib/vkontakte_api/result.rb