module TelphinApi::Result

A module that handles method result processing.

It implements method blocks support, result typecasting and raises `TelphinApi::Error` in case of an error response.

Public Class Methods

process(response, type, block) click to toggle source

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 [TelphinApi::Error] raised when Telphin returns an error response.

# File lib/telphin_api/result.rb, line 13
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 Class Methods

extract_result(response) click to toggle source
# File lib/telphin_api/result.rb, line 29
def extract_result(response)
  if response.error?
    raise TelphinApi::Error.new(response.error)
  else
    response
  end
end
typecast(parameter, type) click to toggle source
# File lib/telphin_api/result.rb, line 37
def typecast(parameter, type)
  case type
  when :boolean
    # '1' becomes true, '0' becomes false
    !parameter.to_i.zero?
  else
    parameter
  end
end