Class: ProductHunt::Client

Inherits:
Object
  • Object
show all
Includes:
HTTParty, API
Defined in:
lib/product_hunt/client.rb

Constant Summary

Constants included from API::Users

API::Users::CURRENT_USER_PATH, API::Users::USERS_PATH

Constants included from API::Posts

API::Posts::PATH

Instance Method Summary collapse

Methods included from API::Users

#current_user, #user, #users

Methods included from API::Posts

#all_posts, #comments_for_post, #post, #posts, #votes_for_post

Constructor Details

#initialize(token) ⇒ Client

Returns a new instance of Client.



12
13
14
# File 'lib/product_hunt/client.rb', line 12

def initialize(token)
  @config = { headers: { "Authorization" => "Bearer #{token}" } }
end

Instance Method Details

#fetch(path, params) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/product_hunt/client.rb', line 16

def fetch(path, params)
  config = @config

  if params.has_key?(:headers)
    headers = params.delete(:headers)
    config = config.merge({headers: config[:headers].merge(headers)})
  end

  if params.has_key?(:etag)
    etag = params.delete(:etag)
    config = config.merge({headers: config[:headers].merge({'If-None-Match' => etag})})
  end

  queryopts = if params.is_a?(Enumerable) && params.size > 0
    "?" + URI.encode_www_form(params)
  end

  self.class.get(path + (queryopts || ""), config)
end

#process(path, params) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/product_hunt/client.rb', line 36

def process(path, params)
  response = fetch(path, params)
  processed_response = nil

  fail "Block required to process response" if !block_given?

  if response.code == 200
    processed_response = yield response
    processed_response.define_singleton_method(:modified?) { true }
  elsif response.code == 304
    processed_response.define_singleton_method(:modified?) { false }
    processed_response.define_singleton_method(:method_missing) do |symbol, args|
      raise InvalidAccessToUnmodifiedRecordError.new("Trying to call `#{symbol}`")
    end
  else
    fail "Still need to cover the other response codes and use cases for the API (eg. 304 not modified, error cases)"
  end

  if response.headers["etag"]
    fail "Object already defines #etag method" if processed_response.respond_to?(:etag)
    processed_response.define_singleton_method(:etag) { response.headers["etag"].gsub!(/\A"|"\z/, '') }
  end

  processed_response
end