有沒有辦法執行一些僅在控制檯啓動時才運行的代碼?有點像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
將此包含在初始化程序中 – apneadiving
在控制檯中只需鍵入:load'foo.rb',並執行foo.rb的內容。把所有你需要的代碼放在那裏。 – jdoe
@apneadiving:哪一位?整個東西? – pixelearth