Search code examples
rubyinstance-variablesoptparseattr-accessor

Accessing ruby's optparse from a class


I'm fairly new to ruby. I'm trying to use optparse to influence the way my code executes. I would like to get the results from optparse into my class so I can base some conditionals on it.

I spent a good couple of hours googling (optparse, attr_accessor), and implemented the results as best I could, in a sort of trial-and-error way.

Below, I've tried to provide a minimal working example. I apologise if any of the syntax or presentation is off...

require 'optparse'

options = {}
OptionParser.new do |opts|
 opts.banner = "Usage: example.rb [options]"

 opts.on("-v", "--verbose", "Adopt verbose policy") do |v|
  options[:verbose] = v
 end
end.parse!
@options = options

class Chatty

 def initialize
  puts "We're gonna be verbose" if @options[:verbose]
 end

end

Chatty.new

The problem is that @options is nil inside the class. This results in a NoMethodError.

#  ...in `initialize': undefined method `[]' for nil:NilClass (NoMethodError)

But I don't know how to get around that.


Solution

  • @options is an instance variable. The @options you reference at the top level is not the same @options referenced within your Chatty initialization method.

    If you want the options to be accessible within Chatty, you'll need to pass it in (e.g. upon instantiation). For example, instead of:

    @options = options
    
    class Chatty
    
     def initialize
      puts "We're gonna be verbose" if @options[:verbose]
     end
    
    end
    
    Chatty.new
    

    you could do:

    class Chatty
    
      def initialize(options)
        @options = options
        puts "We're gonna be verbose" if @options[:verbose]
      end
    
    end
    
    Chatty.new(options)