Sisss
Sisss

Reputation: 55

Load a file of Ruby code

Having the following files:

# ./app.rb
require_relative 'container'
require_relative 'contained'

# ./container.rb
class Foo
  def initialize &block
    puts block.call
  end
end

# ./contained.rb
Foo.new do
  "Hello, world!"
end

We can test and see everything's okay from a console:

$ ruby ./app.rb
Hello, world!

But I would like to simplify contained.rb by removing Foo.new do and end, keeping just the content of the block, by modifying app.rb.

In this quest, I came to this result:

# ./app.rb
require_relative 'container'
require_relative 'contained'

Foo.new do
  eval File.open('contained.rb').read
end

# ./container.rb
class Foo
  def initialize &block
    puts block.call
  end
end

# ./contained.rb
"Hello, world!"

With the same result:

$ ruby ./app.rb
Hello, world!

However I am not very proud of this code, mostly because of the eval method. Is there a best practice in this kind of case? What would you do? Thanks for sharing your light.

Upvotes: 0

Views: 55

Answers (1)

sawa
sawa

Reputation: 168091

The fact that you want to read from a separate file must be that you want to separate it from the main code and you want to occasionally change it. That category of things belongs to what would be called configuration. It is common these days to write that as a YAML file and read into Ruby using a yaml library.

Upvotes: 1

Related Questions