Class: YBoss::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/yboss/base.rb

Direct Known Subclasses

Blogs, Images, Limitedweb, News, Related, Spelling, Web

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Base

Returns a new instance of Base.



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/yboss/base.rb', line 12

def initialize(options = {})
  if options.is_a?(Hash)
    options.delete('format')
  end

  @options = {
    'format' => 'json',
  }.merge(options)

  @oauth = YBoss::Oauth.new
  @oauth.consumer_key = YBoss::Config.instance.oauth_key
  @oauth.consumer_secret = YBoss::Config.instance.oauth_secret
end

Instance Attribute Details

#creditsObject (readonly)

Returns the value of attribute credits.



10
11
12
# File 'lib/yboss/base.rb', line 10

def credits
  @credits
end

#optionsObject (readonly)

Returns the value of attribute options.



10
11
12
# File 'lib/yboss/base.rb', line 10

def options
  @options
end

Instance Method Details

#base_uriObject



79
80
81
# File 'lib/yboss/base.rb', line 79

def base_uri
  ::YBoss::SERVICE_PREFIX + method_name
end

#call(options = {}) ⇒ Object



26
27
28
29
30
31
# File 'lib/yboss/base.rb', line 26

def call(options = {})
  data = fetch(@options.merge(options))

  clazz = YBoss.class_from_string(self.class.to_s + '::Result')
  clazz.new(data)
end

#fetch(options = {}) ⇒ Object



34
35
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
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/yboss/base.rb', line 34

def fetch(options = {})
  @options.merge!(options)

  url = base_uri + '?'
  url += @options.find_all { |k,v| ! v.nil? }.map { |k,v| "#{k}=#{URI.escape(v)}" }.join('&')

  parsed_url = URI.parse(url)
  url += "?" + @oauth.sign(parsed_url).query_string

  data = nil

  if YBoss::Config.instance.proxy
    proxy_uri = URI.parse(YBoss::Config.instance.proxy)

    Net::HTTP::Proxy(proxy_uri.host, proxy_uri.port).start(parsed_url.host)  { | http |
      req = Net::HTTP::Get.new "#{ parsed_url.path }?" + @oauth.sign(parsed_url).query_string
      response = http.request(req)
      if ! response.is_a?(Net::HTTPSuccess)
        raise FetchError.new("Got error while fetching #{url}: #{response.code} #{response.message}")
      end

      data = JSON.parse(response.read_body)
    }
  else
    Net::HTTP.start( parsed_url.host ) { | http |
      req = Net::HTTP::Get.new "#{ parsed_url.path }?" + @oauth.sign(parsed_url).query_string
      response = http.request(req)
      if ! response.is_a?(Net::HTTPSuccess)
        raise FetchError.new("Got error while fetching #{url}: #{response.code} #{response.message}")
      end

      data = JSON.parse(response.read_body)
    }
  end


  data
end

#method_nameObject



73
74
75
76
77
# File 'lib/yboss/base.rb', line 73

def method_name
  # derive the method name from the class name
  #
  self.class.to_s.downcase.split(/::/).last
end