Class: Openbeautyfacts::Mission

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

Constant Summary collapse

LOCALE_PATHS =

TODO: Add more locales

{
  'fr' => 'missions',
  'uk' => 'missions',
  'us' => 'missions',
  'world' => 'missions'
}

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

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



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/openbeautyfacts/mission.rb', line 15

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

    dom.css('#missions li').map do |mission_dom|
      links = mission_dom.css('a')

      attributes = {
        "title" => links.first.text.strip,
        "url" => URI.join(url, links.first.attr('href')).to_s,
        "description" => mission_dom.css('div').first.children[2].text.gsub('', '').strip,
        "users_count" => links.last.text[/(\d+)/, 1].to_i
      }

      new(attributes)
    end
  end
end

Instance Method Details

#fetchObject Also known as: reload

Fetch mission



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/openbeautyfacts/mission.rb', line 39

def fetch
  if (self.url)
    html = open(self.url).read
    dom = Nokogiri::HTML.fragment(html)

    description = dom.css('#description').first

    # Remove "All missions" link
    users = dom.css('#main_column a')[0..-2].map do |user_link|
      User.new(
        "user_id" => user_link.text.strip,
        "url" => URI.join(self.url, user_link.attr('href')).to_s,
      )
    end

    mission = {
      "title" => dom.css('h1').first.text.strip,
      "description" => description.text.strip,
      "description_long" => description.next.text.strip,

      "users" => users,
      "users_count" => users.count
    }

    self.merge!(mission)
  end

  self
end