Class: Hangry::RecipeParser

Inherits:
Object
  • Object
show all
Defined in:
lib/hangry/recipe_parser.rb

Defined Under Namespace

Classes: NullObject

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(recipe_html) ⇒ RecipeParser

Returns a new instance of RecipeParser.



8
9
10
11
12
13
14
15
# File 'lib/hangry/recipe_parser.rb', line 8

def initialize(recipe_html)
  @recipe_html = recipe_html
  @recipe = Recipe.new
  initialize_nutrition
  self.nokogiri_doc = Nokogiri::HTML(recipe_html)
  self.recipe_ast = nokogiri_doc.css(self.class.root_selector).first
  self.nutrition_ast = recipe_ast && recipe_ast.css(self.class.nutrition_selector)
end

Instance Attribute Details

#nokogiri_docObject

Returns the value of attribute nokogiri_doc.



6
7
8
# File 'lib/hangry/recipe_parser.rb', line 6

def nokogiri_doc
  @nokogiri_doc
end

#nutrition_astObject

Returns the value of attribute nutrition_ast.



6
7
8
# File 'lib/hangry/recipe_parser.rb', line 6

def nutrition_ast
  @nutrition_ast
end

#recipeObject

Returns the value of attribute recipe.



6
7
8
# File 'lib/hangry/recipe_parser.rb', line 6

def recipe
  @recipe
end

#recipe_astObject

Returns the value of attribute recipe_ast.



6
7
8
# File 'lib/hangry/recipe_parser.rb', line 6

def recipe_ast
  @recipe_ast
end

#recipe_htmlObject (readonly)

Returns the value of attribute recipe_html.



5
6
7
# File 'lib/hangry/recipe_parser.rb', line 5

def recipe_html
  @recipe_html
end

Class Method Details

.can_parse?(html) ⇒ Boolean

Returns:

  • (Boolean)


28
29
30
# File 'lib/hangry/recipe_parser.rb', line 28

def self.can_parse?(html)
  new(html).recipe_ast
end

.canonical_url_matches_domain?(html, domain) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/hangry/recipe_parser.rb', line 32

def self.canonical_url_matches_domain?(html, domain)
  CanonicalUrlParser.new(html).canonical_domain == domain
end

Instance Method Details

#parseObject



17
18
19
20
21
22
23
24
25
26
# File 'lib/hangry/recipe_parser.rb', line 17

def parse
  RECIPE_ATTRIBUTES.each do |attribute|
    attr_value = value(send("parse_#{attribute}"))
    recipe.public_send("#{attribute}=", attr_value)
    next unless recipe.public_send(attribute).present?

    send("clean_#{attribute}", recipe) if respond_to? "clean_#{attribute}"
  end
  recipe
end