Movatterモバイル変換


[0]ホーム

URL:


Skip to ContentSkip to Search
Ruby on Rails 8.1.1

Module Rails::Generators::Actions

v8.1.1
Methods
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/"dogem"rspec-rails"end

Source:show |on GitHub

# 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

Alias for:environment

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.rbclassApplication<Rails::Applicationconfig.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.configuredoconfig.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:

environmentdo%(config.asset_host = "cdn.provider.com")endenvironment(nil,env:"development")do%(config.asset_host = "localhost:3000")end
Also aliased as:application

Source:show |on GitHub

# 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 thegem declaration in theGemfile.

gem"my_gem",comment:"First line.\nSecond line."

Outputs:

# First line.# Second line.gem"my_gem"
:group

The gem group in theGemfile 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"

Source:show |on GitHub

# 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,:testdogem"rspec-rails"end

Source:show |on GitHub

# 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.

Source:show |on GitHub

# File railties/lib/rails/generators/actions.rb, line 332defgenerate(what,*args)log:generate,whatoptions =args.extract_options!options[:abort_on_failure] =!options[:inline]rails_command"generate #{what} #{args.join(" ")}",optionsend

git(commands = {})Link

Runs one or more git commands.

git:init# => runs `git init`gitadd:"this.file that.rb"# => runs `git add this.file that.rb`gitcommit:"-m 'First commit'"# => runs `git commit -m 'First commit'`gitadd:"good.rb",rm:"bad.cxx"# => runs `git add good.rb; git rm bad.cxx`

Source:show |on GitHub

# File railties/lib/rails/generators/actions.rb, line 237defgit(commands = {})ifcommands.is_a?(Symbol)run"git #{commands}"elsecommands.eachdo|cmd,options|run"git #{cmd} #{options}"endendend

github(repo, options = {}, &block)Link

Source:show |on GitHub

# 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

Source:show |on GitHub

# File railties/lib/rails/generators/actions.rb, line 319definitializer(filename,data =nil)log:initializer,filenamedata||=yieldifblock_given?create_file("config/initializers/#{filename}",optimize_indentation(data),verbose:false)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

Source:show |on GitHub

# File railties/lib/rails/generators/actions.rb, line 275deflib(filename,data =nil)log:lib,filenamedata||=yieldifblock_given?create_file("lib/#{filename}",optimize_indentation(data),verbose:false)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 toENV["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 usingsudo.

Source:show |on GitHub

# 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 toENV["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 usingsudo.

Source:show |on GitHub

# File railties/lib/rails/generators/actions.rb, line 364defrake(command,options = {})execute_command:rake,command,optionsend

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"doproject =ask("What is the UNIX name of your project?")<<~RUBY    namespace :#{project} do      task :bootstrap do        puts "Boots! Boots! Boots!"      end    end  RUBYend

Source:show |on GitHub

# File railties/lib/rails/generators/actions.rb, line 302defrakefile(filename,data =nil)log:rakefile,filenamedata||=yieldifblock_given?create_file("lib/tasks/#{filename}",optimize_indentation(data),verbose:false)end

readme(path)Link

Reads the given file at the source root and prints it in the console.

readme"README"

Source:show |on GitHub

# File railties/lib/rails/generators/actions.rb, line 442defreadme(path)logFile.read(find_in_source_paths(path))end

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

Source:show |on GitHub

# 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

Source:show |on GitHub

# File railties/lib/rails/generators/actions.rb, line 258defvendor(filename,data =nil)log:vendor,filenamedata||=yieldifblock_given?create_file("vendor/#{filename}",optimize_indentation(data),verbose:false)end

Instance Private methods

execute_command(executor, command, options = {})Link

Runs the supplied command using eitherrake orrails based on the executor parameter provided.

Source:show |on GitHub

# File railties/lib/rails/generators/actions.rb, line 460defexecute_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.

Source:show |on GitHub

# File railties/lib/rails/generators/actions.rb, line 495defindentation# :doc:"  "*@indentationend

log(*args)Link

Define log for backwards compatibility. If just one argument is sent, invokesay, otherwise invokesay_status.

Source:show |on GitHub

# File railties/lib/rails/generators/actions.rb, line 449deflog(*args)# :doc:ifargs.size==1sayargs.first.to_selseargs<< (behavior==:invoke?:green::red)say_status(*args)endend

optimize_indentation(value, amount = 0)Link

Returns optimized string with indentation

Also aliased as:rebase_indentation

Source:show |on GitHub

# File railties/lib/rails/generators/actions.rb, line 486defoptimize_indentation(value,amount =0)# :doc:return"#{value}\n"unlessvalue.is_a?(String)"#{value.strip_heredoc.indent(amount).chomp}\n"end

quote(value)Link

Always returns value in double quotes.

Source:show |on GitHub

# File railties/lib/rails/generators/actions.rb, line 474defquote(value)# :doc:ifvalue.respond_to?:each_pairreturnvalue.mapdo|k,v|"#{k}: #{quote(v)}"end.join(", ")endreturnvalue.inspectunlessvalue.is_a?String"\"#{value.tr("'", '"')}\""end

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.

Source:show |on GitHub

# File railties/lib/rails/generators/actions.rb, line 502defwith_indentation(&block)# :doc:@indentation+=1instance_eval(&block)ensure@indentation-=1end

[8]ページ先頭

©2009-2025 Movatter.jp