Sometimes you can see:
do_this do
available_method1 "arg1"
available_method2 "arg1"
end
When I use the block from do_this method then I get some methods I could use inside that block.
I wonder how this is accomplished? How does the code look like behind the scenes?
I want to be able to provide some methods through a block.
It’s called a Domain-Specific Language (DSL). Here’s (Last archived version) some great info on various forms of Ruby DSL blocks.
There are really two ways to go about doing this, with different syntaxes:
The first is more explicit and less likely to fail, while the second is more concise.
The first can be implemented like so, by simply passing a new instance as the block parameter with
yield:And the second, which runs the block in the context of the new object, giving it access to
self, instance variables, and methods:And if you really want to do it without calling
MyThing.create, just: