Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip initializer if not rails s running it

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!

like image 514
Tudor S. Avatar asked Dec 08 '22 00:12

Tudor S.


2 Answers

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

like image 37
Oleg Antonyan Avatar answered Dec 23 '22 20:12

Oleg Antonyan


if you just need to check if the server is running you can use this one

if defined?(Rails::Server)
  # do something usefull
end
like image 133
rob Avatar answered Dec 23 '22 19:12

rob