Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

initial commit

  • Loading branch information...
commit 379c922e69f26fa38ab96c795c6814b39da28c3b 0 parents
@zdennis authored
16 lib/functional_struct.rb
@@ -0,0 +1,16 @@
+class FunctionalStruct
+ def initialize(options={})
+ metaclass = class << self ; self ; end
+ options.each_pair do |method_name, val|
+ if val.is_a?(Proc)
+ metaclass.send :define_method, method_name do |*args|
+ val.call(*args)
+ end
+ else
+ metaclass.send :define_method, method_name do
+ val
+ end
+ end
+ end
+ end
+end
23 spec/functional_struct_spec.rb
@@ -0,0 +1,23 @@
+require File.dirname(__FILE__) + '/spec_helper'
+
+describe FunctionalStruct do
+ it "behaves like an OpenStruct" do
+ o = FunctionalStruct.new(:a => 1, :b => 2, "c" => 3)
+ o.a.should == 1
+ o.b.should == 2
+ o.c.should == 3
+ end
+
+ it "makes procs callable" do
+ o = FunctionalStruct.new(
+ :foo => lambda { "foo" },
+ :bar => lambda { "bar" })
+ o.foo.should == "foo"
+ o.bar.should == "bar"
+ end
+
+ it "makes procs callable with arguments" do
+ o = FunctionalStruct.new(:foo => lambda { |a| "foo#{a}" })
+ o.foo("d").should == "food"
+ end
+end
4 spec/spec_helper.rb
@@ -0,0 +1,4 @@
+require 'rubygems'
+require 'spec'
+
+require File.dirname(__FILE__) + '/../lib/functional_struct'
Please sign in to comment.
Something went wrong with that request. Please try again.