From 361ca56b22716a371ad35d6b40f0ad1e2ec1b41a 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 b326fd1c..fdcbf569 100644 --- a/lib/active_hash/base.rb +++ b/lib/active_hash/base.rb @@ -117,7 +117,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 @@ -135,13 +135,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 @@ -153,6 +152,12 @@ def next_id end end + def records + @records ||= [] + end + + private :records + def record_index @record_index ||= {} end @@ -193,7 +198,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 @@ -211,7 +216,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