Load file to rails console with access to variables defined in this file
Asked Answered
C

2

19

I work with rails console and often i need to preload some ruby code to work with.

#file that i want to load in rails console
#my_file.rb
a = 1
b = 2
puts a + b 

When i run my console with ./script/console

rails-console :001 > load 'my_file.rb' 
3
 => []
rails-console :002 > a
NameError: undefined local variable or method 'a' for #<Object:123445>

How can i get access to my 'a' and 'b' variables in console?

Calmative answered 22/10, 2011 at 14:36 Comment(0)
U
22

When you load a file local variables go out of scope after the file is loaded that is why a and b will be unavailable in the console that loads it.

Since you are treating a and b as constants how about just capitalizing them like so

A = 1
B = 2
puts A+B

Now in you console you should be able to do the following

load 'myfile.rb'
A #=> 1

Alternately you could make the variables in myfile.rb global ($a, $b)

Unwritten answered 22/10, 2011 at 14:52 Comment(1)
you can also access vars like @a and @b in this file and use them in irb console :-)Tarsia
V
2

First of all, you should use an irbrc. Please read more here for example.

Then you could define a method in your irbrc to mock your variables:

def a
 [1, 2, 4]
end

but I prefer to add methods to specific Ruby classes like:

class Array
  def self.toy(n=10,&block)
    block_given? ? Array.new(n,&block) : Array.new(n) {|i| i+1}
  end
end 
Valorize answered 22/10, 2011 at 14:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.