Commit ec3ffdd1 by Jon Yurek

Cache pluralizations in interpolations for speed

parent 0d4bf12d
......@@ -35,6 +35,7 @@ require 'paperclip/geometry'
require 'paperclip/processor'
require 'paperclip/tempfile'
require 'paperclip/thumbnail'
require 'paperclip/interpolations/plural_cache'
require 'paperclip/interpolations'
require 'paperclip/tempfile_factory'
require 'paperclip/style'
......
......@@ -36,6 +36,10 @@ module Paperclip
end
end
def self.plural_cache
@plural_cache ||= PluralCache.new
end
# Returns the filename, the same way as ":basename.:extension" would.
def filename attachment, style_name
[ basename(attachment, style_name), extension(attachment, style_name) ].reject(&:blank?).join(".")
......@@ -81,7 +85,7 @@ module Paperclip
# all class names. Calling #class will return the expected class.
def class attachment = nil, style_name = nil
return super() if attachment.nil? && style_name.nil?
attachment.instance.class.to_s.underscore.pluralize
plural_cache.underscore_and_pluralize(attachment.instance.class.to_s)
end
# Returns the basename of the file. e.g. "file" for "file.jpg"
......@@ -169,7 +173,7 @@ module Paperclip
# Returns the pluralized form of the attachment name. e.g.
# "avatars" for an attachment of :avatar
def attachment attachment, style_name
attachment.name.to_s.downcase.pluralize
plural_cache.pluralize(attachment.name.to_s.downcase)
end
# Returns the style, or the default style if nil is supplied.
......
module Paperclip
module Interpolations
class PluralCache
def initialize
@cache = {}
end
def pluralize(word)
@cache[word] ||= word.pluralize
end
def underscore_and_pluralize(word)
@cache[word] ||= word.underscore.pluralize
end
end
end
end
require './test/helper'
class PluralCacheTest < Test::Unit::TestCase
should 'cache pluralizations' do
cache = Paperclip::Interpolations::PluralCache.new
word = "box"
word.expects(:pluralize).returns("boxes").once
cache.pluralize(word)
cache.pluralize(word)
end
should 'cache pluralizations and underscores' do
cache = Paperclip::Interpolations::PluralCache.new
word = "BigBox"
word.expects(:pluralize).returns(word).once
word.expects(:underscore).returns(word).once
cache.underscore_and_pluralize(word)
cache.underscore_and_pluralize(word)
end
should 'pluralize words' do
cache = Paperclip::Interpolations::PluralCache.new
word = "box"
assert_equal "boxes", cache.pluralize(word)
end
should 'pluralize and underscore words' do
cache = Paperclip::Interpolations::PluralCache.new
word = "BigBox"
assert_equal "big_boxes", cache.underscore_and_pluralize(word)
end
end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment