Skip to content

Instantly share code, notes, and snippets.

@alassek
Created October 23, 2019 14:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alassek/4432be39258976de5ce403fbdb36ef8d to your computer and use it in GitHub Desktop.
Save alassek/4432be39258976de5ce403fbdb36ef8d to your computer and use it in GitHub Desktop.
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