Init some variables when opening rails console

544 Views Asked by At

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

There are 1 best solutions below

0
On

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?