- A
- E
- G
- I
- L
- O
- Q
- R
- V
- W
Instance Public methods
add_source(source, options = {}, &block)Link
Add the given source toGemfile
If block is given, gem entries in block are wrapped into the source group.
add_source "http://gems.github.com/"add_source "http://gems.github.com/" do gem "rspec-rails"end
# File railties/lib/rails/generators/actions.rb, line 151defadd_source(source,options = {},&block)log:source,sourcein_rootdoifblockappend_file_with_newline"Gemfile","\nsource #{quote(source)} do",force:truewith_indentation(&block)append_file_with_newline"Gemfile","end",force:trueelseprepend_file"Gemfile","source #{quote(source)}\n",verbose:falseendendend
application(data = nil, options = {})Link
environment(data = nil, options = {})Link
Adds configuration code to a Rails runtime environment.
By default, adds code inside theApplication
class inconfig/application.rb
so that it applies to all environments.
environment %(config.asset_host = "cdn.provider.com")
Results in:
# config/application.rbclass Application < Rails::Application config.asset_host = "cdn.provider.com" # ...end
If the:env
option is specified, the code will be added to the corresponding file inconfig/environments
instead.
environment %(config.asset_host = "localhost:3000"), env: "development"
Results in:
# config/environments/development.rbRails.application.configure do config.asset_host = "localhost:3000" # ...end
:env
can also be an array. In which case, the code is added to each corresponding file inconfig/environments
.
The code can also be specified as the return value of the block:
environment do %(config.asset_host = "cdn.provider.com")endenvironment(nil, env: "development") do %(config.asset_host = "localhost:3000")end
# File railties/lib/rails/generators/actions.rb, line 206defenvironment(data =nil,options = {})sentinel ="class Application < Rails::Application\n"env_file_sentinel ="Rails.application.configure do\n"data||=yieldifblock_given?in_rootdoifoptions[:env].nil?inject_into_file"config/application.rb",optimize_indentation(data,4),after:sentinel,verbose:falseelseArray(options[:env]).eachdo|env|inject_into_file"config/environments/#{env}.rb",optimize_indentation(data,2),after:env_file_sentinel,verbose:falseendendendend
gem(*args)Link
Adds agem
declaration to theGemfile
for the specified gem.
gem "rspec", group: :testgem "technoweenie-restful-authentication", lib: "restful-authentication", source: "http://gems.github.com/"gem "rails", "3.0", git: "https://github.com/rails/rails"gem "RedCloth", ">= 4.1.0", "< 4.2.0"gem "rspec", comment: "Put this comment above the gem declaration"
Note that this method only adds the gem to theGemfile
; it does not install the gem.
Options
:version
The version constraints for the gem, specified as a string or an array of strings:
gem "my_gem", version: "~> 1.1"gem "my_gem", version: [">= 1.1", "< 2.0"]
Alternatively, can be specified as one or more arguments following the gem name:
gem "my_gem", ">= 1.1", "< 2.0"
:comment
Outputs a comment above the
gem
declaration in theGemfile
.gem "my_gem", comment: "First line.\nSecond line."
Outputs:
# First line.# Second line.gem "my_gem"
:group
The gem group in the
Gemfile
that the gem belongs to.:git
The URL of the git repository for the gem.
Any additional options passed to this method will be appended to thegem
declaration in theGemfile
. For example:
gem "my_gem", comment: "Edge my_gem", git: "https://example.com/my_gem.git", branch: "master"
Outputs:
# Edge my_gemgem "my_gem", git: "https://example.com/my_gem.git", branch: "master"
# File railties/lib/rails/generators/actions.rb, line 67defgem(*args)options =args.extract_options!name,*versions =args# Set the message to be shown in logs. Uses the git repo if one is given,# otherwise use name (version).parts,message = [quote(name) ],name.dup# Output a comment above the gem declaration.comment =options.delete(:comment)ifversions =versions.any??versions:options.delete(:version)_versions =Array(versions)_versions.eachdo|version|parts<<quote(version)endmessage<<" (#{_versions.join(", ")})"endmessage =options[:git]ifoptions[:git]log:gemfile,messageparts<<quote(options)unlessoptions.empty?in_rootdostr = []ifcommentcomment.each_linedo|comment_line|str<<indentationstr<<"# #{comment_line}"endstr<<"\n"endstr<<indentationstr<<"gem #{parts.join(", ")}"append_file_with_newline"Gemfile",str.join,verbose:falseendend
gem_group(*names, &block)Link
Wraps gem entries inside a group.
gem_group :development, :test do gem "rspec-rails"end
# File railties/lib/rails/generators/actions.rb, line 111defgem_group(*names,&block)options =names.extract_options!str =names.map(&:inspect)str<<quote(options)unlessoptions.empty?str =str.join(", ")log:gemfile,"group #{str}"in_rootdoappend_file_with_newline"Gemfile","\ngroup #{str} do",force:truewith_indentation(&block)append_file_with_newline"Gemfile","end",force:trueendend
generate(what, *args)Link
Runs another generator.
generate "scaffold", "Post title:string body:text"generate "scaffold", "Post", "title:string", "body:text"
The first argument is the generator name, and the remaining arguments are joined together and passed to the generator.
git(commands = {})Link
Runs one or more git commands.
git :init# => runs `git init`git add: "this.file that.rb"# => runs `git add this.file that.rb`git commit: "-m 'First commit'"# => runs `git commit -m 'First commit'`git add: "good.rb", rm: "bad.cxx"# => runs `git add good.rb; git rm bad.cxx`
github(repo, options = {}, &block)Link
# File railties/lib/rails/generators/actions.rb, line 125defgithub(repo,options = {},&block)str = [quote(repo)]str<<quote(options)unlessoptions.empty?str =str.join(", ")log:github,"github #{str}"in_rootdoif@indentation.zero?append_file_with_newline"Gemfile","\ngithub #{str} do",force:trueelseappend_file_with_newline"Gemfile","#{indentation}github #{str} do",force:trueendwith_indentation(&block)append_file_with_newline"Gemfile","#{indentation}end",force:trueendend
initializer(filename, data = nil)Link
Creates an initializer file inconfig/initializers/
. The code can be specified as an argument or as the return value of the block.
initializer "api.rb", <<~RUBY API_KEY = "123456"RUBYinitializer "api.rb" do %(API_KEY = "123456")end
lib(filename, data = nil)Link
Creates a file inlib/
. The contents can be specified as an argument or as the return value of the block.
lib "foreign.rb", <<~RUBY # Foreign code is funRUBYlib "foreign.rb" do "# Foreign code is fun"end
rails_command(command, options = {})Link
Runs the specified Rails command.
rails_command "db:migrate"rails_command "db:migrate", env: "production"rails_command "db:migrate", abort_on_failure: truerails_command "stats", capture: truerails_command "gems:install", sudo: true
Options
:env
The Rails environment in which to run the command. Defaults to
ENV["RAILS_ENV"] || "development"
.:abort_on_failure
Whether to halt the generator if the command exits with a non-success exit status.
:capture
Whether to capture and return the output of the command.
:sudo
Whether to run the command using
sudo
.
# File railties/lib/rails/generators/actions.rb, line 391defrails_command(command,options = {})ifoptions[:inline]log:rails,commandcommand,*args =Shellwords.split(command)in_rootdosilence_warningsdo::Rails::Command.invoke(command,args,**options)endendelseexecute_command:rails,command,optionsendend
rake(command, options = {})Link
Runs the specified Rake task.
rake "db:migrate"rake "db:migrate", env: "production"rake "db:migrate", abort_on_failure: truerake "stats", capture: truerake "gems:install", sudo: true
Options
:env
The Rails environment in which to run the task. Defaults to
ENV["RAILS_ENV"] || "development"
.:abort_on_failure
Whether to halt the generator if the task exits with a non-success exit status.
:capture
Whether to capture and return the output of the task.
:sudo
Whether to run the task using
sudo
.
rakefile(filename, data = nil)Link
Creates a Rake tasks file inlib/tasks/
. The code can be specified as an argument or as the return value of the block.
rakefile "bootstrap.rake", <<~RUBY task :bootstrap do puts "Boots! Boots! Boots!" endRUBYrakefile "bootstrap.rake" do project = ask("What is the UNIX name of your project?") <<~RUBY namespace :#{project} do task :bootstrap do puts "Boots! Boots! Boots!" end end RUBYend
readme(path)Link
Reads the given file at the source root and prints it in the console.
readme "README"
route(routing_code, namespace: nil)Link
Make an entry in Rails routing fileconfig/routes.rb
route "root 'welcome#index'"route "root 'admin#index'", namespace: :admin
# File railties/lib/rails/generators/actions.rb, line 409defroute(routing_code,namespace:nil)namespace =Array(namespace)namespace_pattern =route_namespace_pattern(namespace)routing_code =namespace.reverse.reduce(routing_code)do|code,name|"namespace :#{name} do\n#{rebase_indentation(code, 2)}end"endlog:route,routing_codein_rootdoifnamespace_match =match_file("config/routes.rb",namespace_pattern)base_indent,*,existing_block_indent =namespace_match.captures.compact.map(&:length)existing_line_pattern =/^[ ]{,#{existing_block_indent}}\S.+\n?/routing_code =rebase_indentation(routing_code,base_indent+2).gsub(existing_line_pattern,"")namespace_pattern =/#{Regexp.escape namespace_match.to_s}/endinject_into_file"config/routes.rb",routing_code,after:namespace_pattern,verbose:false,force:falseifbehavior==:revoke&&namespace.any?&&namespace_matchempty_block_pattern =/(#{namespace_pattern})((?:\s*end\n){1,#{namespace.size}})/gsub_file"config/routes.rb",empty_block_pattern,verbose:false,force:truedo|matched|beginning,ending =empty_block_pattern.match(matched).capturesending.sub!(/\A\s*end\n/,"")while!ending.empty?&&beginning.sub!(/^[ ]*namespace .+ do\n\s*\z/,"")beginning+endingendendendend
vendor(filename, data = nil)Link
Creates a file invendor/
. The contents can be specified as an argument or as the return value of the block.
vendor "foreign.rb", <<~RUBY # Foreign code is funRUBYvendor "foreign.rb" do "# Foreign code is fun"end
Instance Private methods
execute_command(executor, command, options = {})Link
Runs the supplied command using eitherrake
orrails
based on the executor parameter provided.
# File railties/lib/rails/generators/actions.rb, line 461defexecute_command(executor,command,options = {})# :doc:logexecutor,commandsudo =options[:sudo]&&!Gem.win_platform??"sudo ":""config = {env: {"RAILS_ENV"=> (options[:env]||ENV["RAILS_ENV"]||"development") },verbose:false,capture:options[:capture],abort_on_failure:options[:abort_on_failure], }in_root {run("#{sudo}#{Shellwords.escape Gem.ruby} bin/#{executor} #{command}",config) }end
indentation()Link
Returns a string corresponding to the current indentation level (i.e. 2 *@indentation
spaces). See alsowith_indentation
, which can be used to manage the indentation level.
log(*args)Link
Define log for backwards compatibility. If just one argument is sent, invokesay
, otherwise invokesay_status
. Differently fromsay
and similarly tosay_status
, this method respects thequiet?
option given.
optimize_indentation(value, amount = 0)Link
Returns optimized string with indentation
quote(value)Link
Always returns value in double quotes.
with_indentation(&block)Link
Increases the current indentation indentation level for the duration of the given block, and decreases it after the block ends. Callindentation
to get an indentation string.