Class: Openbeautyfacts::Faq

Inherits:
Hashie::Mash
  • Object
show all
Defined in:
lib/openbeautyfacts/faq.rb

Constant Summary collapse

LOCALE_PATHS =

TODO: Add more locales

{
  'fr' => 'questions-frequentes',
  'uk' => 'faq',
  'us' => 'faq',
  'world' => 'faq'
}

Class Method Summary collapse

Class Method Details

.items(locale: DEFAULT_LOCALE, domain: DEFAULT_DOMAIN) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/openbeautyfacts/faq.rb', line 17

def items(locale: DEFAULT_LOCALE, domain: DEFAULT_DOMAIN)
  if path = LOCALE_PATHS[locale]
    html = open("https://#{locale}.#{domain}/#{path}").read
    dom = Nokogiri::HTML.fragment(html)

    titles = dom.css('#main_column h2')
    titles.each_with_index.map do |item, index|
      paragraphs = []

      element = item.next_sibling
      while !element.nil? && element.node_name != 'h2'
        if element.node_name == 'p'
          paragraphs.push(element)
        end

        element = element.next_sibling
      end

      if index == titles.length - 1
        paragraphs = paragraphs[0..-3]
      end

      new({
        "question" => item.text.strip,
        "answer" => paragraphs.map { |paragraph| paragraph.text.strip.gsub(/\r?\n/, ' ') }.join("\n\n"),
        "answer_html" => paragraphs.map(&:to_html).join
      })
    end
  end
end