Skip to content

Instantly share code, notes, and snippets.

@youz
Forked from melborne/filter.rb
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save youz/9386661 to your computer and use it in GitHub Desktop.
Save youz/9386661 to your computer and use it in GitHub Desktop.
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 method.is_a?(Array)
method, *args = method
else
args = []
end
if custom = Filter.filters[method]
custom.call(mem, *args)
else
mem.send method, *args
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) || (other.is_a?(Array) && other[0].is_a?(Symbol))
Filter.new(self) | other
end
end
end
end
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, sign = "$"|
raise ArgumentError unless int.is_a?(Numeric)
"#{sign}%.2f" % int
end
puts 123.45 * 3 | :currency
# >> $370.35
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment