重做条件语句的正确 ruby 方法是什么?

What is the proper ruby way to redo a conditional?

任务是检查联系人页面是否存在并导航到该页面。对于非英文网站,该方法查找英文页面,然后重新启动以检查联系页面。

我的条件工作正常,但我认为必须是一个更好的方法:

  # 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. 1.times do是单人redo的最佳方式吗? begin 会更好吗?

  2. 据了解我在这些检查中的每一个中都设置了 @url 变量,在条件分支的 get(@url) 中似乎存在冗余。有没有更简洁的方法?

  3. 我写了三遍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