28 May 2015

前言

Rails开发中必备的vim插件,Rails.vim。

vim-rails使用手册

作者: Tim Pope http://tpo.pe/, 手册目录:

  • rails-introduction 介绍和特性总结Introduction and Feature Summary
  • rails-commands 通用命令General Commands
  • rails-navigation 导航Navigation
  • rails-gf 在光标下的文件File Under Cursor - gf
  • rails-alternate-related 可选的和相关的文件Alternate and Related Files
  • rails-type-navigation 文件类型命令File Type Commands
  • rails-rake Rake
  • rails-scripts 脚本包装Script Wrappers
  • rails-refactoring 重构帮助Refactoring Helpers
  • rails-partials Partial Extraction
  • rails-migrations Migration Inversion
  • rails-integration 集成Integration
  • rails-vim-integration Integration with the Vim Universe
  • rails-rails-integration Integration with the Rails Universe
  • rails-abbreviations 缩写Abbreviations
  • rails-syntax 语法高亮Syntax Highlighting
  • rails-options 管理VIM操作Managed Vim Options
  • rails-projections Projections
  • rails-configuration 配置Configuration
  • rails-global-settings 全局设置Global Settings

该插件仅仅在VIM的compatible没有设置时可用,即在.vimrc中加入set nocompatible.

简介

无论何时,当你在编辑Rails应用中的文件时,该插件将自动激活,其设置了很多选项并定义了一些buffer特定的命令。

如果你急于开始,并想最小化阅读量,快速浏览本文的头部和命令。如果想查找特定的信息,请移步导航节。

通用命令

所有的命令都是针对局部缓冲区。这意味着,必须要编辑一个Rails应用中的文件。

  • :Rails new {directory} - 唯一的全局命令,调用”rails new {directory}”并将生成的文件加载到quickfix列表中。
  • :Rails! - 显示安装的rails.vim的版本好。如果rails.vim在当前缓冲区中处于激活状态,也会显示探测出的Rails文件类型。
  • :Redit {file} 编辑文件,:R或:A废弃的别名
  • :Rfind [{file}] 查找文件,:find废弃的别名
  • :Rlog [{logfile}] 分割窗口并打开{logfile}($RAILS_ENV或默认开发的)。其中被用做高亮的控制字符被移除了。如果存在:Tail命令(tailminusf提供)。文件不会根据修改而自动加载,使用checktime告诉VIM检查修改。G被映射为跳到文件末,q被映射为关闭窗口。如果log加载的时候太长,可以使用:Rake log:clear。
  • :Rpreview [path] 在浏览器中打开给定路径的当前应用。主机和端口通过应用当前服务器pid的netstat/lsof trickery。如果没有服务器在运行,就查询Pow,如果所有的都失败了,使用默认的localhost:3000。如果忽略了路径,就启用默认设置(即当前controller/template,但不考虑路由)。可以通过方法调用前或文件头部的注释覆盖默认设置,注释如下:

    # GET /users # PUT /users/1

如果没有使用正确的浏览器,定义一个OpenURL的命令::command -bar -nargs=1 OpenURL :!open <args>

  • :Rpreview! [{path}] 和:Rpreview类似,但使用VIM中的netrw代替。
  • :Rrefresh 刷新包含了某些缓冲设置。需要注意的是:该命令清除了用作语法高亮的类列表的缓存。
  • :Rrefresh! 同上,并重新加载rails.vim
  • :Cd [{directory}] 改变路径,例如:Cd /path/to/railsapp/{directory}.
  • :Lcd [{directory}] :lcd to /path/to/railsapp/{directory}. 改变路径
  • :Ctags 在当前应用程序的根目录调用ctags -R。Ctags必须事先安装。传递给ctags的附加参数可通过 g:rails_ctags_arguments 来设定。

导航

导航才是该插件的强大之处。有效的使用如下的特性将会简化在Rails文件结构中的导航。

例如 :find application_controller.rb ,其中命令支持补全。

标准的Rails加载路径,被追加到了path变量中。

gf命令,跳转到位于光标下的文件,其本质就是在快速查找相应的文件。CTRL-W_f在新窗口中打开,CTRL-W_gf在新标签页中打开。

