Vladimir Tsukanov
Vladimir Tsukanov

Reputation: 4459

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?

Upvotes: 19

Views: 16711

Answers (2)

Moiz Raja
Moiz Raja

Reputation: 5760

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)

Upvotes: 23

lucapette
lucapette

Reputation: 20724

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 

Upvotes: 2

Related Questions