Created
June 28, 2015 04:24
-
-
Save 0x0dea/f2ac964c4cedbc90bb6d to your computer and use it in GitHub Desktop.
Pseudo-class composition in Ruby.
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
module Composable | |
extend self | |
def extended klass | |
klass.send :attr_reader, :val | |
end | |
def method_missing klass | |
f, g = self, const_get(klass) | |
Class.new do | |
define_method(:initialize) do |n| | |
@val = f.new(g.new(n).val).val | |
end | |
end.extend Composable | |
end | |
end | |
class Succ | |
extend Composable | |
def initialize n | |
@val = n.succ | |
end | |
end | |
class Twice | |
extend Composable | |
def initialize n | |
@val = n * 2 | |
end | |
end | |
(Twice . Succ . Twice).new(10).val # => 42 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment