Steven
Steven

Reputation: 18014

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?

Upvotes: 1

Views: 2055

Answers (2)

Jed Schneider
Jed Schneider

Reputation: 14671

the idomatic ruby way to handle this is to memoize it

@@warning_said ||= "warning"

Upvotes: 4

Reactormonk
Reactormonk

Reputation: 21730

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.

Upvotes: 3

Related Questions