Skip to content

Instantly share code, notes, and snippets.

@RyanScottLewis
Created May 25, 2010 07:40
Show Gist options
  • Save RyanScottLewis/412892 to your computer and use it in GitHub Desktop.
Save RyanScottLewis/412892 to your computer and use it in GitHub Desktop.
A way to make DSLs for Ruby
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