交替和相关文件

:R:A命令用来跳转到相关和可选的文件中。

:A相关的命令: :A, :AE, :AS, :AV, :AT, :AD

该命令是模仿的Michael Sharpe 的 a.vim。简而言之,他们用来编辑 相关文件。:A 和 :AE 在相同窗口中 打开文件。 :AS 在新的水平分隔窗口中打开, :AV 在垂直分隔窗口中打开, :AT 在新标签页中打开。

:R相关的命令: :R, :RE, :RS, :RV, :RT, :RD。其使用与:A类似。 alternate文件通常是test文件, 也有特例。related文件是变化的,通常依赖文件当前的位置。例如,例如在编辑控制器时,相关文件是 当前方法对应的模板。

学习命令的最简单的方式是实践。 下面是相关文件和交替文件的例子:

Current file Alternate file Related file
model unit test schema definition
controller (in method) functional test template (view)
template (view) functional test controller (jump to method)
migration previous migration next migration
database.yml database.example.yml environments/*.rb

可以与 rails-projections 配套使用。

文件类型的导航命令

对于其他情况, 会提供一组特定命令,并带有合理的tab补全。 命令默认位于当前模式或控制器中,例如,app/helpers/posts_helper.rb中默认的控制器就是 “posts” ,在test/fixtures/comments.yml中,当前模型就是 “comment”。 在模型相关的控制器中,控制器是复数化的模型名,在控制器相关的模型中,当前模式是单数化的控制器名。

Each of the following commands has variants for splitting, vertical splitting, opening in a new tab, and reading the file into the current buffer. For :Emodel, those variants would be :Smodel, :Vmodel, :Tmodel, and :Dmodel. They also allow for jumping to methods or line numbers using the same syntax as :R, and file creation (with a bit of boilerplate) can be forced by adding a ! after the filename (not after the command itself!).

每种命令都有,水平分隔,垂直分隔,新tab页中打开等。例如,:Emodel,其变种有:Smodel, :Vmodel, :Tmodel, 和 :Dmodel。 这些方法可在 :R 命令和文件创建命令中使用。

:R命令的通用版本: :Rmodel, :RSmodel, :RVmodel, :RTmodel, 和 :RDmodel

  • :Econtroller [{name}] Edit the specified or current controller.
  • :Eenvironment [{name}] Edit the config/environments file specified. With no argument, defaults to editing config/application.rb or config/environment.rb.
  • :Efixtures [{name}] Edit the fixtures for the given or current model. If an argument is given, it must be pluralized, like the final filename (this may change in the future). If omitted, the current model is pluralized. An optional extension can be given, to distinguish between YAML and CSV fixtures.
  • :Efunctionaltest [{name}] Edit the functional test or controller spec for the specified or current controller.
  • :Ehelper [{name}] Edit the helper for the specified name or current controller.
  • :Einitializer [{name}] Edit the config/initializers file specified. With no argument, defaults to editing config/routes.rb.
  • :Eintegrationtest [{name}] Edit the integration test, integration spec, or cucumber feature specified. With no argument, defaults to editing test/test_helper.rb.
  • :Ejavascript [{name}] Edit the JavaScript for the specified name or current controller. Also supports CoffeeScript in app/scripts/.
  • :Elayout [{name}] Edit the specified layout. Defaults to the layout for the current controller, or the application layout if that cannot be found. A new layout will be created if an extension is given.
  • :Elib [{name}] Edit the library from the lib directory for the specified name. With no argument, defaults to editing the application Gemfile (a task formally handled by the defunct :Rplugin).
  • :Elocale [{name}] Edit the config/locale file specified, optionally adding a yml or rb extension if none is given. With no argument, checks config/environment.rb for the default locale.
  • :Emailer [{name}] Edit the mailer specified. This looks in both app/mailers for Rails 3 and app/models for older versions of Rails but only tab completes the former.
  • :Emigration [{pattern}] If {pattern} is a number, find the migration for that particular set of digits, zero-padding if necessary. Otherwise, find the newest migration containing the given pattern. Omitting the pattern selects the latest migration. Give a numeric argument of 0 to edit db/seeds.rb.
  • :Emodel [{name}] Edit the specified or current model.
  • :Espec [{name}] Edit the given spec. With no argument, defaults to editing spec/spec_helper.rb (If you want to jump to the spec for the given file, use :A instead). This command is only defined if there is a spec folder in the root of the application.
  • :Eschema [{table}] Edit the schema and optionally jump to the specified table.
  • :Estylesheet [{name}] Edit the stylesheet for the specified name or current controller. Also supports Sass and SCSS.
  • :Etask [{name}] Edit the .rake file from lib/tasks for the specified name. If no argument is given, the application Rakefile is edited.
  • :Eunittest [{name}] Edit the unit test or model spec for the specified name or current model.
  • :Eview [[{controller}/]{view}] Edit the specified view. The controller will default sensibly, and the view name can be omitted when editing a method of a controller. If a view name is given with an extension, a new file will be created. This is a quick way to create a new view.

Finally, one Vim feature that proves helpful in conjunction with all of the above is CTRL-^. This keystroke edits the previous file, and is helpful to back out of any of the above commands.

最后,vim提供的 CTRL-^ 可在任何时候,回退到上一个编辑的文件,这非常的有用。

RAKE

通过:Rake命令集成Rake命令,没发现有什么特别的用处,不如直接执行shell命令好用。

  • :[range]Rake {targets} Calls :make! {targets} (with ‘makeprg’ being rake) and opens the quickfix window if there were any errors. An argument of “-“ reruns the last task. If {targets} are omitted, :Rake defaults to something sensible as described below. Giving a line number argument may affect that default.
  • :[range]Rake! {targets} Called with a bang, :Rake will forgo opening the quickfix window.

Finally, you can override the default task with a comment like “# rake …” before the method pointed to by [range] or at the top of the file.

可以通过在文件顶部,写入诸如”# rake …“这样的注释,从而覆盖默认的task。

脚本包装

The following commands are wrappers around the scripts in the script directory of the Rails application. Most have extra features beyond calling the script. A limited amount of completion with is supported.

包装Rails,并提供的命令,并提供额外的特性,提供了有限的补全。

  • :Rails {command} [options] - 就是rails命令
  • :Rscript {command} [options] - :Rails 弃用的别名
  • :[range]Rrunner [file] - 通过 rails runnerload 运行给定的文件和代码
  • :Rrunner {code} 运行的结果将返回到 quickfix 列表,并使用ruby的错误解析器(:compiler). If the file looks like a test, spec, or cucumber feature, the “rubyunit”, “rspec”, or “cucumber” :compiler will be used instead. If provided, [range] is passed to the test runner to restrict execution to a particular line. With no argument, defaults to running the test for the current file.
  • :[range]Rp {code} Use rails runner to execute “p begin {code} end” and echo the result.
  • :[range]Rpp {code} Like :Rp, but with pp (pretty print).
  • :Rgenerate {options} Calls rails generate {options} and loads the generated files into the quickfix list. Use ! to surpress jumping to the first file.
  • :Rdestroy {options} Calls rails destroy {options} and loads the destroyed files into the quickfix list.
  • :Rserver {options} Launches rails server {options} in the background. On win32, this means !start. Otherwise, the –daemon option is passed in.
  • :Rserver! {options} Kill the pid found in tmp/pids/server.pid and then invoke :Rserver.

重构辅助

有一些用来帮助重构代码的特性。

部分提取

:Rextract命令可以用来提取部分视图,部分辅助方法,,以及模型或控制器的 concern。

:[range]Rextract [{controller}/]{name} 创建一个命名的部分视图,默认是在当前行。 仅在视图中可用。

:[range]Rextract {helper} 创建一名为{name}的的helper,仅在 helper 中可用。 :[range]Rextract {concern} 创建一个命名的 concern ,仅在 模型 和 控制器 可用

例如 在app/views/blog/show.html.erb文件中,存在如下的内容:

 1  <div>
 2    <h2><%= @post.title %></h2>
 3    <p><%= @post.body %></p>
 4  </div>

然后,输入如下的命令:

:2,3Rextract post

就会产生如下的结果:

 1  <div>
 2    <%= render 'post' %>
 3  </div>

以及app/views/blog/_post.html.erb文件:

 1  <h2><%= @post.title %></h2>
 2  <p><%= @post.body %></p>

最简单的使用提取方法是 使用提取模式: :'<,'>Rextract blog/post

迁移反演

:Rinvert 在应用中,重写self.up方法和self.down方法。虽然很复杂,但是可通过简单调用create_tableadd_column方法等类似的方法来解决。新版rails提供了可逆迁移的更好的方法。所以这个命令将被遗弃不用.

集成

Having one foot in Rails and one in Vim, rails.vim has two worlds with which to interact.

rails.vim处于Rails和vim两个世界之间,并集成两者。

A handful of Vim plugins are enhanced by rails.vim. All plugins mentioned can be found at http://www.vim.org/.

有一些可以提供Rails.vim的作用的vim插件,所有的插件都可在http://www.vim.org/中找到。

:Rdbext [{environment}] 该命令仅在dbext插件安装时有效。 其从config/database.yml中加载配置环境(默认是$RAILS_ENV 或 development),并用其来配置 dbext。配置缓存在每个应用的basis中。配合 8.0 以上的dbext,该命令将在需要时,自动调用。在配置 dbext 时,可在vim 中直接执行sql语句。

:Select * from posts order by id desc
:Update comments set author_id = 1

The surround plugin available from vim.org enables adding and removing “surroundings” like parentheses, quotes, and HTML tags. Even by itself, it is quite useful for Rails development, particularly eRuby editing. When coupled with this plugin, a few additional replacement surroundings are available in eRuby files. See the surround documentation for details on how to use them. The table below uses ^ to represent the position of the surrounded text.

surround插件在编辑erb时,非常的有用。一些例子:

= <%= ^ %>
- <% ^ -%>
# <%# ^ %>
<C-E> <% ^ -%>\n<% end -%>

尤其是最后一个包装命令,非常的有用,可将其映射到vimrc文件中。 可以是使用Alt+o打开一个新行。

Among the many features of abolish on vim.org is the ability to change the inflection of the word under the cursor. For example, one can hit crs to change from MixedCase to snake_case. This plugin adds two additional inflections: crl for alternating between the singular and plural, and crt for altering between tableize and classify. The latter is useful in changing constructs like BlogPost.all to current_user.blog_posts.all and vice versa.

The presence of a spec directory causes several additional behaviors to activate. :A knows about specs and will jump to them (but Test::Unit files still get priority). The associated controller or model of a spec is detected, so all navigation commands should work as expected inside a spec file. :Rake in a spec runs just that spec, and in a model, controller, or helper, runs the associated spec.

:Eunittest and :Efunctionaltest lead double lives, handling model/helper and controller/mailer specs respectively. For view specs, you can use :Espec, or define your own navigation commands:

Rnavcommand specview spec/views -glob=*/ -suffix=_spec.rb <

