From cf523a4834da2a4c5a975f5dc573ef221b596041 Mon Sep 17 00:00:00 2001 From: David Stosik Date: Thu, 5 Mar 2020 13:37:52 +0900 Subject: [PATCH] Fix bug where records can't be added to an originally empty ActiveJSON datastore Simple fix would be to replace `@records = nil` with `@records = []`, but the suggested approach as a better impact on the code base, avoiding repetitions such as `@records || []`. --- lib/active_hash/base.rb | 17 +++++++++++------ lib/enum/enum.rb | 2 +- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/lib/active_hash/base.rb b/lib/active_hash/base.rb index 5a14f980..cdede86a 100644 --- a/lib/active_hash/base.rb +++ b/lib/active_hash/base.rb @@ -109,7 +109,7 @@ def data def data=(array_of_hashes) mark_dirty - @records = nil + records.clear reset_record_index self._data = array_of_hashes if array_of_hashes @@ -127,13 +127,12 @@ def exists?(record) end def insert(record) - @records ||= [] record[:id] ||= next_id validate_unique_id(record) if dirty mark_dirty - add_to_record_index({ record.id.to_s => @records.length }) - @records << record + add_to_record_index({ record.id.to_s => records.length }) + records << record end def next_id @@ -145,6 +144,12 @@ def next_id end end + def records + @records ||= [] + end + + private :records + def record_index @record_index ||= {} end @@ -185,7 +190,7 @@ def create!(attributes = {}) end def all(options = {}) - ActiveHash::Relation.new(self, @records || [], options[:conditions] || {}) + ActiveHash::Relation.new(self, records, options[:conditions] || {}) end delegate :where, :find, :find_by, :find_by!, :find_by_id, :count, :pluck, :pick, :first, :last, :order, to: :all @@ -203,7 +208,7 @@ def transaction def delete_all mark_dirty reset_record_index - @records = [] + records.clear end def fields(*args) diff --git a/lib/enum/enum.rb b/lib/enum/enum.rb index c331f389..4001f026 100644 --- a/lib/enum/enum.rb +++ b/lib/enum/enum.rb @@ -21,7 +21,7 @@ def insert(record) def delete_all if @enum_accessors.present? - @records.each do |record| + records.each do |record| constant = constant_for(record, @enum_accessors) remove_const(constant) if const_defined?(constant, false) end