I've got some code in an initializer and I'd like it to run only when the server starts but not when the console is started. Is there any way of telling them apart?
Thanks!
I have special helper for this task
#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
Update: extracted this idea to gem https://github.com/olegantonyan/initializer_helpers
if you just need to check if the server is running you can use this one
if defined?(Rails::Server)
# do something usefull
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With