fotanus
fotanus

Reputation: 20106

How to execute local functions using code from external file in ruby?

Can a require execute a locally defined function? I guess the easiest way to describe what I need is to show an example.

I'm using ruby 1.9.3, but solutions for 1.8 and 2.0 are also welcome.

I have a file main.rb as the following:

class Stuff
  def self.do_stuff(x)
    puts x
  end
  require_relative('./custom.rb')

  do_stuff("y")
end

And also have a file custom.rb in the same folder, with the following content:

do_stuff("x")

Running main.rb, I have following output:

/home/fotanus/custom.rb:1:in `<top (required)>': undefined method `do_stuff' for main:Object (NoMethodError)
    from main.rb:5:in `require_relative'
    from main.rb:5:in `<class:Stuff>'
    from main.rb:1:in `<main>'

Note that without the require, the output is y.

Upvotes: 2

Views: 974

Answers (2)

Max
Max

Reputation: 22315

In C, #include literally drops the code as-is into the file. require in Ruby is different: it actually runs the code in the required file in its own scope. This is good, since otherwise we could break required code by redefining things before the require.

If you want to read in the contents of a script and evaluate it in the current context, there are methods for doing just that: File.read and eval.

Upvotes: 2

Pigueiras
Pigueiras

Reputation: 19356

I'm not sure if it is the best solution but using eval should do the trick.

class Stuff
  def self.do_stuff(x)
    puts x
  end
  eval(File.read('./custom.rb'))

  do_stuff("y")
end

The output will be:

pigueiras@pigueiras$ ruby stuff.rb 
x
y

Upvotes: 5

Related Questions