ruby-on-railsrubyirbhirb

Extend IRB main methods


I have a directory structure in my app. For development purposes (and possibly beyond), I currently have a class X which has class methods pwd, cd, and ls. Is there a way to make these methods available when I enter irb whithin my app, for example:

2.1.5 :0 > pwd
/current_dir/

Currently I am doing:

2.1.5 :0 > X.pwd
/current_dir/

which is simply inconvenient.

A solution where I could simply add something to my existing class would be perfect, like:

class X < Irb::main
  def self.pwd
    #stuff
  end
end

Right now I don't really dig hirb, but if there is a solution that works with hirb or irb, I'll give it a shot! Thanks for your help!


Solution

  • In Rails, you can conditionally mix methods into the console when the Rails app is started via IRB.

    This is done using the console configuration block in your application.rb file.

    module MyApp
      class Application < Rails::Application
    
        # ...
    
        console do
          # define the methods here
        end
    
      end
    end
    

    In your case, there are several possibilities. You can simply delegate the methods to your library.

    module MyApp
      class Application < Rails::Application
        console do
    
          # delegate pwd to X
          def pwd
            X.pwd
          end
    
        end
      end
    end
    

    or if X is a module, you can include it

    module MyApp
      class Application < Rails::Application
        console do
          Rails::ConsoleMethods.send :include, X
        end
      end
    end