Automatically defining a variable in Rails console

1k views Asked by At

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
3

There are 3 answers

3
Sergio Tulentsev On BEST ANSWER

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.

  • I don't have to re-type the same definitions with every console restart
  • No pollution in the global config file
  • Local variables with nice short names (that is, without the @)
4
Jordan Running On

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.

0
tuffylock On

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/