Search code examples
ruby-on-railsruby-on-rails-3listenerexecute

Write code that fires on "generate" commands


In which file in Rails do I need to place code that I want executed for example when the user types

rails g migration doSomethingFancy

My intention is to keep track of these commands in a sort-of log file. I noticed this relevant question, but it seems this method has been deprecated in Rails3 (creating a generate file doesn't work). Do you know of any way to achieve a similar result in Rails3?


Solution

  • Well, you could certainly do something similar by editing the rails script file.

    require 'rubygems'
    
    version = ">= 0"
    
    if ARGV.first =~ /^_(.*)_$/ and Gem::Version.correct? $1 then
      version = $1
      ARGV.shift
    end
    
    # This is the logging code
    CMD = "#{$0} #{ARGV.join(' ')}\n"
    File.open('/absolute-path/log/generate.log', 'a') {|f| f.write(CMD) }
    
    gem 'rails', version
    load Gem.bin_path('rails', 'rails', version)