Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Mechanize::Page::Link#text is now lazily populated
  • Loading branch information
drbrain committed Jun 24, 2011
1 parent d74ad51 commit 9ec3d57
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 22 deletions.
4 changes: 3 additions & 1 deletion lib/mechanize/page/frame.rb
@@ -1,12 +1,14 @@
class Mechanize
class Page < Mechanize::File
class Page
# This class encapsulates a 'frame' tag. Frame objects can be treated
# just like Link objects. They contain src, the link they refer to,
# name, the name of the frame. 'src' and 'name' are aliased to 'href'
# and 'text' respectively so that a Frame object can be treated just
# like a Link.
class Frame < Link
alias :src :href

attr_reader :text
alias :name :text

def initialize(node, mech, referer)
Expand Down
49 changes: 29 additions & 20 deletions lib/mechanize/page/link.rb
Expand Up @@ -11,32 +11,28 @@
class Mechanize::Page::Link
attr_reader :node
attr_reader :href
attr_reader :text
attr_reader :attributes
attr_reader :page
alias :to_s :text
alias :referer :page

def initialize(node, mech, page)
@node = node
@href = node['href']
@text = node.inner_text
@text = nil
@page = page
@mech = mech
@attributes = node
end

# If there is no text, try to find an image and use it's alt text
if (@text.nil? || @text.length == 0) && node.search('img').length > 0
@text = ''
node.search('img').each do |e|
@text << ( e['alt'] || '')
end
end

# Click on this link
def click
@mech.click self
end

def uri
@href && URI.parse(WEBrick::HTTPUtils.escape(@href))
# This method is a shorthand to get link's DOM id.
# Common usage: page.link_with(:dom_id => "links_exact_id")
def dom_id
node['id']
end

# A list of words in the rel attribute, all lower-cased.
Expand All @@ -49,15 +45,28 @@ def rel?(kind)
rel.include?(kind)
end

# Click on this link
def click
@mech.click self
# The text content of this link
def text
return @text if @text

@text = node.inner_text

# If there is no text, try to find an image and use it's alt text
if (@text.nil? or @text.empty?) and not node.search('img').empty? then
@text = ''

@node.search('img').each do |e|
@text << ( e['alt'] || '')
end
end

@text
end

# This method is a shorthand to get link's DOM id.
# Common usage: page.link_with(:dom_id => "links_exact_id")
def dom_id
node['id']
alias :to_s :text

def uri
@href && URI.parse(WEBrick::HTTPUtils.escape(@href))
end

end
Expand Down
2 changes: 1 addition & 1 deletion test/test_pretty_print.rb
Expand Up @@ -4,7 +4,7 @@ class TestPrettyPrint < Test::Unit::TestCase
def setup
@agent = Mechanize.new
end

def test_pretty_print
@agent.get("http://localhost/tc_pretty_print.html")
pretty_string = @agent.pretty_print_inspect
Expand Down

0 comments on commit 9ec3d57

Please sign in to comment.