From bbf20e7e18c3317625d7dd08e9f92abbee197e4f Mon Sep 17 00:00:00 2001 From: Garrett Thornburg Date: Mon, 8 Feb 2016 10:10:26 -0700 Subject: [PATCH] Memoize instances of typcasters in typecaster map All of the default typecasters are stateless by default, so allocating a new instance for each field becomes extremely costly, especially for larger models. To reduce this, we memoize instances by default, but still allow users to provide a custom stateful type. --- lib/active_attr/typecasting.rb | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/lib/active_attr/typecasting.rb b/lib/active_attr/typecasting.rb index 9c09f44..a969308 100644 --- a/lib/active_attr/typecasting.rb +++ b/lib/active_attr/typecasting.rb @@ -26,14 +26,14 @@ module ActiveAttr module Typecasting # @private TYPECASTER_MAP = { - BigDecimal => BigDecimalTypecaster, - Boolean => BooleanTypecaster, - Date => DateTypecaster, - DateTime => DateTimeTypecaster, - Float => FloatTypecaster, - Integer => IntegerTypecaster, - Object => ObjectTypecaster, - String => StringTypecaster, + BigDecimal => BigDecimalTypecaster.new, + Boolean => BooleanTypecaster.new, + Date => DateTypecaster.new, + DateTime => DateTimeTypecaster.new, + Float => FloatTypecaster.new, + Integer => IntegerTypecaster.new, + Object => ObjectTypecaster.new, + String => StringTypecaster.new, }.freeze # Typecasts a value using a Class @@ -51,16 +51,15 @@ def typecast_attribute(typecaster, value) typecaster.call(value) end - # Resolve a Class to a typecaster + # Resolve an Class to a typecaster Instance # # @param [Class] type The type to cast to # - # @return [#call, nil] The typecaster to use + # @return [#call, nil] The typecaster instance to use # # @since 0.6.0 def typecaster_for(type) - typecaster = TYPECASTER_MAP[type] - typecaster.new if typecaster + TYPECASTER_MAP[type] end end end