Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to require a file only for console

I've a Ruby class that I will use only for console, it monkey patches ActiveRecord::Base with some shortcuts like ua for update_attribute and I don't want to load it when running rails server but only when running the rails console command.

What is the way to achieve this?

like image 709
Arnold Roa Avatar asked Feb 09 '16 11:02

Arnold Roa


Video Answer


1 Answers

rails console defines Rails::Console

So you can do

if defined?(Rails::Console)
  # this runs only in rails console
end

Another approach would be to use config/application.rb:

module MyApplication
  class Application < Rails::Application
    console do
      require 'my_console_file'
    end
  end
end
like image 74
Mihai Dinculescu Avatar answered Oct 05 '22 08:10

Mihai Dinculescu