Skip to content

Instantly share code, notes, and snippets.

@RichOrElse
Last active September 20, 2020 15: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 RichOrElse/6ddcc064ca75ef54479e9007a45ee6f9 to your computer and use it in GitHub Desktop.
Save RichOrElse/6ddcc064ca75ef54479e9007a45ee6f9 to your computer and use it in GitHub Desktop.
DelegateTo
class DelegateTo < BasicObject
include ::Kernel
def initialize(object)
@delegate_to = object
end
def inspect
"#{self.class.inspect}[#{@delegate_to}]"
end
class << self
alias_method :[], :new
def to_proc
method(:new).to_proc
end
def const_missing(name)
::Object.const_get(name)
end
end
end
def DelegateTo(target, &block)
comparisons = [:=~, :!~, :===, :<=>, :eql?, :hash]
Class.new(::DelegateTo) do
delegate_missing_to target
delegate target, to: :@delegate_to
delegate :to_s, *comparisons, to: target
define_method(:==) do |other|
return true if other.equal?(self)
public_send(target) == other
end
define_method(:!=) do |other|
return false if other.equal?(self)
public_send(target) != other
end
define_singleton_method(:inspect) do
name || "DelegateTo(#{target})"
end
class_eval(&block) unless block.nil?
end
end
Current = DelegateTo(:current)
now = Current[Time]
First = DelegateTo(:first)
first = First.new [1,2,3]
# => First[[1, 2, 3]]
first == first
# => true
first == First.new([3,2,1])
# => false
first == 1 # => true
first != 1 # => false
first == 2 # => false
first != 2 # => true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment