Created
June 16, 2021 21:17
-
-
Save zhulik/2dbc8064d7f607f049cda65108495730 to your computer and use it in GitHub Desktop.
An optimized template to build an includible DSL in 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
# 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