如何判断是否已使用generate
或destroy
命令来调用自定义生成器?
在Rails 2中你可以这样做:
if options[:command] == :destroy
...
end
我想打印一些有用的信息,但仅在调用rails generate
时,而不是在调用rails destroy
时:
if is_generating
puts "You're generated something!"
end
感谢。
答案 0 :(得分:1)
检查生成器类的行为。看起来你应该得到:invoke for generate或:revoke for destroy。例如,我添加了这个:
class PatternGenerator < Rails::Generators::NamedBase
def echo_behavior
p "generate? #{generating?}"
p "destroying? #{destroying?}"
end
protected
def generating?
:invoke == behavior
end
def destroying?
:revoke == behavior
end
end
运行这个,我得到:
younker % rails g pattern foo
"generate? true"
"destroying? false"
younker % rails destroy pattern foo
"generate? false"
"destroying? true"
似乎工作有道理,所以这是我的最终答案。