Created
September 16, 2016 10:15
-
-
Save Electron-libre/019626622e96f8435990cfa9b1e4a655 to your computer and use it in GitHub Desktop.
Extend on demand
This file contains hidden or 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
# 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