2015-11-11 43 views

回答

4

我對這個任務

#lib/initializer_helpers.rb 
module InitializerHelpers 

    def self.skip_console_rake_generators &block 
    skip(defined?(Rails::Console) || defined?(Rails::Generators) || File.basename($0) == "rake", &block) 
    end 

    def self.skip_rake_generators &block 
    skip(defined?(Rails::Generators) || File.basename($0) == "rake", &block) 
    end 

    def self.skip_generators &block 
    skip(defined?(Rails::Generators), &block) 
    end 

    def self.skip_console &block 
    skip(defined?(Rails::Console), &block) 
    end 

    private 

    def self.skip(condition, &block) 
    raise ArgumentError.new("no block given") if block.blank? 
    unless condition 
     yield 
    end 
    end 

end 

# use it 
InitializerHelpers.skip_console do 
    # not executed in console 
end 

更新特殊助手:如果你只是提取這個想法寶石https://github.com/olegantonyan/initializer_helpers

1

你可以檢查Rails的控制檯定義:

run_code unless defined?(Rails::Console) 
2

需要檢查服務器是否在運行,您可以使用這一個

if defined?(Rails::Server) 
    # do something usefull 
end