Class: Yelp::Api

Inherits:
Object
  • Object
show all
Defined in:
lib/yelp/api.rb

Constant Summary collapse

PATH =
'/v2/search?term=pubs&sort=2&cc=GB&location=__CITY__'
MSG =
{
connection_error: 'Could not connect to the internet',
no_results: 'No matching results' }

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Api

Returns a new instance of Api.



14
15
16
17
18
# File 'lib/yelp/api.rb', line 14

def initialize( options )
  @body = "", ""
  @consumer = OAuth::Consumer.new( options[:consumer_key], options[:consumer_secret], {:site => "http://#{options[:api_host]}"} )
  @access_token = OAuth::AccessToken.new( @consumer, options[:token], options[:token_secret] )
end

Instance Attribute Details

#access_tokenObject

Returns the value of attribute access_token.



7
8
9
# File 'lib/yelp/api.rb', line 7

def access_token
  @access_token
end

#bodyObject

Returns the value of attribute body.



7
8
9
# File 'lib/yelp/api.rb', line 7

def body
  @body
end

#consumerObject

Returns the value of attribute consumer.



7
8
9
# File 'lib/yelp/api.rb', line 7

def consumer
  @consumer
end

Instance Method Details



20
21
22
23
24
25
26
27
28
# File 'lib/yelp/api.rb', line 20

def popular_pub_in( city = 'London')
  path = PATH.gsub( '__CITY__', city )
  @body = @access_token.get( path ).body
  @body.include?('error') ? JSON.parse(@body)['error']['text'] : results
rescue SocketError => e
  MSG[:connection_error]
rescue Exception => e
  "[#{e.class}] - #{e.message}"
end

#prepare_output(business) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/yelp/api.rb', line 41

def prepare_output( business )
  neighborhoods = business['location']['neighborhoods']  unless business['location']['neighborhoods'].nil?
  output =
"""
The highest rated pub in #{business['location']['city']} is:

================================================================================
#{business['name']} - #{ !neighborhoods.nil? ? neighborhoods.join(', ') : 'N/A'}
================================================================================

#{business['location']['address'].join(', ')}
#{business['phone']}

#{business['rating']} stars

================================================================================
"""
  output
end

#resultsObject



30
31
32
33
34
35
36
37
38
39
# File 'lib/yelp/api.rb', line 30

def results
  business = {}
  @body = JSON.parse( @body )
  unless @body['businesses'].empty?
    business = @body['businesses'].first #we are interested just in first result
    business['location']['address'] << business['location']['postal_code']
  end

  business.empty? ? MSG[:no_results] : prepare_output( business )
end