At work, we���ve developed some plugins that cause issues when invoked in generators. For instance, you may be creating controllers on the fly, and so when you what to generate a controller to override the automatic one, you can���t as it is ���reserved���.
Well, you can determine what context in which you code is being executed quite easily using built in globals in Ruby.
$0 # returns the command executed to run this script, i.e. script/generate, rake, etc
unless $0 =~ /generate$/
puts "Code that wont run in generators goes here"
end
if $0 == 'rake' and ARGV[0] =~ /migrate$/
puts "special code to be run in migrations, like some cool migrations enhancing plugin for instance"
end
I���d love to wrap this in a nice plugin, patch or gem to enable cool things like this:
if ['db:migrate', 'db:schema:load', 'db:schema:dump'].include?(Rails.rake_task) or Rails.run_by?('script/generate')
puts "do cool stuff"
end