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

时间:2015-10-09 08:44:20

标签: ruby conditional redo

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

我的条件很好,但我认为必须是更好的方法:

  # 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变量?

  4. 感谢您的帮助!

1 个答案:

答案 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