Pass a whole file to #instance_eval

Hey there!

I’m a Ruby beginner and I’m stuck with a doubt.
I want realize a sort of DSL that looks like:

require 'exampledsl'

method1 do
    #...
end

method2 do
    #...
end

Because these method aren’t part of Kernel module I can’t call them in
this way so I thought to pass the whole file using ‘load’ to the
methods’ class like:

Example.instance_eval { load "./example.rb" }

But I’m not sure if it’s ‘good practice’ or there’s a cleaner way.
I saw on Google but without results.

Mark McCoy wrote in post #1184859:

Hey there!

I’m a Ruby beginner and I’m stuck with a doubt.
I want realize a sort of DSL that looks like:

require 'exampledsl'

method1 do
    #...
end

method2 do
    #...
end

declare your dsl in Kernel module:

module Kernel
def methode1() yield end
def methode1() yield end
end

Or, better, declare them in your module, and ask to
your user to make a “include DSL”:

exampledsl.rb:
module DSL
def methode1() yield end
def methode1() yield end
end

Use:

require ‘exampledsl’
include DSL

Example.instance_eval { load "./example.rb" }

Example.instance_eval { File.read “./example.rb” }

(but very dangerous :slight_smile:

What if I want execute an operation at the end without implicitly write
it like, for instance, pass ‘a’ to a class.

require 'exampledsl'
include DSL

a = 1

method_1 do
  a += 1
end

method_2 do
  a += 2
end