-
-
Save RyanScottLewis/412892 to your computer and use it in GitHub Desktop.
A way to make DSLs for Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DSL | |
def initialize(*args, &blk); call(*args, &blk); end | |
def call(*args, &blk); instance_exec(*args, &blk); end | |
end | |
class Klass | |
def foo | |
print 'foo' | |
DSL.new do | |
def bar | |
puts 'bar' | |
end | |
def baz | |
puts 'baz' | |
end | |
end | |
end | |
end | |
klass = Klass.new | |
klass.foo.bar | |
klass.foo.baz | |
class Klass | |
class << self | |
def foo(&blk) | |
@dsl ||= DSL.new do | |
def bar(&blk) | |
say blk.call.to_s | |
end | |
def say(msg) | |
puts "foo#{msg}" | |
end | |
end | |
@dsl.instance_eval(&blk) if block_given? | |
@dsl | |
end | |
end | |
end | |
class MyKlass < Klass | |
foo do | |
bar do | |
'barbarbar' | |
end | |
say('mmmwoah') | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment