DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Rails And Vim

07.28.2006
| 7675 views |
  • submit to reddit
        A simple command for opening related Rails project files in Vim:

#!/usr/bin/env ruby

if ARGV.empty?
  puts "usage: #{File.basename($0)} string" 
  puts "  Scans related Rails directories for " + 
         "files begining with string " 
  puts "  and opens them in vi." 
  exit
end

files = []
ignore = [/CVS$/]

# Find models or controllers that match args
ARGV.each do |arg|
  models = Dir["app/models/#{arg}*"]
  controllers = Dir["app/controllers/#{arg}*"]
  files += models + controllers
end

# Remove duplicates
files.sort!.uniq!

# Add unit tests for models
files.grep(%r{app/models/(.*?).rb}) do
  tests = Dir["test/unit/#{$1}_test.rb"]
  files += tests
end

# Add views and functional tests for controllers
files.grep(%r{app/controllers/(.*?)_controller.rb}) do
  views = Dir["app/views/#{$1}/*"]
  tests = Dir["test/functional/#{$1}_controller_test.rb"]
  files += views + tests
end

# Add views and fixtures for mailers
files.grep(%r{app/models/(.*?_mailer).rb}) do
  views = Dir["app/views/#{$1}/*"]
  fixtures = Dir["test/fixtures/#{$1}/*"]
  files += views + fixtures
end

# Again remove duplicates
files.sort!.uniq!

# Remove files that match ignore list
files.delete_if do |filename|
  result = false
  ignore.each do |i|
    if filename =~ i
      result = true
      break
    end
  end
  result
end

system "vi -o #{files.join(' ')}" 

Drop it in a file called "edit" in your path and you can open related rails files with a few key strokes:

# open AccountController and related tests and views:
edit account_c

# open AccountMailer and related tests, views, and fixtures:
edit account_m

# open everything related to accounts:
edit account

A detailed explanation here: <a href="http://wiseheartdesign.com/articles/2006/07/27/rails-and-vim/">http://wiseheartdesign.com/articles/2006/07/27/rails-and-vim/</a>.