Ex Dolo::With Intent

search:

Renaming View File Extensions for Rails 2.0

September 26, 2007 @ 02:22 PM

It's not exactly breaking news that .rhtml and friends are no longer the preferred file extensions in the ramp up to Rails 2.0. Though the file extensions are set to be fully functional all through the life-span of the 2.x line (until 3.0), there's no time like the present for house cleaning.

Thusly, I present a lil' task to take care of the nitty gritty details:

    namespace :extension do
      desc 'rename file extensions to Rails 2.0 style conventions'
      task :rename do

        require 'find'

        def ext_for(path)
          case path
          when 'html' : 'erb'
          when 'xml'  : 'builder'
          when 'js'   : 'rjs'
          else ''
          end
        end

        cmd = ENV['mv'] || 'svn mv'

        Find.find('app/views') do |path|
          if File.directory?(path)
            File.basename(path) =~ /^\.svn$/ ? Find.prune : next
          end
          if path =~ /\.r(?:html|xml|js)$/
            shell = "#{cmd} #{path} #{path.gsub(/(.*)\.r(html|xml|js)$/,'\1.\2.')}#{ext_for($2)}"
            ENV['dry'] ? puts(shell) : system(shell)
          end
        end

      end
    end

Usage

To do a dry run and get a comprehensive list of all the files to be changed and the exact syntax used to do so, run like so from the root of your Rails application:

rake extension:rename dry=true

NB: you can pass the dry key any value you like (even 'tap-dancing-koala-bear' if you are so inclined) and it'll still provide you with the aforementioned pretty read-out.

There's also an optional argument for you crazy non-subversion using folk to replace the svn mv bit handily:

rake extension:rename mv='git-mv'

or even:

rake extension:rename mv='mv'

for you heathens that don't even use SCM.

Get it

Either copy the above into a rake file in your lib/tasks directory or if you're one of the cool kids, take yours to go in the form of a Sake Bomb:

sake -i http://pastie.caboo.se/101107.txt

Given the one-off nature and applicability to different projects, make mine a Sake, thanks.

Comments

powered by rails and mephisto.