任务是检查联系人页面是否存在并导航到该页面。对于非英文的网站,该方法查找英文页面,然后重新启动以检查联系人页面。
我的条件工作得很好,但我认为必须是更好的方法:
# First, I set the @url variable during Booleans.
# Checks are either to see if a link exists or if a page exists,
# (aka no 404 error).
#
# Here are two examples:
# Boolean, returns true if contact link is present.
def contact_link?
@url = link_with_href('contact')
!@url.nil?
end
# True if contact page '../contact' does NOT get a 404 error.
def contact_page?
@url = page.uri.merge('../contact').to_s
begin
true if Mechanize.new.get(@url)
rescue Mechanize::ResponseCodeError
false
end
end
# #
# Now go to the correct page, based off of checks.
#
def go_to_contact_page
1.times do
case # No redo necessary.
when contact_link? # True if hyperlink exists
get(@url)
when contact_page? # False if 404 error
get(@url)
else # Redo is now necessary.
if english_link? # True if hyperlink exists
get(@url)
redo
elsif en_page? # False if 404 error
get(@url)
redo
elsif english_page? # False if 404 error
redo
end
end
end
end
有几件事需要引起你的注意:
1.times do
是做单个redo
的最佳方式吗?begin
会更好吗?理解我在每个检查中设置
@url
变量,在条件分支中get(@url)
似乎有冗余。有没有更简洁的方法?我写了三次
redo
,这似乎也是多余的。是否有一种方法来调用它一次,仍然设置@url
变量?
谢谢你的帮助!
这样的东西更容易读,更简洁
def english_contact_page
..
rescue
nil
end
def contact_page
..
rescue
nil
end
def get_page
@url = link_with_href('contact')
return nil if @url.nil?
contact_page || english_contact_page # left side is evaluated first
rescue
nil
end