lib/jsonapi/formatter.rb in jsonapi-resources-0.7.1.beta1 vs lib/jsonapi/formatter.rb in jsonapi-resources-0.7.1.beta2
- old
+ new
@@ -7,13 +7,16 @@
def unformat(arg)
arg
end
+ def cached
+ return FormatterWrapperCache.new(self)
+ end
+
def formatter_for(format)
- formatter_class_name = "#{format.to_s.camelize}Formatter"
- formatter_class_name.safe_constantize
+ "#{format.to_s.camelize}Formatter".safe_constantize
end
end
end
class KeyFormatter < Formatter
@@ -49,12 +52,34 @@
def unformat(value)
super(value)
end
def value_formatter_for(type)
- formatter_name = "#{type.to_s.camelize}Value"
- formatter_for(formatter_name)
+ "#{type.to_s.camelize}ValueFormatter".safe_constantize
end
+ end
+ end
+
+ # Warning: Not thread-safe. Wrap in ThreadLocalVar as needed.
+ class FormatterWrapperCache
+ attr_reader :formatter_klass
+
+ def initialize(formatter_klass)
+ @formatter_klass = formatter_klass
+ @format_cache = NaiveCache.new{|arg| formatter_klass.format(arg) }
+ @unformat_cache = NaiveCache.new{|arg| formatter_klass.unformat(arg) }
+ end
+
+ def format(arg)
+ @format_cache.get(arg)
+ end
+
+ def unformat(arg)
+ @unformat_cache.get(arg)
+ end
+
+ def cached
+ self
end
end
end
class UnderscoredKeyFormatter < JSONAPI::KeyFormatter