Skip to content

Instantly share code, notes, and snippets.

@Electron-libre
Created September 16, 2016 10:15
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 Electron-libre/019626622e96f8435990cfa9b1e4a655 to your computer and use it in GitHub Desktop.
Save Electron-libre/019626622e96f8435990cfa9b1e4a655 to your computer and use it in GitHub Desktop.
Extend on demand
# this wont work for immediate values as Fixnum Symbols but there may be workaround
#
module Doublable
def self.extended(base)
case base
when ::Array
base.extend Doublable::Array
when ::String
base.extend Doublable::String
when ::Numeric
base.extend Doublale::Numeric
else
base.extend NotDoublable
end
end
module Array
def double
collect {|e| e.dup.extend(Doublable).double }
end
end
module Numeric
def double
self * 2
end
end
module String
def double
self.next
end
end
module NotDoublable
def double
raise "don't know how to double #{self.class} #{self.inspect}"
end
end
end
class MyView
attr_reader :target
def initialize(target)
@target = target
end
def double
target.dup.extend(Doublable).double
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment