Extend IRB main methods

血红的双手。 提交于 2019-12-08 10:17:29

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/27998113/extend-irb-main-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!