Last active
August 29, 2015 13:57
Revisions
-
melborne revised this gist
Mar 5, 2014 . 1 changed file with 29 additions and 0 deletions.There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,29 @@ require './filter' using CoreExt puts 'hello' | :upcase # >> HELLO puts 123 | :next # >> 124 puts 'Mississippi' | :upcase | :squeeze | :chars | :reverse # >> ["I", "P", "I", "S", "I", "S", "I", "M"] puts 123 | :next | :even? # >> true Filter.add :currency do |int| raise ArgumentError unless int.is_a?(Numeric) "$%.2f" % int end puts 123.45 * 3 | :currency # >> $370.35 Filter.add :titleize do |str| str.scan(/\w+/).map(&:capitalize)*' ' end puts 'ruby on rails' | :titleize # >> Ruby On Rails -
melborne created this gist
Mar 5, 2014 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,46 @@ class Filter class << self def filters @filters ||= {} end def add(name, &code) filters[name] = code end end def initialize(obj) @methods = [] @obj = obj end def |(method) @methods << method self end def run @methods.inject(@obj) do |mem, method| if custom = Filter.filters[method] custom.call(mem) else mem.send method end end end def to_s run.to_s end end module CoreExt [Fixnum, Float, String].each do |klass| refine klass do def |(other) return super unless other.is_a?(Symbol) Filter.new(self) | other end end end end