Making an option false by default

Viewed 309

This is a common way to set a default in Ruby:

class QuietByDefault
  def initialize(opts = {})
    @verbose = opts[:verbose]
  end
end

This is an easy trap to fall into:

class VerboseNoMatterWhat
  def initialize(opts = {})
    @verbose = opts[:verbose] || true
  end
end

This is a correct way to do it:

class VerboseByDefault
  def initialize(opts = {})
    @verbose = opts.include?(:verbose) ? opts[:verbose] : true
  end
end

What is the best / cleanest way to code VerboseByDefault? (I could factor it out, of course.)

What pattern is widely used, if any, in Ruby code in general? Does ActiveSupport have a pattern for this? (Minimal is better -- I don't need a full command line option parser.)

Ranting P.S.: I don't like the asymmetry between code that handles a default true vs. code that handles a default false option. A pattern that makes changing between the two -- without causing bugs -- would be a good thing to see.

3 Answers
Related