Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass array to class option of rails generator?

I'm creating the following ruby class generator:

class Template < Rails::Generators::Base
  source_root File.expand_path('../templates', __FILE__)

  argument :name, type: 'string', required: true
  ...
  class_option :templates, type: 'array', default: [1, 2, 3, 4], aliases: '-t'

  private
  ...

end

In the rails console I tried:

rails generate template test -t=1 2 
rails generate template test -t 1 2 
rails generate template test -t 1,2
rails generate template test -t=1,2  
rails generate template test -t=[1,2]
rails generate template test -t [1,2]

but the generator is not working correctly. It seems that the input doesn't return an array, because the following private method is not working:

def should_be_template_rendered(param)
  options.templates.include? param
end

Where param is simply a number. The result is that none of the templates are rendered at all. I have checked the Thor documentations here and here, but was not able to find an example on how the array is passed as argument.

like image 262
gotqn Avatar asked Oct 22 '25 15:10

gotqn


1 Answers

The following work fine for me

rails generate template test -t=1 2 
rails generate template test -t 1 2 

Just notice that the result is a string array:

options["templates"]
#=> ["1", "2"]
like image 79
lingceng Avatar answered Oct 25 '25 19:10

lingceng