Class: Rails::Generators::Base
Class Attribute Summary
- .exit_on_failure? ⇒ Boolean readonly Internal use only
Class Method Summary
-
.base_root
Returns the base root for a common set of generators.
-
.default_source_root
Returns the default source root for a given generator.
-
.desc(description = nil)
Tries to get the description from a USAGE file one folder above the source root otherwise uses a default description.
-
.hide!
Convenience method to hide this generator from the available ones when running rails generator command.
-
.hook_for(*names, &block)
Invoke a generator based on the value supplied by the user to the given option named “name”.
-
.namespace(name = nil)
Convenience method to get the namespace from the class name.
-
.remove_hook_for(*names)
Remove a previously added hook.
-
.source_root(path = nil)
Returns the source root for this generator using default_source_root as default.
-
.add_shebang_option!
private
Small macro to add ruby as an option to the generator with proper default value plus an instance helper method called shebang.
-
.banner
private
Use Rails default banner.
-
.base_name
private
Sets the base_name taking into account the current class namespace.
-
.default_aliases_for_option(name, options)
private
Returns default aliases for the option name given doing a lookup in aliases.
-
.default_for_option(config, name, options, default)
private
Returns default for the option name given doing a lookup in config.
- .default_generator_root private
-
.default_value_for_option(name, options)
private
Returns the default value for the option name given doing a lookup in options.
-
.generator_name
private
Removes the namespaces and get the generator name.
- .usage_path private
- .class_option(name, options = {}) Internal use only
-
.inherited(base)
Internal use only
Cache source root and add lib/generators/base/generator/templates to source paths.
-
.hooks
private
Internal use only
Keep hooks configuration that are used on prepare_for_invocation.
-
.prepare_for_invocation(name, value)
private
Internal use only
Prepare class invocation to search on
::Rails
namespace if a previous added hook is being used.
Instance Attribute Summary
- #namespaced? ⇒ Boolean readonly private
Instance Method Summary
-
#class_collisions(*class_names)
private
Check whether the given class names are already taken by user application or Ruby on
::Rails
. -
#extract_last_module(nesting)
private
Takes in an array of nested modules and extracts the last module.
- #indent(content, multiplier = 2) private
-
#module_namespacing(&block)
private
Wrap block with namespace of current application if namespace exists and is not skipped.
- #namespace private
- #namespace_dirs private
- #namespaced_path private
- #wrap_with_namespace(content) private
Actions
- Included
#add_source | Add the given source to |
#application | Alias for Actions#environment. |
#environment | Adds configuration code to a Rails runtime environment. |
#gem | Adds a |
#gem_group | Wraps gem entries inside a group. |
#generate | Runs another generator. |
#git | Runs one or more git commands. |
#github, | |
#initializer | Creates an initializer file in |
#lib | Creates a file in |
#rails_command | Runs the specified Rails command. |
#rake | Runs the specified Rake task. |
#rakefile | Creates a Rake tasks file in |
#readme | Reads the given file at the source root and prints it in the console. |
#route | Make an entry in Rails routing file |
#vendor | Creates a file in |
#append_file_with_newline | Append string to a file with a newline if necessary. |
#execute_command | Runs the supplied command using either “rake …” or “rails …” based on the executor parameter provided. |
#indentation | Indent the |
#log | Define log for backwards compatibility. |
#match_file, | |
#optimize_indentation | Returns optimized string with indentation. |
#quote | Always returns value in double quotes. |
#rebase_indentation | Alias for Actions#optimize_indentation. |
#route_namespace_pattern, | |
#with_indentation | Manage |
#initialize |
Class Attribute Details
.exit_on_failure? ⇒ Boolean
(readonly)
# File 'railties/lib/rails/generators/base.rb', line 29
def self.exit_on_failure? # :nodoc: false end
Class Method Details
.add_shebang_option! (private)
Small macro to add ruby as an option to the generator with proper default value plus an instance helper method called shebang.
# File 'railties/lib/rails/generators/base.rb', line 396
def self.add_shebang_option! # :doc: class_option :ruby, type: :string, aliases: "-r", default: Thor::Util.ruby_command, desc: "Path to the Ruby binary of your choice", banner: "PATH" no_tasks { define_method :shebang do @shebang ||= begin command = if [:ruby] == Thor::Util.ruby_command "/usr/bin/env #{File.basename(Thor::Util.ruby_command)}" else [:ruby] end "#!#{command}" end end } end
.banner (private)
Use Rails default banner.
# File 'railties/lib/rails/generators/base.rb', line 329
def self. # :doc: "bin/rails generate #{namespace.delete_prefix("rails:")} #{arguments.map(&:usage).join(' ')} [options]".gsub(/\s+/, " ") end
.base_name (private)
Sets the base_name taking into account the current class namespace.
# File 'railties/lib/rails/generators/base.rb', line 334
def self.base_name # :doc: @base_name ||= if base = name.to_s.split("::").first base.underscore end end
.base_root
Returns the base root for a common set of generators. This is used to dynamically guess the default source root.
# File 'railties/lib/rails/generators/base.rb', line 236
def self.base_root __dir__ end
.class_option(name, options = {})
Make class option aware of Rails::Generators.options and Rails::Generators.aliases.
# File 'railties/lib/rails/generators/base.rb', line 217
def self.class_option(name, = {}) # :nodoc: [:desc] = "Indicates when to generate #{name.to_s.humanize.downcase}" unless .key?(:desc) [:aliases] = default_aliases_for_option(name, ) [:default] = default_value_for_option(name, ) super(name, ) end
.default_aliases_for_option(name, options) (private)
Returns default aliases for the option name given doing a lookup in Rails::Generators.aliases.
# File 'railties/lib/rails/generators/base.rb', line 357
def self.default_aliases_for_option(name, ) # :doc: default_for_option(Rails::Generators.aliases, name, , [:aliases]) end
.default_for_option(config, name, options, default) (private)
Returns default for the option name given doing a lookup in config.
# File 'railties/lib/rails/generators/base.rb', line 362
def self.default_for_option(config, name, , default) # :doc: if generator_name && (c = config[generator_name.to_sym]) && c.key?(name) c[name] elsif base_name && (c = config[base_name.to_sym]) && c.key?(name) c[name] elsif config[:rails].key?(name) config[:rails][name] else default end end
.default_generator_root (private)
[ GitHub ].default_source_root
Returns the default source root for a given generator. This is used internally by ::Rails
to set its generators source root. If you want to customize your source root, you should use source_root.
# File 'railties/lib/rails/generators/base.rb', line 227
def self.default_source_root return unless base_name && generator_name return unless default_generator_root path = File.join(default_generator_root, "templates") path if File.exist?(path) end
.default_value_for_option(name, options) (private)
Returns the default value for the option name given doing a lookup in Rails::Generators.options.
# File 'railties/lib/rails/generators/base.rb', line 351
def self.default_value_for_option(name, ) # :doc: default_for_option(Rails::Generators., name, , [:default]) end
.desc(description = nil)
Tries to get the description from a USAGE file one folder above the source root otherwise uses a default description.
# File 'railties/lib/rails/generators/base.rb', line 41
def self.desc(description = nil) return super if description @desc ||= if usage_path ERB.new(File.read(usage_path)).result(binding) else "Description:\n Create #{base_name.humanize.downcase} files for #{generator_name} generator." end end
.generator_name (private)
Removes the namespaces and get the generator name. For example, ModelGenerator
will return “model” as generator name.
# File 'railties/lib/rails/generators/base.rb', line 342
def self.generator_name # :doc: @generator_name ||= if generator = name.to_s.split("::").last generator.delete_suffix!("Generator") generator.underscore end end
.hide!
Convenience method to hide this generator from the available ones when running rails generator command.
# File 'railties/lib/rails/generators/base.rb', line 61
def self.hide! Rails::Generators.hide_namespace(namespace) end
.hook_for(*names, &block)
Invoke a generator based on the value supplied by the user to the given option named “name”. A class option is created when this method is invoked and you can set a hash to customize it.
Examples
module Rails::Generators
class ControllerGenerator < Base
hook_for :test_framework, aliases: "-t"
end
end
The example above will create a test framework option and will invoke a generator based on the user supplied value.
For example, if the user invoke the controller generator as:
$ bin/rails generate controller Account --test-framework=test_unit
The controller generator will then try to invoke the following generators:
"rails:test_unit", "test_unit:controller", "test_unit"
Notice that “rails:generators:test_unit” could be loaded as well, what Rails looks for is the first and last parts of the namespace. This is what allows any test framework to hook into Rails as long as it provides any of the hooks above.
Options
The first and last part used to find the generator to be invoked are guessed based on class invokes hook_for, as noticed in the example above. This can be customized with two options: :in
and :as
.
Let’s suppose you are creating a generator that needs to invoke the controller generator from test unit. Your first attempt is:
class AwesomeGenerator < Rails::Generators::Base
hook_for :test_framework
end
The lookup in this case for test_unit as input is:
"test_unit:awesome", "test_unit"
Which is not the desired lookup. You can change it by providing the :as
option:
class AwesomeGenerator < Rails::Generators::Base
hook_for :test_framework, as: :controller
end
And now it will look up at:
"test_unit:controller", "test_unit"
Similarly, if you want it to also look up in the rails namespace, you just need to provide the :in
value:
class AwesomeGenerator < Rails::Generators::Base
hook_for :test_framework, in: :rails, as: :controller
end
And the lookup is exactly the same as previously:
"rails:test_unit", "test_unit:controller", "test_unit"
Switches
All hooks come with switches for user interface. If you do not want to use any test framework, you can do:
$ bin/rails generate controller Account --skip-test-framework
Or similarly:
$ bin/rails generate controller Account --no-test-framework
Boolean hooks
In some cases, you may want to provide a boolean hook. For example, webrat developers might want to have webrat available on controller generator. This can be achieved as:
Rails::Generators::ControllerGenerator.hook_for :webrat, type: :boolean
Then, if you want webrat to be invoked, just supply:
$ bin/rails generate controller Account --webrat
The hooks lookup is similar as above:
"rails:generators:webrat", "webrat:generators:controller", "webrat"
Custom invocations
You can also supply a block to hook_for to customize how the hook is going to be invoked. The block receives two arguments, an instance of the current class and the class to be invoked.
For example, in the resource generator, the controller should be invoked with a pluralized class name. But by default it is invoked with the same name as the resource generator, which is singular. To change this, we can give a block to customize how the controller can be invoked.
hook_for :resource_controller do |instance, controller|
instance.invoke controller, [ instance.name.pluralize ]
end
# File 'railties/lib/rails/generators/base.rb', line 174
def self.hook_for(*names, &block) = names. in_base = .delete(:in) || base_name as_hook = .delete(:as) || generator_name names.each do |name| unless .key?(name) defaults = if [:type] == :boolean {} elsif [true, false].include?(default_value_for_option(name, )) { banner: "" } else { desc: "#{name.to_s.humanize} to be invoked", banner: "NAME" } end class_option(name, defaults.merge!( )) end klass = self singleton_class.define_method("#{name}_generator") do value = [name].default Rails::Generators.find_by_namespace(klass.generator_name, value) end hooks[name] = [ in_base, as_hook ] invoke_from_option(name, , &block) end end
.hooks (private)
Keep hooks configuration that are used on prepare_for_invocation.
# File 'railties/lib/rails/generators/base.rb', line 375
def self.hooks # :nodoc: @hooks ||= from_superclass(:hooks, {}) end
.inherited(base)
Cache source root and add lib/generators/base/generator/templates to source paths.
# File 'railties/lib/rails/generators/base.rb', line 242
def self.inherited(base) # :nodoc: super # Invoke source_root so the default_source_root is set. base.source_root if base.name && !base.name.end_with?("Base") Rails::Generators.subclasses << base Rails::Generators.templates_path.each do |path| if base.name.include?("::") base.source_paths << File.join(path, base.base_name, base.generator_name) else base.source_paths << File.join(path, base.generator_name) end end end end
.namespace(name = nil)
Convenience method to get the namespace from the class name. It’s the same as Thor default except that the Generator at the end of the class is removed.
# File 'railties/lib/rails/generators/base.rb', line 54
def self.namespace(name = nil) return super if name @namespace ||= super.delete_suffix("_generator").sub(/:generators:/, ":") end
.prepare_for_invocation(name, value) (private)
Prepare class invocation to search on ::Rails
namespace if a previous added hook is being used.
# File 'railties/lib/rails/generators/base.rb', line 381
def self.prepare_for_invocation(name, value) # :nodoc: return super unless value.is_a?(String) || value.is_a?(Symbol) if value && constants = hooks[name] value = name if TrueClass === value Rails::Generators.find_by_namespace(value, *constants) elsif klass = Rails::Generators.find_by_namespace(value) klass else super end end
.remove_hook_for(*names)
Remove a previously added hook.
remove_hook_for :orm
# File 'railties/lib/rails/generators/base.rb', line 207
def self.remove_hook_for(*names) remove_invocation(*names) names.each do |name| singleton_class.undef_method("#{name}_generator") hooks.delete(name) end end
.source_root(path = nil)
Returns the source root for this generator using default_source_root as default.
# File 'railties/lib/rails/generators/base.rb', line 34
def self.source_root(path = nil) @_source_root = path if path @_source_root ||= default_source_root end
.usage_path (private)
[ GitHub ]# File 'railties/lib/rails/generators/base.rb', line 414
def self.usage_path # :doc: paths = [ source_root && File. ("../USAGE", source_root), default_generator_root && File.join(default_generator_root, "USAGE") ] paths.compact.detect { |path| File.exist? path } end
Instance Attribute Details
#namespaced? ⇒ Boolean
(readonly, private)
[ GitHub ]
# File 'railties/lib/rails/generators/base.rb', line 316
def namespaced? # :doc: ! [:skip_namespace] && namespace end
Instance Method Details
#class_collisions(*class_names) (private)
Check whether the given class names are already taken by user application or Ruby on ::Rails
.
# File 'railties/lib/rails/generators/base.rb', line 264
def class_collisions(*class_names) return unless behavior == :invoke return if .skip_collision_check? return if .force? class_names.flatten.each do |class_name| class_name = class_name.to_s next if class_name.strip.empty? # Split the class from its module nesting nesting = class_name.split("::") last_name = nesting.pop last = extract_last_module(nesting) if last && last.const_defined?(last_name.camelize, false) raise Error, "The name '#{class_name}' is either already used in your application " \ "or reserved by Ruby on Rails. Please choose an alternative or use --skip-collision-check " \ "or --force to skip this check and run this generator again." end end end
#extract_last_module(nesting) (private)
Takes in an array of nested modules and extracts the last module
# File 'railties/lib/rails/generators/base.rb', line 287
def extract_last_module(nesting) # :doc: nesting.inject(Object) do |last_module, nest| break unless last_module.const_defined?(nest, false) last_module.const_get(nest) end end
#indent(content, multiplier = 2) (private)
[ GitHub ]# File 'railties/lib/rails/generators/base.rb', line 302
def indent(content, multiplier = 2) # :doc: spaces = " " * multiplier content.each_line.map { |line| line.blank? ? line : "#{spaces}#{line}" }.join end
#module_namespacing(&block) (private)
Wrap block with namespace of current application if namespace exists and is not skipped
# File 'railties/lib/rails/generators/base.rb', line 296
def module_namespacing(&block) # :doc: content = capture(&block) content = wrap_with_namespace(content) if namespaced? concat(content) end
#namespace (private)
[ GitHub ]# File 'railties/lib/rails/generators/base.rb', line 312
def namespace # :doc: Rails::Generators.namespace end
#namespace_dirs (private)
[ GitHub ]# File 'railties/lib/rails/generators/base.rb', line 320
def namespace_dirs @namespace_dirs ||= namespace.name.split("::").map(&:underscore) end
#namespaced_path (private)
[ GitHub ]# File 'railties/lib/rails/generators/base.rb', line 324
def namespaced_path # :doc: @namespaced_path ||= namespace_dirs.join("/") end