From ffcc994a986e5719db19ffafc0b3f3c07fffe77e Mon Sep 17 00:00:00 2001 From: Aaron Lasseigne Date: Mon, 7 Apr 2014 11:47:50 -0500 Subject: [PATCH] make filter column objects flyweight --- lib/active_interaction/base.rb | 2 +- lib/active_interaction/filter_column.rb | 14 ++++++++++++++ spec/active_interaction/filter_column_spec.rb | 18 +++++++++++++++++- 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/lib/active_interaction/base.rb b/lib/active_interaction/base.rb index a368d163..e397b839 100644 --- a/lib/active_interaction/base.rb +++ b/lib/active_interaction/base.rb @@ -166,7 +166,7 @@ def initialize(inputs = {}) def column_for_attribute(name) filter = self.class.filters[name] - FilterColumn.new(filter.database_column_type) if filter + FilterColumn.intern(filter.database_column_type) if filter end # @!method compose(other, inputs = {}) diff --git a/lib/active_interaction/filter_column.rb b/lib/active_interaction/filter_column.rb index e267735a..27658e7d 100644 --- a/lib/active_interaction/filter_column.rb +++ b/lib/active_interaction/filter_column.rb @@ -5,6 +5,20 @@ module ActiveInteraction class FilterColumn attr_reader :limit, :type + class << self + def intern(type) + @columns ||= {} + + if @columns[type] + @columns.fetch(type) + else + @columns[type] = new(type) + end + end + + private :new + end + def initialize(type) @type = type end diff --git a/spec/active_interaction/filter_column_spec.rb b/spec/active_interaction/filter_column_spec.rb index fb85eebe..e674b462 100644 --- a/spec/active_interaction/filter_column_spec.rb +++ b/spec/active_interaction/filter_column_spec.rb @@ -4,7 +4,23 @@ describe ActiveInteraction::FilterColumn do let(:type) { :float } - subject(:column) { described_class.new(type) } + subject(:column) { described_class.intern(type) } + + describe '.intern(type)' do + it 'returns the same object for each type' do + expect(described_class.intern(type)).to equal column + end + + it 'returns different objects for different types' do + expect(described_class.intern(:integer)).to_not equal column + end + end + + describe '.new(type)' do + it 'is private' do + expect { described_class.new(type) }.to raise_error NoMethodError + end + end describe '#limit' do it 'returns nil' do