Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add thread safety to ActiveFile #229

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions lib/active_file/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ module ActiveFile

class Base < ActiveHash::Base
extend ActiveFile::MultipleFiles
@@instance_lock = Mutex.new

class_attribute :filename, :root_path, :data_loaded, instance_reader: false, instance_writer: false

Expand All @@ -13,10 +14,12 @@ def delete_all
end

def reload(force = false)
return if !self.dirty && !force && self.data_loaded
self.data_loaded = true
self.data = load_file
mark_clean
@@instance_lock.synchronize do
return if !self.dirty && !force && self.data_loaded
self.data = load_file
mark_clean
self.data_loaded = true
end
end

def set_filename(name)
Expand Down Expand Up @@ -53,6 +56,10 @@ def actual_root_path
end
end

def all_in_process
return super if data_loaded
@records || []
end
end
end

Expand Down
7 changes: 6 additions & 1 deletion lib/active_hash/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -145,14 +145,19 @@ def insert(record)
end

def next_id
max_record = all.max { |a, b| a.id <=> b.id }
max_record = all_in_process.max { |a, b| a.id <=> b.id }
if max_record.nil?
1
elsif max_record.id.is_a?(Numeric)
max_record.id.succ
end
end

def all_in_process
all
end
private :all_in_process

def record_index
@record_index ||= {}
end
Expand Down
6 changes: 6 additions & 0 deletions spec/active_yaml/base_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@ class Empty < ActiveYaml::Base ; end # Empty YAML
it 'can load empty yaml' do
expect(Empty.first).to be_nil
end

it 'is thread-safe' do
(1..5).map do
Thread.new { expect(City.count).to eq(2) }
end.each(&:join)
end
end

describe ".all" do
Expand Down