-
-
Save youz/9386661 to your computer and use it in GitHub Desktop.
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 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 |
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
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