Reputation: 819
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!
Upvotes: 4
Views: 2544
Reputation: 3113
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
Upvotes: 4
Reputation: 2296
if you just need to check if the server is running you can use this one
if defined?(Rails::Server)
# do something usefull
end
Upvotes: 9
Reputation: 3638
You could check if the Rails Console is defined:
run_code unless defined?(Rails::Console)
Upvotes: 1