8

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?

Mihai Dinculescu
  • 19,743
  • 8
  • 55
  • 70
Arnold Roa
  • 7,335
  • 5
  • 50
  • 69

2 Answers2

9

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
Robin Daugherty
  • 7,115
  • 4
  • 45
  • 59
Mihai Dinculescu
  • 19,743
  • 8
  • 55
  • 70
  • 1
    a file in initialize would be a good place to put this? remember that i want to monkey path ActiveRecord classes – Arnold Roa Feb 09 '16 at 14:07
  • This seems to work only for Rails 3+, any idea for rails 2.3? – Arnold Roa Feb 09 '16 at 14:22
  • An initializer sounds like a good idea. As for rails 2.3, sorry I have no idea. Isn't `Rails::Console` getting defined? – Mihai Dinculescu Feb 09 '16 at 16:47
  • Hm, I wish this worked, but putting it in an initializer doesn't actually seem to require the files I want it to, at least when using the Rails 4+ spring-ified console (don't know how to test without Spring). EDIT: This answer worked for me: http://stackoverflow.com/a/31961065/337446 – swrobel Feb 04 '17 at 02:31
  • `rails c` Running via Spring preloader in process 3170 Loading development environment (Rails 5.0.1) 2.3.0 :001 > `defined?(Rails::Console)` => "constant" – Mihai Dinculescu Feb 04 '17 at 10:01
  • @swrobel It's working for me in Rails 5.0.1 with Spring. I have updated my answer with your suggestion though, it's a good approach nonetheless. Thanks! – Mihai Dinculescu Feb 04 '17 at 10:02
1

You could set up a new environment, "console", by copying one of the existing ones and making the desired changes, and then always launch the console in that environment. This seems like it will cut down on accidental side-effect syndrome.

Max Williams
  • 32,435
  • 31
  • 130
  • 197