Rails code that doesn’t get executed for generations and migrations
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.
To elaborate on the boss’s original post
|
1 2 3 4 5 6 7 8 9 10 11 |
<code class='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 </code> |
I’d love to wrap this in a nice plugin, patch or gem to enable cool things like this:
|
1 2 3 4 5 |
<code class='ruby'> if ['db:migrate', 'db:schema:load', 'db:schema:dump'].include?(Rails.rake_task) or Rails.run_by?('script/generate') puts "do cool stuff" end </code> |