Reputation: 1665
Depending on what I'm working on, I routinely define variables (e.g., f = Foo.last
) when I open rails console
.
Is there any way to do this automatically in my development environment?
For what it's worth, I'm using pry.
I can do this, but the session will exit:
$ rails c <<EOF
heredoc> f = Foo.last
heredoc> EOF
Upvotes: 1
Views: 1103
Reputation: 1
i poked around for a way to do this for a while and the best i've come up with is a way to set multiple variables in one line, at least. (keeping in mind that i do not want to use instance variables, and i want to be able to overwrite them, so methods wouldn't work):
in ~/.pryrc
:
# f, b, u, s = setup
def setup
f = Foo.last
b = Foo.bar
u = User.find(5)
s = u.settings.email_settings
[f, b, u, s]
end
and so on.
i also found a post that covers abstracting the method approach, if you don't need to be able to overwrite them: http://kevinkuchta.com/_site/2014/09/load-useful-data-in-rails-console/
Upvotes: 0
Reputation: 106017
As an alternative to Sergio's suggestion of instance variables, you can also define methods in .pryrc
:
def f
@_f ||= Foo.last
end
I'm not certain this has all of the semantics you want, but it works for me.
Upvotes: 5
Reputation: 230276
If you're fine with instance variables, you can add those to ~/.pryrc
@f = Foo.last
With local variables this won't work, because they're local to their scope (hence the name).
What I do myself, is have all of the "setup" commands in a separate text file. Then in the new rails console, I just paste it.
@
)Upvotes: 4