-
-
Save alassek/4432be39258976de5ce403fbdb36ef8d to your computer and use it in GitHub Desktop.
Option Proxy
This file contains 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
require "active_support/core_ext/module/delegation" | |
module UI | |
class OptionProxy | |
def initialize(parent, *method_names) | |
@__parent__ = parent | |
@__options__ = {} | |
method_names.each do |option| | |
define_singleton_method("#{option}=") { |value| @__options__[option.to_sym] = value } | |
end | |
end | |
def yield!(options) | |
return unless block_given? | |
yield self | |
options.merge!(**self) | |
end | |
delegate :to_hash, to: :@__options__ | |
def respond_to_missing?(method_name, *args, &block) | |
String(method_name).end_with?("=") | |
end | |
def method_missing(method_name, *args, &block) | |
if @__parent__.respond_to?(method_name) | |
@__parent__.send method_name, *args, &block | |
elsif respond_to_missing?(method_name) | |
option = String(method_name).delete_suffix("=").to_sym | |
@__options__[option] = args.shift | |
else | |
public_send method_name, *args, &block | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment