Init some variables when opening rails console

筅森魡賤 提交于 2019-12-11 14:48:47

问题


Here's the thing. I use quite a lot the console to test my methods before plugging them in my app (nothing new here I guess).

What I'd find convenient, would be to have like a console_seed.rb file that I would load and then all my variables are ready for use.

Ex: console_seed.rb

me = User.find(77)
other_person = User.find(89)

So I can immediately test:

me.add_friend(other_person)

when opening the console, without having to write the .find() lines again and again.

I found this post : how can I run an initializer from the rails console?

load "#{Rails.root}/config/db/console_seed.rb"

which would do the trick but unfortunately, the variables created in the file don't share the same context as the console ...

Could rails magik happen again in this situation ? :)


回答1:


Thanks to @dave-newton suggestions, I found a nice solution through .irbrc

Created a ~/.irbrc file:

// when rails constole is started, go find the console_seed.rb - project specific - file
require Dir.pwd + "/db/console_seed.rb"
puts 'Config init'

And App_Root_Path/db/console.seed.rb file:

Me = User.find(77)
Other_person = User.find(89)

The trick is that Me and Other_person have to be constants and not variables, otherwise they are not passed to the console scope. But in my case, it actually makes sense to have constants. Otherwise, method definition could be used, but I haven't explored this possibility yet.

My only frustration remains on the fact that my teamates need to create their own ~/.irbrc file to get the same behaviour, it is not automatically included into git scope ... Any suggestion for doing this? Ain't there any script that is loaded everytime the console is initialized?



来源:https://stackoverflow.com/questions/18553944/init-some-variables-when-opening-rails-console

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