Skip to content

Instantly share code, notes, and snippets.

@alassek alassek/option_proxy.rb Secret
Created Oct 23, 2019

Embed
What would you like to do?
Option Proxy
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
You can’t perform that action at this time.