Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to define method to be accessible directly from rails console

So idea is to define

def foo
  puts "Works!"
end

and directly from the console without loading anything I write

irb(main):001:0>foo()
=> "Works!"
irb(main):002:0>

I am using 1.9.3 on Windows. I want to use this in order to have a method which will reload lib/* so that I don't need to restart the console. Thank you.

like image 611
Haris Krajina Avatar asked Dec 05 '25 02:12

Haris Krajina


1 Answers

I think this is what you're asking... I have the following code in an initializer:

if defined?(Rails::Console)
  require "util/console_extensions"
  include ConsoleExtensions
end

and any extra methods I want in the console defined in lib/util/console_extensions.rb

module ConsoleExtensions
  def foo
    puts "Works!"
  end
end

This automatically requires and includes the ConsoleExtension module when loading the rails console and makes the methods defined in it available without the need to manually load anything.

like image 80
Russell Avatar answered Dec 07 '25 17:12

Russell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!