diff --git a/lib/active_hash/base.rb b/lib/active_hash/base.rb index b326fd1c..1b7bed91 100644 --- a/lib/active_hash/base.rb +++ b/lib/active_hash/base.rb @@ -116,9 +116,7 @@ def data end def data=(array_of_hashes) - mark_dirty - @records = nil - reset_record_index + delete_all self._data = array_of_hashes if array_of_hashes auto_assign_fields(array_of_hashes) @@ -135,13 +133,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 +150,12 @@ def next_id end end + def records + @records ||= [] + end + + private :records + def record_index @record_index ||= {} end @@ -193,7 +196,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 +214,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 diff --git a/spec/active_json/base_spec.rb b/spec/active_json/base_spec.rb index 236ba66b..4c5ace25 100644 --- a/spec/active_json/base_spec.rb +++ b/spec/active_json/base_spec.rb @@ -23,7 +23,7 @@ class Empty < ActiveJSON::Base ; end # Empty JSON expect(State.first.name).to match(/^New York/) end - it 'can load empty yaml' do + it 'can load empty JSON' do expect(Empty.first).to be_nil end end @@ -46,6 +46,12 @@ class Empty < ActiveJSON::Base ; end # Empty JSON end end + describe ".create" do + it "does not fail when the loaded JSON was empty" do + Empty.create() + end + end + describe ".delete_all" do context "when called before .all" do it "causes all to not load data" do