So I am figuring out how to set up some options for a class. ‘options’ is a hash. I want to
1) filter out options I don’t want or need
2) set some instance variables to use elsewhere
3) and set up another hash with the processed options as @current_options.
def initialize_options(options)
@whitelisted_options, @current_options = [:timestamps_offset, :destructive, :minimal_author], {}
n_options = options.select { |k,v| @whitelisted_options.include?(k) }
@current_options[:timestamps_offset] = @timestamp_offset = n_options.fetch(:timestamps_offset, 0)*(60*60*24)
@current_options[:destructive] = @destructive = n_options.fetch(:destructive, false)
@current_options[:minimal_author] = @minimal_author = n_options.fetch(:minimal_author, false)
end
I’m guessing this is a bit much, no matter what I pass in I get:
{:timestamps_offset=>0, :destructive=>false, :minimal_author=>false}
When I do this line by line from the command line, it works as I want it to but not in my class. So what is going on and how do I clean this up?
EDIT: this actually works disembodied from the class I’m using it in, but inside it doesn’t so the reality is something is going on I’m not aware of right now.
attr_reader :current_options is how this is set on the class, perhaps that needs some revision.
EDIT2: line 2 of the method is supposed to select from @whitelisted_options
EDIT3: Actually turned out to be something I wasn’t thinking of…”options” comes in parsed from a yaml file as strings….and I was fetching symbols, changing that around makes a difference where before the method was looking for symbols and finding none, e.g. “destructive” vs :destructive, so always defaulting to the defaults. In short, I just needed to symbolize the hash keys when options are imported.
Your@current_optionsis initialized as an empty hash. When you filter theoptionspassed as params, none of the keys will be present in@current_optionsson_optionswill end up empty.Then when you set up
@current_optionsin the following lines, it will always grab the default values(0, false, false), and that’s why your output’s always the same.You solve this problem by conditionally initializing @current_options so that it’s only set to
{}once:@current_options ||= {}
Post-OP edit:
Your issue’s with
options.select— in Ruby 1.8, it doesn’t return a Hash, but rather an Array. Your calls tofetchare then always failing (as symbols can’t be array indexes), so always returning defaults.Instead, try:
where
pis an array containing each key/value pair.In Ruby 1.9.2,
Hash.selectbehaves the way you expected it to.Edit 2: Here’s how I’d approach it:
In use: