marvelapi

ref: master

lib/marvel/client.rb


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
module Marvel
  class Client
    HOST  = "https://gateway.marvel.com"
    PRIVKEY = Configuration["api"]["private"]
    PUBKEY = Configuration["api"]["public"]

    def initialize
      if PRIVKEY.nil? || PUBKEY.nil?
        raise ArgumentError.new("You must set Marvel's api keys on config/config.yml")
      end
    end

    def story(id)
      dial("stories/#{id}").first
    end

    def characters_from_story(story_id)
      dial("stories/#{story_id}/characters")
    end

    private

    def dial(endpoint)
      response = HTTP::Client.get("#{HOST}/v1/public/#{endpoint}", parameters)

      extract_results(response)
    end

    def extract_results(response)
      unless response.nil?
        response["data"]["results"]
      end
    end

    def parameters
      now = Time.now.to_i

      {
        "ts" => now,
        "apikey" => PUBKEY,
        "hash" => Digest::MD5.hexdigest("#{now}#{PRIVKEY}#{PUBKEY}")
      }
    end
  end
end