Created
March 10, 2011 22:50
-
-
Save ashmoran/865117 to your computer and use it in GitHub Desktop.
A completely stupid example of how to implement classes/objects in Ruby with Procs and Proc#method_missing
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 Proc | |
| def method_missing(name, *args) | |
| self[name, *args] | |
| end | |
| end | |
| MyCrazyClass = ->(message, *args) { | |
| case message | |
| when :new | |
| ->(message, *args) { | |
| case message | |
| when :foo | |
| "foo" | |
| when :upcase | |
| args.first.upcase | |
| end | |
| } | |
| else | |
| raise NoMethodError.new | |
| end | |
| } | |
| describe MyCrazyClass do | |
| it "responds to new" do | |
| expect { | |
| MyCrazyClass.new | |
| }.to_not raise_error | |
| end | |
| it "does not respond to arbitrary messages" do | |
| expect { | |
| MyCrazyClass.foobarbazquux | |
| }.to raise_error(NoMethodError) | |
| end | |
| end | |
| describe MyCrazyClass do | |
| subject { MyCrazyClass.new } | |
| its(:foo) { should eq "foo" } | |
| it "can upcase strings" do | |
| subject.upcase("a string").should eq "A STRING" | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment