Permalink
Browse files

First commit

  • Loading branch information...
0 parents commit 53585033d50c745cdac97f37ac0748c924a751b0 @wycats committed Jul 14, 2010
Showing with 96 additions and 0 deletions.
  1. +18 −0 README.markdown
  2. +44 −0 lib/chainable_compare.rb
  3. +32 −0 spec/chainable_compare_spec.rb
  4. +2 −0 spec/spec_helper.rb
@@ -0,0 +1,18 @@
+This provides a module which you can mix into any class to get chainable compare properties:
+
+ class String
+ include ChainablyComparable
+ end
+
+ def pick_line(name)
+ if "A" < name < "M"
+ "Line a"
+ else
+ "Line b"
+ end
+ end
+
+ puts pick_line("Yehuda")
+ puts pick_line("Evan")
+
+This works by overriding the <, >, <=, and >= operators on the class in question, as well as in FalseClass. I probably wouldn't override built-in classes this way without thinking pretty hard about the consequences.
@@ -0,0 +1,44 @@
+class ChainableCompare
+ def initialize(obj)
+ @obj = obj
+ end
+
+ %w(< > <= >=).each do |operator|
+ class_eval <<-RUBY, __FILE__, __LINE__ + 1
+ def #{operator}(other)
+ if @obj #{operator} other
+ ChainableCompare.new(other)
+ else
+ false
+ end
+ end
+ RUBY
+ end
+end
+
+module ChainablyComparable
+ def self.included(klass)
+ %w(< > <= >=).each do |operator|
+ klass.class_eval <<-RUBY, __FILE__, __LINE__ + 1
+ def #{operator}(other)
+ if super
+ ChainableCompare.new(other)
+ else
+ false
+ end
+ end
+ RUBY
+ end
+
+ end
+end
+
+class FalseClass
+ %w(< > <= >=).each do |operator|
+ class_eval <<-RUBY, __FILE__, __LINE__ + 1
+ def #{operator}(other)
+ false
+ end
+ RUBY
+ end
+end
@@ -0,0 +1,32 @@
+require "spec_helper"
+
+class Fixnum
+ include ChainablyComparable
+end
+
+describe "chainable compare" do
+ it "works for 1 < x < 5 when x is 3" do
+ x = 3
+ (1 < x < 5).should be_true
+ end
+
+ it "works for 1 < x < 5 when x is 0" do
+ x = 0
+ (1 < x < 5).should be_false
+ end
+
+ it "works for 1 < x < 5 when x is 6" do
+ x = 6
+ (1 < x < 5).should be_false
+ end
+
+ it "works for 10 > x <= 9 where x = 7" do
+ x = 7
+ (10 > x <= 9).should be_true
+ end
+
+ it "works for 10 > x <= 9 where x = 10" do
+ x = 10
+ (10 > x <= 9).should be_false
+ end
+end
@@ -0,0 +1,2 @@
+$:.push File.expand_path("../../lib")
+require "chainable_compare"

0 comments on commit 5358503

Please sign in to comment.