2012-05-01 31 views
7

有沒有辦法執行一些僅在控制檯啓動時才運行的代碼?有點像rc文件(.bashrc.zshrc等)?我發現自己總是在做某些事情。如何僅在軌道控制檯啓動時運行某些代碼,類似於rc文件?

例如,我會在哪裏把這個

u = User.find_by_username('my_console_user') 

使u可在rails console

我已經訴諸於此,使用$作爲全局變量聲明,並使用了不明確的console do。我認爲有一些更優雅莫名其妙......

class Application < Rails::Application 
    #this is only executed in the console, also doens't seem to be documented anywhere but here: https://github.com/rails/rails/pull/3139 
    console do 
     $u1 = User.find_by_username('user1') 
     $u2 = User.find_by_username('user2') 
    end 

    end 
+0

將此包含在初始化程序中 – apneadiving

+1

在控制檯中只需鍵入:load'foo.rb',並執行foo.rb的內容。把所有你需要的代碼放在那裏。 – jdoe

+0

@apneadiving:哪一位?整個東西? – pixelearth

回答

3

如果使用irb,只需添加一個方法~/.irbrc(創建一個如果不存在):

def find_by_username(username) 
    User.find_by_username('my_console_user') 
end 

或加入~/.pryrc如果您使用pry-rails

希望這會有所幫助!

+1

我們希望這是項目本身的一部分嗎?以便其他開發人員可以獲得好處? –

+0

將irbrc/pryrc提交到版本控制。 – juanitofatas

+0

然後給用戶留下說明將其複製到他們的主文件夾? –

相關問題