CheapSteaks
CheapSteaks

Reputation: 5019

How to pass a ruby hash as a commandline option?

I'm using slimrb, which has an option called attr_list_delims that expects a hash as the value in the format of:

{'(' => ')', '[' => ']', '{' => '}'}

I need to change that to just

{'(' => ')', '[' => ']'}

I'm not familiar with ruby, is this even possible to pass as a commandline argument?

Wrapping the entire thing in double quotes didn't seem to work

Upvotes: 1

Views: 636

Answers (2)

Chris Cashwell
Chris Cashwell

Reputation: 22899

Perhaps a little less than ideal and not slim-specific, but you could pass it as JSON and use JSON.parse:

# test.rb
require 'json'
puts JSON.parse(ARGV[0])

Then executing it with a parameter that is a string representation of a JSON-ified hash will produce the expected result:

ccashwell:~/dev/fun (master) ✗ ruby test.rb '{"(": ")", "[": "]"}'
{"("=>")", "["=>"]"}

Upvotes: 2

Ajedi32
Ajedi32

Reputation: 48428

From the documentation, it looks like you should be able to do it using the --option flag:

$ slimrb --help
Usage: slimrb [options]
  -o, --option name=code           Set slim option

To me, the word "code" there implies that you can use any Ruby expression you want. If that is indeed correct, you could use it like this:

slimrb --option attr_list_delims="{'(' => ')', '[' => ']'}"

A quick peak at the source code seems to confirm that assumption:

opts.on('-o', '--option name=code', String, 'Set slim option') do |str|
  parts = str.split('=', 2)
  Engine.default_options[parts.first.gsub(/\A:/, '').to_sym] = eval(parts.last)
end

Note that this feature is specific to slimrb, not to Ruby in general.

Upvotes: 3

Related Questions