Class: Openfoodfacts::Mission
- Inherits:
-
Hashie::Mash
- Object
- Hashie::Mash
- Openfoodfacts::Mission
- Defined in:
- lib/openfoodfacts/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
-
#fetch ⇒ Object
(also: #reload)
Fetch mission.
Class Method Details
.all(locale: DEFAULT_LOCALE, domain: DEFAULT_DOMAIN) ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/openfoodfacts/mission.rb', line 16 def all(locale: DEFAULT_LOCALE, domain: DEFAULT_DOMAIN) if path = LOCALE_PATHS[locale] url = "https://#{locale}.#{domain}/#{path}" html = URI.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
#fetch ⇒ Object Also known as: reload
Fetch mission
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 68 |
# File 'lib/openfoodfacts/mission.rb', line 40 def fetch if (self.url) html = URI.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 |