开发者

How to make a function call that happens only once in Ruby/Rails

A gem/plugin 开发者_开发技巧that I'm using to support my test suite calls some GNU commands that cause the Windows shell to roll over and die. I can rewrite these functions with a bypass in this fashion:

def get_rake_output(task)
  if RUBY_PLATFORM.include? 'mingw'
    puts 'Skipped since OS is Windows. Run the test suite on a UNIX-like shell.'
    ''
  else
    `./rake --silent #{task}`
  end
end

Of course, this prints the message every time the function is called. How do I best make sure that it displays only once?


the idomatic ruby way to handle this is to memoize it

@@warning_said ||= "warning"


It's method in ruby.</rant>. Use a class variable like @@warning_said and check for that one. Aka

puts "Ruby does not like Windows here" unless @@warning_said
@@warning_said = true

I'm not exaclty sure what scope you are operating in, but that should do it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