缩写

Abbreviations are “snippets lite”. They may later be extracted into a separate plugin, or removed entirely.

:Rabbrev List all Rails abbreviations.

:Rabbrev {abbr} {expn} [{extra}] Define a new Rails abbreviation. {extra} is permitted if and only if {expn} ends with “(“.

:Rabbrev! {abbr} Remove an abbreviation.

Rails abbreviations differ from regular abbreviations in that they only expand after a <C-]> (see i_CTRL-]) or a (if does not work, it is likely mapped by another plugin). If the abbreviation ends in certain punctuation marks, additional expansions are possible. A few examples will hopefully clear this up (all of the following are enabled by default in appropriate file types).

Command Sequence typed Resulting text ~ Rabbrev rp( render :partial\ => rp( render(:partial => Rabbrev rp( render :partial\ => rp render :partial => Rabbrev vs( validates_size_of vs( validates_size_of( Rabbrev pa[ params pa[:id] params[:id] Rabbrev pa[ params pa<C-]> params Rabbrev pa[ params pa.inspect params.inspect Rabbrev AR:: ActionRecord AR::Base ActiveRecord::Base

In short, ( expands on (, :: expands on . and :, and [ expands on . and [. These trailing punctuation marks are NOT part of the final abbreviation, and you cannot have two mappings that differ only by punctuation.

You must escape spaces in your expansion, either as “\ “ or as “". For an abbreviation ending with "(", you may define where to insert the parenthesis by splitting the expansion into two parts (divided by an unescaped space).

You can also define abbreviations as a hash in g:rails_abbreviations or by using rails-projection-abbreviations:

let g:rails_abbreviations = { \ “AE::”: “ActiveResource”, \ “p[”: “params”, \ “rj(“: [“render”, “json: “]} < Many abbreviations are provided by default: use :Rabbrev to list them. They vary depending on the type of file (models have different abbreviations than controllers).

语法高亮

Syntax highlighting is by and large a transparent process. For the full effect, however, you need a colorscheme which accentuates rails.vim extensions. One such colorscheme is vividchalk, available from vim.org.

The following is a summary of the changes made by rails.vim to the standard syntax highlighting.

Rails specific keywords are highlighted in a filetype specific manner. For example, in a model, has_many is highlighted, whereas in a controller, before_filter is highlighted. A wide variety of syntax groups are used but they all link by default to railsMethod.

Models, helpers, and controllers are given special highlighting. Depending on the version of Vim installed, you may need a rails.vim aware colorscheme in order to see this. Said colorscheme needs to provide highlighting for the railsUserClass syntax group.

The class names are determined by camelizing filenames from certain directories of your application. If app/models/line_item.rb exists, the class “LineItem” will be highlighted.

The list of classes is refreshed automatically after certain commands like :Rgenerate. Use :Rrefresh to trigger the process manually.

If you define custom assertions in test_helper.rb, these will be highlighted in your tests. These are found by scanning test_helper.rb for lines of the form “ def assert_…” and extracting the method name. The railsUserMethod syntax group is used. The list of assertions can be refreshed with :Rrefresh.

A string literal using %Q<> or %<> delimiters will have its contents highlighted as HTML. This is sometimes useful when writing helpers. > link = %«a href=”http://www.vim.org”>Vim</a>>.html_safe < YAML syntax highlighting has been extended to highlight eRuby, which can be used in most Rails YAML files (including database.yml and fixtures).

管理VIM选项

The following options are set local to buffers where the plugin is active.

Indent settings are no longer adjusted by default. Install sleuth.vim, or try this in your vimrc instead: > autocmd FileType ruby set sw=2 sts=2 et < All the relevant directories from your application are added to your ‘path’. This makes it easy to access a buried file: > :find blog_controller < The ‘includeexpr’ option is set to enable the magic described in rails-gf.

The ‘filetype’ is sometimes adjusted for Rails files. Most notably, *.rxml and *.rjs are treated as Ruby files, and files that have been falsely identified as Mason sources are changed back to eRuby files (but only when they are part of a Rails application).

PROJECTIONS The bulk of rails.vim features support core Rails conventions and a just a handful of popular additions (such as RSpec). Projections let you teach rails.vim about app specific and gem specific behavior.

There are four primary ways to define projections:

  1. Globally, in g:rails_projections.
  2. Per app, in config/projections.json.
  3. Per bundled gem, in g:rails_gem_projections (requires bundler.vim).
  4. Inside a bundled gem, in lib/rails/projections.json (requires bundler.vim).

Vim syntax looks a lot like JSON, but with funky line-continuation:

let g:rails_projections = { \ “app/uploaders/_uploader.rb”: { \ “command”: “uploader”, \ “template”: \ [“class %SUploader < CarrierWave::Uploader::Base”, “end”], \ “test”: [ \ “test/unit/%s_uploader_test.rb”, \ “spec/models/%s_uploader_spec.rb” \ ], \ “keywords”: “process version” \ }, \ “features/support/.rb”: {“command”: “support”}, \ “features/support/env.rb”: {“command”: “support”}}

Keys can be either literal file names or globs containing a single asterisk. In the latter case, you can use placeholders in the values to plug in some variant of the variable portion:

%s: original %p: pluralized %i: singularized %S: camelized %h: humanized

The full list of available options is as follows:

“alternate” ~ Determines the destination of the rails-:A command. If this is a list, the first readable file will be used. “related” ~ Determines the destination of the rails-:R and :.A commands. In addition to the standard placeholders, %d can be used for the current ‘define’ match (typically a method). “test” ~ Determines the default test file to run with rails-:Rrunner and rails-:Rake. Also serves as a default for “alternate”. “task” ~ Determines the default rake task to run. Provide %l or %d to substitute the current line or ‘define’ match (typically a method), or just a bare % (like :_%) to substitute the current file name. If a list with two tasks is provided, the first will be used when a line number is given, and the second when it’s omitted. “compiler” ~ Determines the :compiler plugin to use with rails-:Rrunner. “keywords” ~ Provides a whitespace delimited list of keywords to syntax highlight. “abbreviations” ~ Provides a dictionary of abbreviations to define. See rails-abbreviations. You might consider setting this in a “*” projection. “command” ~ Names a navigation command to be created. Use the same name on multiple projections to combine them into a single command. Glob keys are used when the command is given an argument, and literal file keys are used when no argument is given. See the “features/support” entries above for an example :Esupport that defaults to env. “affinity” ~ Provide this if the root of your file name corresponds to either a model or controller. The root of a helper generally corresponds to a controller, for example, so a “helper” projection would have an “affinity” of “controller”. You can also provide “collection” if it corresponds to a plural model (e.g., fixtures), or “resource” if it corresponds to a singular controller. Providing this lets you use other affiliated commands without an argument, and determines the default if a command has no literal file name. “template” ~ If you provide a ! after the argument to the navigation command (that is, :Euploader foo!, NOT :Euploader! foo), and a new file is created, this will be used as an array of lines to populate the body.

配置

In addition to projections (described above) and the crude hammer of global settings (described below), rails.vim provides a few different mechanisms for configuration.

If you would like to set your own custom Vim settings whenever a Rails file is loaded, you can use an autocommand like the following in your vimrc: >

autocmd User Rails silent! Lcd autocmd User Rails map :Rake

There used to be autocommands that fire based on the “type” or file name of the buffer, but they have been removed. If you still need to execute code for certain file types only, use the bare User Rails event above and check rails#buffer().relative() for the path relative to the Rails root.

If you have several commands to run on initialization for all file types, they can be placed in a “macros/rails.vim” file in the ‘runtimepath’ (for example, “~/.vim/macros/rails.vim”). This file is sourced by rails.vim each time a Rails file is loaded.

This file used to be sourced automatically from the root of the application, but has been superseded by rails-projections.

:Rnavcommand This command has been superseded by rails-projections.

:Rset This command has been superseded by rails-projections.

全局设置

When all else fails, set a global.

Dictionary of additional abbreviations. See rails-abbreviations.

This variable was formerly used to globally disable abbreviations. Use g:rails_no_abbreviations if you want to do that.

Additional arguments to pass to ctags from :Ctags. Defaults to ignoring JavaScript files, since ctags has a tendency to choke on those.

let g:rails_ctags_arguments = [’–languages=-javascript’] < Defines the set of globally available projections. See rails-projections. Where possible, it is generally advisable to use g:rails_gem_projections or config/projections.json instead.

This is a dictionary where the keys are gem names and the values are projection dictionaries. Projections are only used if the given gem is bundled (requires bundler.vim).

let g:rails_gem_projections = { \ “active_model_serializers”: { \ “app/serializers/_serializer.rb”: { \ “command”: “serializer”, \ “affinity”: “model”}}, \ “fabrication”: { \ “spec/fabricators/_fabricator.rb”: { \ “command”: “fabricator”, \ “affinity”: “model”, \ “alternate”: “app/models/%s.rb”, \ “related”: “db/schema.rb#%p”, \ “test”: “spec/models/%s_spec.rb”, \ “template”: “Fabricator :%s do\nend”}}} < See rails-projections. Generally, you should prefer these gem projections over global projections to avoid getting a bunch of useless commands in every single project.

Gem maintainers may also provide custom projections by placing them in lib/rails/projections.json.

后记

rails.vim 还有很多值得学习的东西。




傲娇的使用Disqus