dotfiles/vim/doc/rails.txt

1130 lines
44 KiB
Plaintext

*rails.txt* Plugin for working with Ruby on Rails applications
Author: Tim Pope <vimNOSPAM@tpope.org> |rails-plugin-author|
|rails-introduction| Introduction and Feature Summary
|rails-installation| Installation and Usage
|rails-configure-vim| Configuring Vim
|rails-install-plugin| Installing and Using the Plugin
|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-custom-navigation| Custom Navigation 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| Managed Vim Options
|rails-configuration| Configuration
|rails-global-settings| Global Settings
|rails-about| About rails.vim
|rails-license| License
This plugin is only available if 'compatible' is not set.
{Vi does not have any of this}
INTRODUCTION *rails-introduction* *rails*
TextMate may be the latest craze for developing Ruby on Rails applications,
but Vim is forever. This plugin offers the following features for Ruby on
Rails application development.
1. Automatically detects buffers containing files from Rails applications,
and applies settings to those buffers (and only those buffers). You can
use an autocommand to apply your own custom settings as well.
|rails-configuration|
2. Unintrusive. Only files in a Rails application should be affected; regular
Ruby scripts are left untouched. Even when enabled, the plugin should keep
out of your way if you're not using its features. (If you find a situation
where this is not a case, contact the |rails-plugin-author|.)
3. Easy navigation of the Rails directory structure. |gf| considers context
and knows about partials, fixtures, and much more. There are two commands,
:A (alternate) and :R (related) for easy jumping between files, including
favorites like model to migration, template to helper, and controller to
functional test. For more advanced usage, :Rmodel, :Rview, :Rcontroller,
and several other commands are provided. |rails-navigation|
4. Enhanced syntax highlighting. From has_and_belongs_to_many to
distance_of_time_in_words, it's here. For easy completion of these long
method names, 'completefunc' is set to enable syntax based completion on
|i_CTRL-X_CTRL-U|. |rails-syntax|
5. Interface to rake. Use :Rake to run the current test, spec, or feature.
Use :.Rake to do a focused run of just the method, example, or scenario on
the current line. :Rake can also run arbitrary migrations, load individual
fixtures, and more. |rails-rake|
6. Interface to script/*. Generally, use ":Rscript about" to call
"script/about" or "script/rails about". Most commands have wrappers with
additional features: ":Rgenerate controller Blog" generates a blog
controller and edits app/controllers/blog_controller.rb. |rails-scripts|
7. Partial extraction and migration inversion. |:Rextract| {file} replaces
the desired range (ideally selected in visual line mode) with "render
:partial => '{file}'", which is automatically created with your content.
The @{file} instance variable is replaced with the {file} local variable.
|:Rinvert| takes a self.up migration and writes a self.down.
|rails-refactoring|
8. Integration with other plugins. |:Rtree| spawns NERDTree.vim. If
dbext.vim is installed, it will be transparently configured to reflect
database.yml. Cream users get some additional mappings, and all GUI users
get a menu. |rails-integration|
INSTALLATION AND USAGE *rails-installation*
If you are familiar Vim and have the latest version installed, you may skip
directly to |rails-install-plugin| below.
Configuring Vim ~
*rails-configure-vim*
If you are new to Vim, you need to create a vimrc. For Windows, this file
goes in ~\_vimrc (try :e ~\_vimrc if you don't know where this is). On other
platforms, use ~/.vimrc. A very minimal example file is shown below.
>
set nocompatible
syntax on
filetype plugin indent on
>
Installing and Using the Plugin ~
*rails-install-plugin*
If you have the zip file, extract it to vimfiles (Windows) or ~/.vim
(everything else). You should have the following files: >
autoload/rails.vim
plugin/rails.vim
doc/rails.txt
See |add-local-help| for instructions on enabling the documentation. In a
nutshell: >
:helptags ~/.vim/doc
Whenever you edit a file in a Rails application, this plugin will be
automatically activated. This sets various options and defines a few
buffer-specific commands.
If you are in a hurry to get started, with a minimal amount of reading, you
are encouraged to at least skim through the headings and command names in this
file, to get a better idea of what is offered. If you only read one thing,
make sure it is the navigation section: |rails-navigation|.
GENERAL COMMANDS *rails-commands*
All commands are buffer local, unless otherwise stated. This means you must
actually edit a file from a Rails application.
*rails-:Rails*
:Rails {directory} The only global command. Creates a new Rails
application in {directory}, and loads the README.
:Rails! Show the version of rails.vim installed. If rails.vim
is active for the current buffer, also show the type
of Rails file detected.
*rails-:Rcd*
:Rcd [{directory}] |:cd| to /path/to/railsapp/{directory}.
*rails-:Rlcd*
:Rlcd [{directory}] |:lcd| to /path/to/railsapp/{directory}.
*rails-:Rdoc*
:Rdoc Browse to the Rails API, either in doc/api in the
current Rails application, gem_server if it is
running, or http://api.rubyonrails.org/ . Requires
:OpenURL to be defined (see |rails-:OpenURL|).
*rails-:Rdoc!*
:Rdoc! Make the appropriate |:helptags| call and invoke
|:help| rails.
*rails-:Redit*
:Redit {file} Edit {file}, relative to the application root. Append
:line or #method to jump within the file, as in
:Redit app/controllers/users_controller.rb:12 or
:Redit app/models/user.rb#activate .
*rails-:Rlog*
:Rlog [{logfile}] Split window and open {logfile} ($RAILS_ENV or
development by default). The control characters used
for highlighting are removed. If you have a :Tail
command (provided by |tailminusf|.vim), that is used;
otherwise, the file does NOT reload upon change.
Use |:checktime| to tell Vim to check for changes.
|G| has been mapped to do just that prior to jumping
to the end of the file, and q is mapped to close the
window. If the delay in loading is too long, you
might like :Rake log:clear.
*rails-:Rpreview*
:Rpreview [{path}] Creates a URL from http://localhost:3000/ and the
{path} given. The not too useful default is to then
edit this URL using Vim itself, allowing |netrw| to
download it. More useful is to define a :OpenURL
command, which will be used instead (see
|rails-:OpenURL|). If {path} is omitted, a sensible
default is used (considers the current
controller/template, but does not take routing into
account). The default is overridden by comments like
the following that are either before the current
method call or at the top of the file: >
# GET /users
# PUT /users/1
<
*rails-:Rpreview!*
:Rpreview! [{path}] As with :Rpreview, except :OpenURL is never used.
*rails-:Rtags*
:Rtags Calls ctags -R on the current application root and
writes the result to tmp/tags. Exuberant ctags must
be installed. Additional arguments can be passed to
ctags with |g:rails_ctags_arguments|.
*rails-:Rrefresh*
:Rrefresh Refreshes certain cached settings. Most noticeably,
this clears the cached list of classes that are syntax
highlighted as railsUserClass.
*rails-:Rrefresh!*
:Rrefresh! As above, and also reloads rails.vim.
*rails-:OpenURL*
:OpenURL {url} This is not a command provided by the plugin, but
rather provided by user and utilized by other plugin
features. This command should be defined to open the
provided {url} in a web browser. An example command
on a Mac might be: >
:command -bar -nargs=1 OpenURL :!open <args>
< The following appears to work on Windows: >
:command -bar -nargs=1 OpenURL :!start cmd /cstart /b <args>
< On Debian compatible distributions, the following is
the preferred method: >
:command -bar -nargs=1 OpenURL :!sensible-browser <args>
< If exists("$SECURITYSESSIONID"), has("gui_win32"), or
executable("sensible-browser") is true, the
corresponding command above will be automatically
defined. Otherwise, you must provide your own (which
is recommended, regardless).
NAVIGATION *rails-navigation*
Navigation is where the real power of this plugin lies. Efficient use of the
following features will greatly ease navigating the Rails file structure.
The 'path' has been modified to include all the best places to be.
>
:find blog_controller
:find book_test
<
*rails-:Rfind*
:Rfind [{file}] Find {file}. Very similar to :find, but things like
BlogController are properly handled, and tab complete
works.
File Under Cursor - gf ~
*rails-gf*
The |gf| command, which normally edits the current file under the cursor, has
been remapped to take context into account. |CTRL-W_f|(open in new window) and
|CTRL-W_gf| (open in new tab) are also remapped.
Example uses of |gf|, and where they might lead.
(* indicates cursor position)
>
Pos*t.first
< app/models/post.rb ~
>
has_many :c*omments
< app/models/comment.rb ~
>
link_to 'Home', :controller => 'bl*og'
< app/controllers/blog_controller.rb ~
>
<%= render 'sh*ared/sidebar' %>
< app/views/shared/_sidebar.html.erb ~
>
<%= stylesheet_link_tag 'scaf*fold' %>
< public/stylesheets/scaffold.css ~
>
class BlogController < Applica*tionController
< app/controllers/application_controller.rb ~
>
class ApplicationController < ActionCont*roller::Base
< .../action_controller/base.rb ~
>
fixtures :pos*ts
< test/fixtures/posts.yml ~
>
layout :pri*nt
< app/views/layouts/print.html.erb ~
>
<%= link_to "New", new_comme*nt_path %>
< app/controllers/comments_controller.rb (jumps to def new) ~
In the last example, the controller and action for the named route are
determined by evaluating routes.rb as Ruby and doing some introspection. This
means code from the application is executed. Keep this in mind when
navigating unfamiliar applications.
Alternate and Related Files ~
*rails-alternate-related*
Two commands, :A and :R, are used quickly jump to an "alternate" and a
"related" file, defined below.
*rails-:A* *rails-:AE* *rails-:AS* *rails-:AV* *rails-:AT* *rails-:AD*
:A These commands were picked to mimic Michael Sharpe's
:AE a.vim. Briefly, they edit the "alternate" file, in
:AS either the same window (:A and :AE), a new split
:AV window (:AS), a new vertically split window (:AV), a
:AT new tab (:AT), or read it into the current buffer
:AD (:AD). A mapping for :A is [f .
*rails-:R* *rails-:RE* *rails-:RS* *rails-:RV* *rails-:RT* *rails-:RD*
:R These are similar |rails-:A| and friends above, only
:RE they jump to the "related" file rather than the
:RS "alternate." A mapping for :R is ]f .
:RV
:RT
:RD
*rails-alternate* *rails-related*
The alternate file is most frequently the test file, though there are
exceptions. The related file varies, and is sometimes dependent on current
location in the file. For example, when editing a controller, the related
file is template for the method currently being edited.
The easiest way to learn these commands is to experiment. A few examples of
alternate and related files for a Test::Unit application follow:
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
config/database.yml config/routes.rb config/environments/*.rb
Suggestions for further contexts to consider for the alternate file, related
file, and file under the cursor are welcome. They are subtly tweaked from
release to release.
File Type Navigation Commands ~
*rails-type-navigation*
For the less common cases, a more deliberate set of commands are provided.
Each of the upcoming commands takes an optional argument (with tab completion)
but defaults to a reasonable guess. Commands that default to the current
model or controller generally behave like you'd expect in other file types.
For example, in app/helpers/posts_helper.rb, the current controller is
"posts", and in test/fixtures/comments.yml, the current model is "comment".
In model related files, the current controller is the pluralized model name,
and in controller related files, the current model is the singularized
controller name.
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
:Rmodel, those variants would be :RSmodel, :RVmodel, :RTmodel, and :RDmodel.
There is also :REmodel which is a synonym for :Rmodel (future versions might
allow customization of the behavior of :Rmodel). They also allow for jumping
to methods or line numbers using the same syntax as |:Redit|, and file
creation can be forced by adding a ! after the filename (not after the command
itself!).
:Rcontroller |rails-:Rcontroller|
:Renvironment |rails-:Renvironment|
:Rfixtures |rails-:Rfixtures|
:Rfunctionaltest |rails-:Rfunctionaltest|
:Rhelper |rails-:Rhelper|
:Rinitializer |rails-:Rinitializer|
:Rintegrationtest |rails-:Rintegrationtest|
:Rjavascript |rails-:Rjavascript|
:Rlayout |rails-:Rlayout|
:Rlib |rails-:Rlib|
:Rlocale |rails-:Rlocale|
:Rmailer |rails-:Rmailer|
:Rmetal |rails-:Rmetal|
:Rmigration |rails-:Rmigration|
:Rmodel |rails-:Rmodel|
:Robserver |rails-:Robserver|
:Rplugin |rails-:Rplugin|
:Rspec |rails-:Rspec|
:Rstylesheet |rails-:Rstylesheet|
:Rtask |rails-:Rtask|
:Runittest |rails-:Runittest|
:Rview |rails-:Rview|
*rails-:Rcontroller*
:Rcontroller [{name}] Edit the specified or current controller.
*rails-:Renvironment*
:Renvironment [{name}] Edit the config/environments file specified. With no
argument, defaults to editing config/application.rb
or config/environment.rb.
*rails-:Rfixtures*
:Rfixtures [{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.
*rails-:Rfunctionaltest*
:Rfunctionaltest [{name}]
Edit the functional test or controller spec for the
specified or current controller.
*rails-:Rhelper*
:Rhelper [{name}] Edit the helper for the specified name or current
controller.
*rails-:Rinitializer*
:Rinitializer [{name}] Edit the config/initializers file specified. With no
argument, defaults to editing config/routes.rb.
*rails-:Rintegrationtest*
:Rintegrationtest [{name}]
Edit the integration test, integration spec, or
cucumber feature specified. With no argument,
defaults to editing test/test_helper.rb.
*rails-:Rjavascript*
:Rjavascript [{name}] Edit the JavaScript for the specified name or current
controller. Also supports CoffeeScript in
app/scripts/.
*rails-:Rlayout*
:Rlayout [{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.
*rails-:Rlib*
:Rlib [{name}] Edit the library from the lib directory for the
specified name. If the current file is part of a
plugin, the libraries from that plugin can be
specified as well. With no argument, defaults to
editing db/seeds.rb.
*rails-:Rlocale*
:Rlocale [{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.
*rails-:Rmailer*
:Rmailer [{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.
*rails-:Rmetal*
:Rmetal [{name}] Edit the app/metal file specified. With no argument,
defaults to editing config/boot.rb.
*rails-:Rmigration*
:Rmigration [{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/schema.rb.
*rails-:Rmodel*
:Rmodel [{name}] Edit the specified or current model.
*rails-:Robserver*
:Robserver [{name}] Find the observer with a name like
{model}_observer.rb. When in an observer, most
commands (like :Rmodel) will seek based on the
observed model ({model}) and not the actual observer
({model}_observer). However, for the command
:Runittest, a file of the form
{model}_observer_test.rb will be found.
*rails-:Rplugin*
:Rplugin [{plugin}[/{path}]]
Edits a file within a plugin. If the path to the file
is omitted, it defaults to init.rb. If no argument is
given, it defaults to editing the application Gemfile.
*rails-:Rspec*
:Rspec [{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.
*rails-:Rstylesheet*
:Rstylesheet [{name}] Edit the stylesheet for the specified name or current
controller. Also supports Sass and SCSS.
*rails-:Rtask*
:Rtask [{name}] Edit the .rake file from lib/tasks for the specified
name. If the current file is part of a plugin, the
tasks for that plugin can be specified as well. If no
argument is given, either the current plugin's
Rakefile or the application Rakefile will be edited.
*rails-:Runittest*
:Runittest [{name}] Edit the unit test or model spec for the specified
name or current model.
*rails-:Rview*
:Rview [[{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.
Custom Navigation Commands ~
*rails-custom-navigation*
It is also possible to create custom navigation commands. This is best done
in an initialization routine of some sort (e.g., an autocommand); see
|rails-configuration| for details.
*rails-:Rnavcommand*
:Rnavcommand [options] {name} [{path} ...]
Create a navigation command with the supplied
name, looking in the supplied paths, using the
supplied options. The -suffix option specifies what
suffix to filter on, and strip from the filename, and
defaults to -suffix=.rb . The -glob option specifies
a file glob to use to find files, _excluding_ the
suffix. Useful values include -glob=* and -glob=**/*.
The -default option specifies a default argument (not
a full path). If it is specified as -default=model(),
-default=controller(), or -default=both(), the current
model, controller, or both (as with :Rintegrationtest)
is used as a default.
*rails-:Rcommand*
:Rcommand Obsolete alias for |:Rnavcommand|.
Examples: >
Rnavcommand api app/apis -glob=**/* -suffix=_api.rb
Rnavcommand config config -glob=*.* -suffix= -default=routes.rb
Rnavcommand concern app/concerns -glob=**/*
Rnavcommand exemplar test/exemplars spec/exemplars -glob=**/*
\ -default=model() -suffix=_exemplar.rb
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.
RAKE *rails-rake*
Rake integration happens through the :Rake command.
*rails-:Rake*
:[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.
*rails-:Rake!*
:[range]Rake! {targets} Called with a bang, :Rake will forgo opening the
quickfix window.
*rails-rake-defaults*
Generally, the default task is one that runs the test you'd expect. For
example, if you're in a view in an RSpec application, the view spec is run,
but if it's a Test::Unit application, the functional test for the
corresponding controller is run. The following table lists the most
interesting mappings:
File Task ~
unit test test:units TEST=...
functional test test:functionals TEST=...
integration test test:integration TEST=...
spec spec SPEC=...
feature cucumber FEATURE=...
model test:units TEST=... spec SPEC=...
controller test:functionals TEST=... spec SPEC=...
helper test:functionals TEST=... spec SPEC=...
view test:functionals TEST=... spec SPEC=...
fixtures db:fixtures:load FIXTURES=...
migration db:migrate VERSION=...
config/routes.rb routes
db/seeds.rb db:seed
Additionally, when :Rake is given a line number (e.g., :.Rake), the following
additional tasks can be invoked:
File Task ~
unit test test:units TEST=... TESTOPTS=-n...
functional test test:functionals TEST=... TESTOPTS=-n...
integration test test:integration TEST=... TESTOPTS=-n...
spec spec SPEC=...:...
feature cucumber FEATURE=...:...
controller routes CONTROLLER=...
fixtures db:fixtures:identify LABEL=...
migration in self.up db:migrate:up VERSION=...
migration in self.down db:migrate:down VERSION=...
migration elsewhere db:migrate:redo VERSION=...
task ... (try to guess currently edited declaration)
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.
SCRIPT WRAPPERS *rails-scripts*
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 <Tab> is supported.
*rails-:Rscript*
:Rscript {script} {options}
Call ruby script/{script} {options}. Defaults to
calling script/console.
*rails-:Rconsole*
:Rconsole {options} Obsolete. Call |:Rscript| instead.
*rails-:Rrunner*
:[range]Rrunner {code} Executes {code} with script/runner. Differs from
:Rscript runner {code} in that the code is passed as
one argument. Also, |system()| is used instead of
|:!|. This is to help eliminate annoying "Press
ENTER" prompts. If a line number is given in the
range slot, the output is pasted into the buffer after
that line.
*rails-:Rp*
:[range]Rp {code} Like :Rrunner, but call the Ruby p method on the
result. Literally "p begin {code} end".
*rails-:Rpp* *rails-:Ry*
:[range]Rpp {code} Like :Rp, but with pp (pretty print) or y (YAML
:[range]Ry {code} output).
*rails-:Rgenerate*
:Rgenerate {options} Calls script/generate {options}, and then edits the
first file generated.
*rails-:Rdestroy*
:Rdestroy {options} Calls script/destroy {options}.
*rails-:Rserver*
:Rserver {options} Launches script/server {options} in the background.
On win32, this means |!start|. On other systems, this
uses the --daemon option.
*rails-:Rserver!*
:Rserver! {options} Same as |:Rserver|, only first attempts to kill any
other server using the same port. On non-Windows
systems, lsof must be installed for this to work.
REFACTORING HELPERS *rails-refactoring*
A few features are dedicated to helping you refactor your code.
Partial Extraction ~
*rails-partials*
The :Rextract command can be used to extract a partial to a new file.
*rails-:Rextract*
:[range]Rextract [{controller}/]{name}
Create a {name} partial from [range] lines (default:
current line).
*rails-:Rpartial*
:[range]Rpartial [{controller}/]{name}
Obsolete alias for :Rextract.
If this is your file, in app/views/blog/show.html.erb: >
1 <div>
2 <h2><%= @post.title %></h2>
3 <p><%= @post.body %></p>
4 </div>
And you issue this command: >
:2,3Rextract post
Your file will change to this: >
1 <div>
2 <%= render :partial => 'post' %>
3 </div>
And app/views/blog/_post.html.erb will now contain: >
1 <h2><%= post.title %></h2>
2 <p><%= post.body %></p>
As a special case, if the file had looked like this: >
1 <% for object in @posts -%>
2 <h2><%= object.title %></h2>
3 <p><%= object.body %></p>
4 <% end -%>
<
The end result would have been this: >
1 <%= render :partial => 'post', :collection => @posts %>
<
The easiest way to choose what to extract is to use |linewise-visual| mode.
Then, a simple >
:'<,'>Rextract blog/post
will suffice. (Note the use of a controller name in this example.)
Migration Inversion ~
*rails-migrations* *rails-:Rinvert*
:Rinvert In a migration, rewrite the self.up method into a
self.down method. If self.up is empty, the process is
reversed. This chokes on more complicated
instructions, but works reasonably well for simple
calls to create_table, add_column, and the like.
INTEGRATION *rails-integration*
Having one foot in Rails and one in Vim, rails.vim has two worlds with which
to interact.
Integration with the Vim Universe ~
*rails-vim-integration*
A handful of Vim plugins are enhanced by rails.vim. All plugins mentioned can
be found at http://www.vim.org/. Cream and GUI menus (for lack of a better
place) are also covered in this section.
*rails-:Rtree*
:Rtree [{arg}] If |NERDTree| is installed, open a tree for the
application root or the given subdirectory.
*rails-:Rdbext* *rails-dbext*
:Rdbext [{environment}] This command is only provided when the |dbext| plugin
is installed. Loads the {environment} configuration
(defaults to $RAILS_ENV or development) from
config/database.yml and uses it to configure dbext.
The configuration is cached on a per application
basis. With dbext version 8.00 and newer, this
command is called automatically when needed. When
dbext is configured, you can execute SQL directly from
Vim: >
:Select * from posts order by id desc
:Update comments set author_id = 1
<
*rails-surround*
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.
Key Surrounding ~
= <%= ^ %>
- <% ^ -%>
# <%# ^ %>
<C-E> <% ^ -%>\n<% end -%>
The last surrounding is particularly useful in insert mode with the following
map in one's vimrc. Use Alt+o to open a new line below the current one. This
works nicely even in a terminal (where most alt/meta maps will fail) because
most terminals send <M-o> as <Esc>o anyways.
>
imap <M-o> <Esc>o
<
One can also use the <C-E> surrounding in a plain Ruby file to append a bare
"end" on the following line.
*rails-abolish*
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.
*rails-cream*
This plugin provides a few additional key bindings if it is running under
Cream, the user friendly editor which uses Vim as a back-end. Ctrl+Enter
finds the file under the cursor (as in |rails-gf|), and Alt+[ and Alt+] find
the alternate (|rails-alternate|) and related (|rails-related|) files.
*rails-menu*
If the GUI is running, a menu for several commonly used features is provided.
Also on this menu is a list of recently accessed projects. This list of
projects can persist across restarts if a 'viminfo' flag is set to enable
retaining certain global variables. If this interests you, add something like
the following to your vimrc: >
set viminfo^=!
<
Integration with the Rails Universe ~
*rails-rails-integration*
The general policy of rails.vim is to focus exclusively on the Ruby on Rails
core. Supporting plugins and other add-ons to Rails has the potential to
rapidly get out of hand. However, a few pragmatic exceptions have been made.
*rails-template-types*
Commands like :Rview use a hardwired list of extensions (erb, rjs, etc.)
when searching for files. In order to facilitate working with non-standard
template types, several popular extensions are featured in this list,
including haml, liquid, and mab (markaby). These extensions will disappear
once a related configuration option is added to rails.vim.
*rails-rspec*
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.
|:Runittest| and |:Rfunctionaltest| lead double lives, handling model and
controller specs respectively. For helper and view specs, you can use
|:Rspec| or define your own navigation commands:
>
Rnavcommand spechelper spec/helpers -glob=**/*
\ -suffix=_helper_spec.rb -default=controller()
Rnavcommand specview spec/views -glob=**/* -suffix=_spec.rb
<
ABBREVIATIONS *rails-abbreviations* *rails-snippets*
Abbreviations are "snippets lite". They may later be extracted into a
separate plugin, or removed entirely.
*rails-:Rabbrev*
:Rabbrev List all Rails abbreviations.
:Rabbrev {abbr} {expn} [{extra}]
Define a new Rails abbreviation. {extra} is permitted
if and only if {expn} ends with "(".
*rails-:Rabbrev!*
:Rabbrev! {abbr} Remove an abbreviation.
Rails abbreviations differ from regular abbreviations in that they only expand
after a <C-]> (see |i_CTRL-]|) or a <Tab> (if <Tab> 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<Tab> 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
Rabbrev :a :action\ =>\ render :a<Tab> render :action =>
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 "<Space>". 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).
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). There is one "smart" abbreviation, :c, which expands to
":controller => ", ":collection => ", or ":conditions => " depending on
context.
SYNTAX HIGHLIGHTING *rails-syntax*
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-syntax-keywords*
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.
If you feel a method has been wrongfully omitted, submit it to the
|rails-plugin-author|.
*rails-syntax-classes*
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.
*rails-syntax-assertions*
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|.
*rails-syntax-strings*
In the following line of code, the "?" in the conditions clause and the "ASC"
in the order clause will be highlighted: >
Post.find(:all, :conditions => ["body like ?","%e%"], :order => "title ASC")
<
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>>
<
*rails-syntax-yaml*
YAML syntax highlighting has been extended to highlight eRuby, which can be
used in most Rails YAML files (including database.yml and fixtures).
MANAGED VIM OPTIONS *rails-options*
The following options are set local to buffers where the plugin is active.
*rails-'shiftwidth'* *rails-'sw'*
*rails-'softtabstop'* *rails-'sts'*
*rails-'expandtab'* *rails-'et'*
A value of 2 is used for 'shiftwidth' (and 'softtabstop'), and 'expandtab' is
enabled. This is a strong convention in Rails, so the conventional wisdom
that this is a user preference has been ignored.
*rails-'path'* *rails-'pa'*
All the relevant directories from your application are added to your 'path'.
This makes it easy to access a buried file: >
:find blog_controller.rb
<
*rails-'suffixesadd'* *rails-'sua'*
This is filetype dependent, but typically includes .rb, .rake, and several
others. This allows shortening the above example: >
:find blog_controller
<
*rails-'includeexpr'* *rails-'inex'*
The 'includeexpr' option is set to enable the magic described in |rails-gf|.
*rails-'statusline'* *rails-'stl'*
Useful information is added to the 'statusline', when |g:rails_statusline| is
enabled.
*rails-'filetype'* *rails-'ft'*
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).
*rails-'completefunc'* *rails-'cfu'*
A 'completefunc' is provided (if not already set). It is very simple, as it
uses syntax highlighting to make its guess. See |i_CTRL-X_CTRL-U|.
CONFIGURATION *rails-configuration*
Very little configuration is actually required; this plugin automatically
detects your Rails application and adjusts Vim sensibly.
*rails-:autocmd* *rails-autocommands*
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! Rlcd
autocmd User Rails map <buffer> <F9> :Rake<CR>
You can also have autocommands that only apply to certain types of files.
These are based off the information shown when running the |:Rails!|
command, with hyphens changed to periods. A few examples: >
autocmd User Rails.controller* iabbr <buffer> wsn wsdl_service_name
autocmd User Rails.model.arb* iabbr <buffer> vfo validates_format_of
autocmd User Rails.view.erb* imap <buffer> <C-Z> <%= %><C-O>3h
End all such Rails autocommands with asterisks, even if you have an exact
specification, to allow for more specific subtypes to be added in the future.
There is also a filename matching syntax: >
autocmd User Rails/config/environment.rb Rabbrev c config
autocmd User Rails/**/foo_bar.rb Rabbrev FB:: FooBar
Use the filetype based syntax whenever possible, reserving the filename based
syntax for more advanced cases.
*macros/rails.vim*
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.
*config/rails.vim*
If you have settings particular to a specific project, they can be put in a
config/rails.vim file in the root directory of the application. The file is
sourced in the |sandbox| for security reasons.
*rails-:Rset*
:Rset {option}[={value}]
Query or set a local option. This command may be
called directly, from an autocommand, or from
config/rails.vim.
Options may be set in one of four scopes, which may be indicated by an
optional prefix. These scopes determine how broadly an option will apply.
Generally, the default scope is sufficient.
Scope Description ~
a: All files in one Rails application
b: Buffer (file) specific
g: Global to all applications
l: Local to method (same as b: in non-Ruby files)
Options are shown below with their default scope, which should be omitted.
While you may override the scope with a prefix, this is rarely necessary and
oftentimes useless. (For example, setting g:task is useless because the
default rake task will apply before considering this option.)
Option Meaning ~
b:alternate Custom alternate file for :A, relative to the Rails root
b:controller Default controller for certain commands (e.g., :Rhelper)
b:model Default model for certain commands (e.g., :Rfixtures)
l:related Custom related file for :R, relative to the Rails root
a:root_url Root URL for commands like :Rpreview
Examples: >
:Rset root_url=http://localhost:12345
:Rset related=app/views/blog/edit.html.erb
<
*rails-modelines*
If |g:rails_modelines| is enabled, these options can also be set from
modelines near the beginning or end of the file. These modelines will always
set buffer-local options; scope should never be specified. Examples: >
# Rset task=db:schema:load
<%# Rset alternate=app/views/layouts/application.html.erb %>
Modelines can also be local to a method. Example: >
def test_comment
# rset alternate=app/models/comment.rb
These two forms differ only in case.
Modelines are deprecated.
GLOBAL SETTINGS *rails-global-settings*
A few global variables control the behavior of this plugin. In general, they
can be enabled by setting them to 1 in your vimrc, and disabled by setting
them to 0. >
let g:rails_some_option=1
let g:rails_some_option=0
Most of these seldom need to be used. So seldom, in fact, that you should
notify the |rails-plugin-author| if you find any of them useful, as nearly all
are being considered for removal.
*g:loaded_rails* >
let g:loaded_rails=1
Set this include guard to prevent the plugin from being loaded.
*g:rails_abbreviations*
Enable Rails abbreviations. See |rails-abbreviations|. Enabled by default.
*g:rails_ctags_arguments* >
let g:rails_ctags_arguments='--languages=-javascript'
Additional arguments to pass to ctags from |:Rtags|. Defaults to ignoring
JavaScript files, since ctags has a tendency to choke on those.
*g:rails_default_file* >
let g:rails_default_file='config/database.yml'
File to load when a new Rails application is created, or when loading an
existing project from the menu. Defaults to the README.
*rails-screen* *g:rails_gnu_screen* >
let g:rails_gnu_screen=1
Use GNU Screen or Tmux (if it is running) to launch |:Rscript| console and
|:Rserver| in the background. Enabled by default.
*g:rails_history_size* >
let g:rails_history_size=5
Number of projects to remember. Set to 0 to disable. See |rails-menu| for
information on retaining these projects across a restart.
*g:rails_mappings* >
let g:rails_mappings=1
Enables a few mappings (mostly for |rails-navigation|). Enabled by default.
*g:rails_modelines* >
let g:rails_modelines=1
Enable modelines like the following: >
# Rset task=db:schema:load
Modelines set buffer-local options using the :Rset command.
Also enables method specific modelines (note the case difference): >
def show
# rset preview=blog/show/1
Modelines are deprecated and disabled by default.
*g:rails_menu* >
let g:rails_menu=1
When 2, a Rails menu is created. When 1, this menu is a submenu under the
Plugin menu. The default is 1 except on MacVim, where reports of weird
terminal output have led to it being disabled by default.
*g:rails_url* >
let g:rails_url='http://localhost:3000/'
Used for the |:Rpreview| command. Default is as shown above. Overridden by
b:rails_url.
*g:rails_statusline* >
let g:rails_statusline=1
Give a clue in the statusline when this plugin is enabled. Enabled by
default. This used to be a far more verbose indicator which included the
type of Rails file. If you actually liked this, you can add either
%{rails#statusline(1)} or %{rails#STATUSLINE(1)} to 'statusline' explicitly
(and let the author know, because this fallback is likely getting the boot).
*g:rails_syntax* >
let g:rails_syntax=1
When enabled, this tweaks the syntax highlighting to be more Rails friendly.
Enabled by default. See |rails-syntax|.
*rails-tabs* *g:rails_tabstop* >
let g:rails_tabstop=4
This option now requires the plugin railstab.vim from vim.org:
http://www.vim.org/scripts/script.php?script_id=2253
If your goal is simply just override this plugin's settings and use your own
custom 'shiftwidth', adjust things manually in an autocommand: >
autocmd User Rails set sw=4 sts=4 noet
This is highly discouraged: don't fight Rails.
ABOUT *rails-about* *rails-plugin-author*
This plugin was written by Tim Pope. Email him at <vimNOSPAM@tpope.org>. He
can also be found on Freenode's IRC network, hanging out in #rubyonrails and
#vim as tpope.
The official homepage is
http://rails.vim.tpope.net
The latest stable version can be found at
http://www.vim.org/scripts/script.php?script_id=1567
You can keep up to date with |GetLatestVimScripts|.
The very latest development versions can be retrieved from Git:
http://github.com/tpope/vim-rails
git clone git://github.com/tpope/vim-rails.git
The Github repository has Pledgie donations enabled. All donations made will
proxied along to ICCF, which goes to help needy children in |Uganda|.
Donations will be made in through the plugin author's vim.org account through
http://www.vim.org/sponsor/ . The voting privileges associated with the
donation will be used to vote for features that will enable better plugins in
the future. If you would rather keep those voting privileges for yourself, or
you want your donation to be tax deductible, donate directly through vim.org
instead. Donations have historically been matched.
Feedback is highly desired on this plugin. Please send all comments,
complaints, and compliments to the author. No bug is too small to report.
*rails-license*
This plugin is distributable under the same terms as Vim itself. See
|license|. No warranties, expressed or implied.
vim:tw=78:ts=8:ft=help:norl: