class MarvelApiConsumer::Character

Public Class Methods

new(params = {}, resource = nil, max=nil) click to toggle source
# File lib/marvel_api_consumer/character.rb, line 5
def initialize(params = {}, resource = nil, max=nil)
  @max = max
  @resource = resource
  @params = params
  @collection = []
  @offset = params.fetch(:offset, nil)
  @limit = params.fetch(:limit, 50)
end

Public Instance Methods

fetch_list() click to toggle source
# File lib/marvel_api_consumer/character.rb, line 28
def fetch_list
  Enumerator.new do |y|
    until last?
      fetch_next_page
      @response['data']['results'].each do |element|
        y.yield element
      end
    end
  end
end
get_character(character_id) click to toggle source
# File lib/marvel_api_consumer/character.rb, line 21
def get_character(character_id)
  @response = with_handling do
    client.characters({}, character_id)
  end
  @response['data']['results'].first
end
max_characters() click to toggle source
# File lib/marvel_api_consumer/character.rb, line 14
def max_characters
  @response = with_handling do
    client.characters({limit: 1})
  end
  @response['data']['total']
end

Private Instance Methods

client() click to toggle source
# File lib/marvel_api_consumer/character.rb, line 62
def client
  MarvelApiConsumer.api
end
fetch_next_page() click to toggle source
# File lib/marvel_api_consumer/character.rb, line 41
def fetch_next_page
  @response = with_handling do
    client.characters(@params)
  end
  @last_response_empty  = @response.empty?
  @collection           += @response['data']['results']
  @offset               = @response['data']['offset'] + @collection.size
end
last?() click to toggle source
# File lib/marvel_api_consumer/character.rb, line 50
def last?
  @last_response_empty || @collection.size >= @max
end
with_handling() { || ... } click to toggle source
# File lib/marvel_api_consumer/character.rb, line 54
def with_handling
  @response = yield
  if @response.code != 200
    raise MarvelApiConsumer::ApiError, "Unexpected API response. code=#{@response.code} reason=#{@response['message']}"
  end
  @response
end