如何运行一些代码只有当rails控制台启动,有点像一个rc文件? [英] How to run some code only when the rails console starts, kind of like an rc file?

查看:99
本文介绍了如何运行一些代码只有当rails控制台启动,有点像一个rc文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法执行一些只在控制台启动时运行的代码?类似一个rc文件( .bashrc .zshrc 等)?



例如,我将这个

放在哪里

  u = User.find_by_username('my_console_user')

c $ c> u 可在 rails console



这里,使用 $ 作为全局变量声明,并使用晦涩的控制台做。我假设有一些更优雅的东西...

  class Application< Rails :: Application 
#this仅在控制台中执行,也似乎在任何地方,但在这里:https://github.com/rails/rails/pull/3139
控制台
$ u1 = User.find_by_username('user1')
$ u2 = User.find_by_username('user2')
end

end


解决方案

如果使用 irb ,只需在〜/ .irbrc 中添加一个方法(如果不存在则创建一个):

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

如果您使用 pry-rails ,请将其添加到〜/ .pryrc >

希望这有助于!


Is there a way to execute some code that is run only when the console starts? Kind of like an rc file (.bashrc, .zshrc, etc.)? I find myself always doing certain things a lot.

For example, where would I put this

u = User.find_by_username('my_console_user')

so that u is available in rails console?

I have resorted to this, the use of $ as global variable declaration, and the use of the obscure console do. I assume there is something more elegant somehow...

  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

解决方案

If you use irb, just add a method in ~/.irbrc (create one if does not exist):

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

Or add to ~/.pryrc if you use pry-rails.

Hope this helps!

这篇关于如何运行一些代码只有当rails控制台启动,有点像一个rc文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