http://guides.rubyonrails.org/generators.html#creating-generators-with-generators
rails generate generator --help
rails generate generator setup_config
First, notice that we are inheriting from Rails::Generators::NamedBase
instead of Rails::Generators::Base
. This means that our generator expects at least one argument, which will be the name of the initializer, and will be available in our code in the variable name.
class SetupConfigGenerator < Rails::Generators::Base
desc "Creates nginx, unicorn, mongoid etc configuration file"
source_root File.expand_path('../templates', __FILE__)
argument :app_name, type: :string, optional: true, default: "#{Rails::Application.subclasses.first.parent.to_s.underscore}"
class_option :app_root, type: :string, desc: "The Root directory for current application", default: "#{Rails.root}"
class_option :unicorn_port, type: :string, desc: "The port unicorn use", default: "7788"
class_option :unicorn_worker_processes, type: :string, desc: "sets the current number of worker_processes to nr", default: 5
def create_mongoid_yml
copy_file 'mongoid.yml', File.join('config', "mongoid.yml")
end
def create_nginx_config
template 'nginx.conf', File.join('config', "nginx.conf")
end
def create_unicorn_config
template 'unicorn.conf.rb', File.join('config', "unicorn.conf.rb")
template 'unicorn_init.sh', File.join('config', "unicorn_init.sh")
end
end
sudo ln -nfs /home/gxdevelop/dev/guanxime_mobile_felix/config/nginx.conf /etc/nginx/conf.d/guanxime_mobile_felix.conf
sudo ln -nfs /home/gxdevelop/dev/guanxime_mobile_felix/config/unicorn_init.sh /etc/init.d/guanxime_mobile_felix
rails g setup_config guanxime_mobile_felix --unicorn-port=7890
class SetupConfigGenerator < Rails::Generators::NamedBase
The class created by the generator inherits from Rails::Generators::NamedBase
. This means that a name will be required when running the generator in the same way as we had to provide a name when we ran the generator generator. We can see this by running our new generator with the --help
option.
class SetupConfigGenerator < Rails::Generators::Base
We want the NAME
option to be optional and to have a default of application. We can do this by having the class inherit from Rails::Generators::Base
, instead of NamedBase
. This will make all of the arguments optional and therefore give us more flexibility to customize the generator to our needs.
We can define the arguments that the generator takes by using the argument method. Defining our own arguments instead of using the default NAME
option means that we can define a default value for each argument. We’ll add a layout_name
argument with a default value of application.