Class: GetterCyndi5::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/getter_cyndi5/parser.rb

Constant Summary collapse

DATA_PREFIX =
'data-'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Parser

Returns a new instance of Parser.



5
6
7
8
# File 'lib/getter_cyndi5/parser.rb', line 5

def initialize(options = {})
  @options = options
  @products = []
end

Instance Attribute Details

#productsObject (readonly)

Returns the value of attribute products.



4
5
6
# File 'lib/getter_cyndi5/parser.rb', line 4

def products
  @products
end

Instance Method Details

#item_rowsObject



34
35
36
37
38
# File 'lib/getter_cyndi5/parser.rb', line 34

def item_rows
  document = @options.fetch(:document)
  item_row_selector = @options.fetch(:item_row_selector)
  document.css(item_row_selector)
end

#parseObject



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

def parse
  base_url = @options.fetch(:base_url)
  item_anchor_selector = @options.fetch(:item_anchor_selector)
  item_price_selector = @options.fetch(:item_price_selector)
  item_rows.each do |item_row|
    item_data = item_row.attributes.select { |k, v| k.start_with? DATA_PREFIX }.map { |k, v| [k.delete_prefix(DATA_PREFIX), v.value]}.to_h
    product_element = item_row.css(item_anchor_selector)[0]
    price_elements = item_row.css(item_price_selector)
    prices = {}
    price_elements.each do |price_element|
      prices[price_element.children[1].text] = price_element.children[0].text.gsub(/[^\d\.]/, '').to_f
    end
    attributes = {
      name: product_element.text,
      url: "#{base_url}#{product_element.attributes['href']}",
      item_data: item_data,
      prices: prices
    }
    product = GetterCyndi5::Product.new(attributes)
    products.append(product)
  end
  products
end