任务是检查联系人页面是否存在并导航到该页面。对于非英语网站,该方法查找英文页面,然后重新开始检查联系页面。
我的条件很好,但我认为必须是更好的方法:
# 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
变量?
感谢您的帮助!
答案 0 :(得分:1)
这样的东西更具可读性和干燥性
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