Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a comma in a string argument to a rake task?

Tags:

I have the following Rakefile:

task :test_commas, :arg1 do |t, args|
  puts args[:arg1]
end

And want to call it with a single string argument containing commas. Here's what I get:

%rake 'test_commas[foo, bar]'
foo

%rake 'test_commas["foo, bar"]'
"foo

%rake "test_commas['foo, bar']"
'foo

%rake "test_commas['foo,bar']"
'foo

%rake "test_commas[foo\,bar]"
foo\

I'm currently using the workaround proposed in this pull request to rake, but is there a way to accomplish this without patching rake?

like image 958
Ben Taitelbaum Avatar asked Aug 31 '11 14:08

Ben Taitelbaum


People also ask

How do I list a rake task?

You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing rake --tasks . Each task has a description, and should help you find the thing you need.


2 Answers

Changing rake is quite a dirty fix. Try using OptionParser instead. The syntax is following

$ rake mytask -- -s 'some,comma,sepparated,string'

the -- is necessary to skip the rake way of parsing the arguments

and here's the ruby code:

task :mytask do
  options = {}

  optparse = OptionParser.new do |opts|
    opts.on('-s', '--string ARG', 'desc of my argument') do |str|
      options[:str] = str
    end

    opts.on('-h', '--help', 'Display this screen') do     
      puts opts                                                          
      exit                                                                      
    end 
  end

  begin 
    optparse.parse!
    mandatory = [:str]
    missing = mandatory.select{ |param| options[param].nil? }
    if not missing.empty?
      puts "Missing options: #{missing.join(', ')}"
      puts optparse
      exit
    end

  rescue OptionParser::InvalidOption, OptionParser::MissingArgument
    puts $!.to_s
    puts optparse
    exit  
  end

  puts "Performing task with options: #{options.inspect}"
  # @TODO add task's code
end
like image 81
Tombart Avatar answered Oct 12 '22 01:10

Tombart


I'm not sure it's possible. Looking at lib/rake/application.rb, the method for parsing the task string is:

def parse_task_string(string)
  if string =~ /^([^\[]+)(\[(.*)\])$/
    name = $1
    args = $3.split(/\s*,\s*/)
  else
    name = string
    args = []
  end 
  [name, args]
end 

It appears that the arguments string is split by commas, so you cannot have an argument that contains a comma, at least not in the current rake-0.9.2.

like image 44
eugen Avatar answered Oct 12 '22 03:10

eugen