Skip to content

Commit 41b7adf

Browse files
committed
Add ImmutableStruct implementation
1 parent 08c2423 commit 41b7adf

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

lib/concurrent/synchronization.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,5 @@ class Object < Implementation
2727
end
2828
end
2929
end
30+
31+
require 'concurrent/synchronization/immutable_struct'
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
module Concurrent
2+
module Synchronization
3+
class ImmutableStruct < Synchronization::Object
4+
def self.with_fields(*names, &block)
5+
Class.new(self) do
6+
attr_reader(*names)
7+
instance_eval &block if block
8+
9+
class_eval <<-RUBY, __FILE__, __LINE__ + 1
10+
def initialize(#{names.join(', ')})
11+
#{names.map { |n| '@' + n.to_s }.join(', ')} = #{names.join(', ')}
12+
ensure_ivar_visibility!
13+
end
14+
RUBY
15+
end
16+
end
17+
18+
def self.[](*args)
19+
new *args
20+
end
21+
end
22+
end
23+
end

spec/concurrent/synchronized_object_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,5 +105,16 @@ def ns_initialize
105105
end
106106
end
107107

108+
describe Synchronization::ImmutableStruct do
109+
let(:klass) { described_class.with_fields(:a, :b) }
110+
subject { klass[1, 'a'] }
111+
112+
specify do
113+
expect(klass.superclass).to eq described_class
114+
expect(subject.a).to eq 1
115+
expect(subject.b).to eq 'a'
116+
end
117+
end
118+
108119
end
109120
end

0 commit comments

Comments
 (0)