Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load file to rails console with access to variables defined in this file

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?

like image 982
Vladimir Tsukanov Avatar asked Oct 22 '11 14:10

Vladimir Tsukanov


2 Answers

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)

like image 108
Moiz Raja Avatar answered Sep 22 '22 22:09

Moiz Raja


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 
like image 28
lucapette Avatar answered Sep 23 '22 22:09

lucapette