-
-
Save thillain/1800201 to your computer and use it in GitHub Desktop.
This file contains 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 'active_support/inflector' | |
require 'benchmark' | |
# QUICK HACK | |
class RuleSet | |
def initialize | |
@rules = [] | |
@regexp = nil | |
end | |
def prepend_rule(pattern, replacement) | |
@rules.unshift([pattern, replacement]) | |
patterns = @rules.each_with_index.map {|rule, i| build_regexp(rule.first, i)} | |
@regexp = Regexp.union(*patterns) | |
end | |
def build_regexp(pattern, i) | |
pattern = Regexp.quote(pattern) if pattern.is_a?(String) | |
/(?<_#{i}>#{pattern})/ | |
end | |
def apply(word) | |
word = word.to_s.dup | |
if md = @regexp.match(word) | |
name = md.names.detect {|n| md[n]} | |
index = name[/\d+/, 0].to_i | |
word.gsub!(@rules[index][0], @rules[index][1]) | |
end | |
word | |
end | |
end | |
rs = RuleSet.new | |
ActiveSupport::Inflector::Inflections.instance.plurals.each do |pattern, replacement| | |
rs.prepend_rule(pattern, replacement) | |
end | |
Benchmark.bmbm do |x| | |
x.report('AS') { 10000.times { %w(user post person).each {|word| ActiveSupport::Inflector.pluralize(word) }}} | |
x.report('RS') { 10000.times { %w(user post person).each {|word| rs.apply(word)}}} | |
end | |
__END__ | |
Rehearsal -------------------------------------- | |
AS 5.310000 0.010000 5.320000 ( 5.323167) | |
RS 1.100000 0.000000 1.100000 ( 1.096796) | |
----------------------------- total: 6.420000sec | |
user system total real | |
AS 5.500000 0.010000 5.510000 ( 5.545606) | |
RS 1.150000 0.000000 1.150000 ( 1.156264) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment