Class: Forex::TabularRates

Inherits:
Object
  • Object
show all
Defined in:
lib/forex/tabular_rates.rb

Constant Summary collapse

NoSuchColumn =
Class.new(StandardError)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(table, options) ⇒ TabularRates

Returns a new instance of TabularRates.



7
8
9
10
# File 'lib/forex/tabular_rates.rb', line 7

def initialize(table, options)
  @table = table
  @options = options.symbolize_keys
end

Instance Attribute Details

#optionsObject

Returns the value of attribute options.



5
6
7
# File 'lib/forex/tabular_rates.rb', line 5

def options
  @options
end

#tableObject

Returns the value of attribute table.



5
6
7
# File 'lib/forex/tabular_rates.rb', line 5

def table
  @table
end

Instance Method Details

#column_labelsObject



34
35
36
# File 'lib/forex/tabular_rates.rb', line 34

def column_labels
  [:buy_cash, :buy_draft, :sell_cash, :sell_draft]
end

#parse_ratesObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/forex/tabular_rates.rb', line 12

def parse_rates
  currency = options.delete(:currency_code) || 0

  table.css('tr').each_with_object({}) do |tr, currencies|
    cells = tr.css('td')
    next if cells.empty?

    currency_code = CurrencyCode.new(cells[currency.to_i].content)

    next if currencies.has_key?(currency_code.to_s) || currency_code.invalid?

    currencies[currency_code.to_s] = column_labels.each_with_object({}) do |column_label, rates|
      next unless rate_column = options[column_label]

      rate_node = cells[rate_column.to_i]
      raise NoSuchColumn, "#{column_label} (#{rate_column}) does not exist in table" unless rate_node

      rates[column_label.to_sym] = Currency.new(rate_node.content).value
    end
  end
end