In Ruby on Rails, "if defined? Product" doesn't work in script/runner mode?
If there is a simple script and to distinguish whether it is running by itself or being run inside the Rails app environment, I tried using
if defined? Product
# something
end
but it failed to be recognized even though Product is defined and can be used otherwise. Since then I tried using
if defined? RAILS_ENV
ins开发者_JS百科tead and it works well, but wonder why the defined? Product
doesn't work?
This should work
if Product
# something
end
defined? ModelName returns nil for all my models.
Loading development environment (Rails 2.3.8)
>> defined? Post
=> nil
But then if I do this
>> Post; defined? Post
=> "constant"
Probably because nothing is loaded until you touch it. Hope this helps.
Edit: Ah ok well then, script/runner is a non-interactive form of script/console, I would think it loads the whole Rails app and runs from that context. If you need to identify wether the call was made from script/runner I can only think of passing a parameter to the function Model.long_running_method(:runner => true) and do your conditional check on that or if that is not convenient enough set a ENV constant ENV['something_runner']. And do the condition check on that instead.
精彩评论