Skip to content

Commit

Permalink
Memoize instances of typcasters in typecaster map
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
film42 committed Feb 8, 2016
1 parent 265346f commit f4ccaa1
Showing 1 changed file with 11 additions and 11 deletions.
22 changes: 11 additions & 11 deletions lib/active_attr/typecasting.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -51,16 +51,16 @@ def typecast_attribute(typecaster, value)
typecaster.call(value)
end

# Resolve a Class to a typecaster
# Resolve an Instance to a typecaster
#
# @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 if typecaster
end
end
end

0 comments on commit f4ccaa1

Please sign in to comment.