Last active
December 26, 2015 23:29
-
-
Save solnic/85215f57c3ee8d669363 to your computer and use it in GitHub Desktop.
Ruby object that has "functions" rather than methods
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
class Function | |
attr_reader :name, :fn | |
class Composed | |
attr_reader :left, :right | |
def initialize(left, right) | |
@left = left | |
@right = right | |
end | |
def call(input) | |
left.(right.(input)) | |
end | |
end | |
def initialize(name, fn) | |
@fn = fn | |
end | |
def *(other) | |
Composed.new(self, other) | |
end | |
def call(input) | |
fn.(input) | |
end | |
end | |
class FunctionObject | |
def self.method_added(name) | |
return if @busy | |
meth = instance_method(name) | |
defn(name, meth) | |
end | |
def self.defn(name, meth) | |
@busy = true | |
undef_method(name) | |
define_method(name) do | |
Function.new(name, meth.bind(self)) | |
end | |
@busy = false | |
end | |
end | |
RSpec.describe FunctionObject do | |
it 'has functions' do | |
things = Class.new(FunctionObject) do | |
def sort(data) | |
data.sort | |
end | |
def upcase(data) | |
data.map(&:upcase) | |
end | |
end.new | |
data = %w(foo bar) | |
expect((things.sort * things.upcase).(data)).to eql(%w(BAR FOO)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment