Skip to content

Instantly share code, notes, and snippets.

@zhulik
Created June 16, 2021 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhulik/2dbc8064d7f607f049cda65108495730 to your computer and use it in GitHub Desktop.
Save zhulik/2dbc8064d7f607f049cda65108495730 to your computer and use it in GitHub Desktop.
An optimized template to build an includible DSL in Ruby.
# frozen_string_literal: true
module Extension
class T
class O
end
end
def self.foo(*args)
p("bar #{args}")
end
end
module Sugar
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def const_missing(name)
super unless Extension.const_defined?(name)
const_set(name, Extension.const_get(name))
end
end
def method_missing(name, *args, &block)
super unless Extension.respond_to?(name)
self.class.send(:define_method, name) { |*arrgs| Extension.send(name, *arrgs) }
Extension.send(name, *args, &block)
end
def respond_to_missing?(name, include_all)
return true if Extension.respond_to?(name)
super
end
end
class Main
include Sugar
def main
foo
foo(1)
foo(1, 2)
foo(1, test: true)
p(T)
p(T::O)
end
end
Main.new.main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment