2015-01-17 72 views
0

我在我的应用程序中有一个目录结构。为了开发目的(以及可能超出),我目前有一个类别X,其具有类别方法pwd,cdls。有没有一种方法,使这些方法可当我输入irb whithin我的应用程序,例如:扩展IRB主要方法

2.1.5 :0 > pwd 
/current_dir/ 

目前我做的:

2.1.5 :0 > X.pwd 
/current_dir/ 

这简直是不方便的。

一个解决方案,我可以简单地添加了一些我现有的类将是完美的,如:

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

现在我真的不挖hirb,但如果有与hirb或有效的解决方案irb,我会给它一个镜头!谢谢你的帮助!

+0

https://github.com/janlelis/irbtools –

回答

2

在Rails中,当通过IRB启动Rails应用程序时,您可以有条件地将方法混合到控制台中。

这是使用application.rb文件中的console配置块完成的。

module MyApp 
    class Application < Rails::Application 

    # ... 

    console do 
     # define the methods here 
    end 

    end 
end 

在你的情况下,有几种可能性。您可以简单地将这些方法委托给您的库。

module MyApp 
    class Application < Rails::Application 
    console do 

     # delegate pwd to X 
     def pwd 
     X.pwd 
     end 

    end 
    end 
end 

,或者如果X是一个模块,可以将其包含

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

这真棒。正是我需要知道的。谢谢。 – nufftenthousand