Class: MetaInfo::Document

Inherits:
Object
  • Object
show all
Defined in:
lib/meta_info/document.rb

Instance Method Summary collapse

Constructor Details

#initialize(html) ⇒ Document

Returns a new instance of Document.



5
6
7
8
# File 'lib/meta_info/document.rb', line 5

def initialize(html)
  raise MetaInfo::Exception::NoHTML if html.nil? || html.empty?
  @doc = Nokogiri::HTML.parse(html)
end

Instance Method Details

#descriptionObject



18
19
20
# File 'lib/meta_info/document.rb', line 18

def description
  get_attr("description") || meta_description
end

#docObject



10
11
12
# File 'lib/meta_info/document.rb', line 10

def doc
  @doc
end

#get_attr(name) ⇒ Object



50
51
52
# File 'lib/meta_info/document.rb', line 50

def get_attr(name)
  og_attr(name) || twitter_attr(name)
end

#imageObject



22
23
24
# File 'lib/meta_info/document.rb', line 22

def image
  get_attr("image")
end

#meta_descriptionObject



30
31
32
# File 'lib/meta_info/document.rb', line 30

def meta_description
  search_meta("name", /^description$/i, "content")
end

#meta_titleObject



42
43
44
45
46
47
48
# File 'lib/meta_info/document.rb', line 42

def meta_title
  if doc.css("title").empty?
    return false
  else
    return doc.css("title")[0].text
  end
end

#og_attr(name) ⇒ Object



38
39
40
# File 'lib/meta_info/document.rb', line 38

def og_attr(name)
  search_meta('property', /^og:#{name}$/i, 'content')
end

#search_meta(attribute, regexp, value_key) ⇒ Object



54
55
56
57
58
59
60
61
# File 'lib/meta_info/document.rb', line 54

def search_meta(attribute, regexp, value_key)
  doc.css('meta').each do |m|
    if m.attribute(attribute) && m.attribute(attribute).to_s.match(regexp)
      return m.attribute(value_key).to_s
    end
  end
  return false
end

#titleObject



14
15
16
# File 'lib/meta_info/document.rb', line 14

def title
  get_attr("title") || meta_title
end

#twitter_attr(name) ⇒ Object



34
35
36
# File 'lib/meta_info/document.rb', line 34

def twitter_attr(name)
  search_meta('name', /^twitter:#{name}$/i, 'content')
end

#valid?Boolean

Returns:

  • (Boolean)


26
27
28
# File 'lib/meta_info/document.rb', line 26

def valid?
  title && description != false
end