From 707dcc6ae50cfdd21c78946c4bb56c97c264af79 Mon Sep 17 00:00:00 2001 From: Alexander Momchilov Date: Fri, 26 Mar 2021 14:27:34 -0400 Subject: [PATCH 1/2] Add constant time `PropertyCollection#count` And `#size` and `#length` to match `Hash`. Since I added `Forwardable` anyway, we can use it to replace the manual definition of `#values` --- lib/smart_properties/property_collection.rb | 15 ++++++++++----- spec/property_collection_caching_spec.rb | 10 ++++++++++ 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/lib/smart_properties/property_collection.rb b/lib/smart_properties/property_collection.rb index a60e3a0..4537f6a 100644 --- a/lib/smart_properties/property_collection.rb +++ b/lib/smart_properties/property_collection.rb @@ -1,6 +1,9 @@ +require 'forwardable' + module SmartProperties class PropertyCollection include Enumerable + extend Forwardable attr_reader :parent @@ -45,17 +48,17 @@ def keys collection_with_parent_collection.keys.map(&:to_sym) end - def values - collection_with_parent_collection.values - end - def each(&block) return to_enum(:each) if block.nil? collection_with_parent_collection.each { |name, value| block.call([name.to_sym, value]) } end + def to_h + each.to_h + end + def to_hash - Hash[each.to_a] + to_h end def register(child) @@ -64,6 +67,8 @@ def register(child) nil end + def_delegators :collection_with_parent_collection, :count, :size, :length, :values + protected attr_accessor :children diff --git a/spec/property_collection_caching_spec.rb b/spec/property_collection_caching_spec.rb index 50e219c..5197757 100644 --- a/spec/property_collection_caching_spec.rb +++ b/spec/property_collection_caching_spec.rb @@ -36,4 +36,14 @@ expect(base_class.new).to have_smart_property(:title) end.not_to raise_error(SystemStackError) end + + specify "PropertyCollection has O(1) #count" do + property_collection = Class.new(SmartProperties::PropertyCollection) do + def collection_with_parent_collection + mock('collection').expects(:count).once.returns(42) + end + end + + expect(property_collection.new.count).to eq(42) + end end From b4ecfd55dbf4f0fe1466961c97fefbe50081a080 Mon Sep 17 00:00:00 2001 From: Alexander Momchilov Date: Fri, 26 Mar 2021 15:08:19 -0400 Subject: [PATCH 2/2] Rename to property_collection_spec Now it tests more than just caching. --- ...rty_collection_caching_spec.rb => property_collection_spec.rb} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename spec/{property_collection_caching_spec.rb => property_collection_spec.rb} (100%) diff --git a/spec/property_collection_caching_spec.rb b/spec/property_collection_spec.rb similarity index 100% rename from spec/property_collection_caching_spec.rb rename to spec/property_collection_spec.rb