Class: Base

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/buscape_api/base.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Base

Returns a new instance of Base.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/buscape_api/base.rb', line 6

def initialize(options = {})
  raise "No :app_id set" unless options.include? :app_id
  options[:format] = 'json' # JSON is more lightweight than xml
  @options = options
  @services = [
    { :method => :categories, :service => :findCategoryList },
    { :method => :products, :service => :findProductList },
    { :method => :offers, :service => :findOfferList, :item => :offer },
    { :method => :top_products, :service => :topProducts },
    { :method => :user_ratings, :service => :viewUserRatings },
    { :method => :product_details, :service => :viewProductDetails },
    { :method => :seller_details, :service => :viewSellerDetails }
  ]
  @methods = @services.map { |service| service[:method] }
  @url = base_url
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/buscape_api/base.rb', line 54

def method_missing(method, *args)
  if @methods.include? method
    select_service method
    set_api
    set_app_id
    select_country if @options.include? :country_code
    self
  elsif method == :where
    parameterize args.first
    response = self.class.get(URI::encode(@url))['Result']
  else
    raise NoMethodError
  end
end

Instance Method Details

#base_urlObject



23
24
25
# File 'lib/buscape_api/base.rb', line 23

def base_url
  @options[:sandbox] ? "http://sandbox.buscape.com" : "http://bws.buscape.com"
end

#parameterize(options) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/buscape_api/base.rb', line 46

def parameterize(options)
  parameters = String.new

  options.keys.each_with_index do |parameter,index|
    index == 0 ? @url << "/?#{parameter}=#{options[parameter]}" : @url << "&#{parameter}=#{options[parameter]}"
  end
end

#select_countryObject



42
43
44
# File 'lib/buscape_api/base.rb', line 42

def select_country
  @url << '/' << @options[:country_code]
end

#select_service(method) ⇒ Object



27
28
29
30
31
32
# File 'lib/buscape_api/base.rb', line 27

def select_service(method)
  @services.each do |s|
    @service = s[:service] if s.values.include? method
  end
  @url << '/service/' << @service.to_s
end

#set_apiObject



34
35
36
# File 'lib/buscape_api/base.rb', line 34

def set_api
  (@url << '/' << @options[:api]) if @options[:api].present?
end

#set_app_idObject



38
39
40
# File 'lib/buscape_api/base.rb', line 38

def set_app_id
  @url << '/' << @options[:app_id]
end