Class: CurrencySpy::Scraper

Inherits:
Object
  • Object
show all
Defined in:
lib/currency_spy/scraper.rb

Overview

A base class for all scrapers. Defines the common logic which is used across all of them.

Direct Known Subclasses

DnbNord, Nbp, Walutomat

Constant Summary collapse

RATE_DATA =

Each item has to be implemented as a method in the scraper sub class.

%w(buy_rate sell_rate medium_rate rate_time).freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeScraper

Base constructor



20
21
22
23
# File 'lib/currency_spy/scraper.rb', line 20

def initialize()
  @url = nil
  @currency_code = 'EUR'
end

Instance Attribute Details

#available_codesObject (readonly)

a list of codes available from given source



15
16
17
# File 'lib/currency_spy/scraper.rb', line 15

def available_codes
  @available_codes
end

#currency_codeObject

current currency code we’re fetching rates for



11
12
13
# File 'lib/currency_spy/scraper.rb', line 11

def currency_code
  @currency_code
end

#institutionObject (readonly)

name of the source institution



17
18
19
# File 'lib/currency_spy/scraper.rb', line 17

def institution
  @institution
end

#urlObject

url of the source web page



13
14
15
# File 'lib/currency_spy/scraper.rb', line 13

def url
  @url
end

Instance Method Details

#fetch_ratesObject

Method which calls all rate fetching methods from the sub class and returns a Hash with appropriate values.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/currency_spy/scraper.rb', line 40

def fetch_rates
  if self.class.superclass.eql?(Object)
    raise Exception.new("This method should be invoked from CurrencySpy::Scraper sub class")
  else
    check_currency_code_validity
    response = {}
    RATE_DATA.each do |rate|
      symbol = rate.to_sym
      if self.class.instance_methods.include?(symbol)
        value = self.send(symbol)
        response[symbol] = value unless value.nil?
      end
    end
    return response
  end
end

#page(reload = false) ⇒ Object

Returns a Mechanize::Page instance which is the being searched on. If the page was once fetched it’s reuse. To reload, call with an argument evaluating to true.



28
29
30
31
32
33
34
35
36
# File 'lib/currency_spy/scraper.rb', line 28

def page(reload = false)
  return nil if   url.nil?
  unless reload
    @page ||= Mechanize.new.get(url)
  else
    @page = Mechanize.new.get(url)
  end
  return @page
end