代码设计//函数包装器

时间:2012-04-26 10:21:29

标签: ruby-on-rails ruby

我一直想知道如何在代码方面改进这部分代码 设计:

(我特别感兴趣的是用不同的方法调用相同的函数 默认属性 - 大量代码重复)

def follow_pages(number_of_pages = 5, sleep_interval = 5)
  process_pages true, number_of_pages, sleep_interval
end

def unfollow_pages(number_of_pages = 5, sleep_interval = 5)
  process_pages false, number_of_pages, sleep_interval
end

def process_pages(follow = true, number_of_pages = 5, sleep_interval = 5)
  number_of_pages.times do |page|

    sleep rand(sleep_interval)

    if follow
      follow_all_pages
    else
      unfollow_all_pages
    end

  end

end

1 个答案:

答案 0 :(得分:2)

你可以这样做:

def follow_pages(*args)
  process_pages true, *args
end

def unfollow_pages(*args)
  process_pages false, *args
end

def process_pages(follow = true, number_of_pages = 5, sleep_interval = 5)
  ...
end

您基本上接受任何参数,为follow参数添加前缀并将其传递给主proess_page方法。我不确定它是否使代码更具可读性,但它绝对可以避免重复参数的默认值。