Skip to content

Commit

Permalink
Merge pull request #75 from Richard-Degenne/fix/ruby-3.1-freeze
Browse files Browse the repository at this point in the history
Fix Ruby 3.1 #freeze
  • Loading branch information
aetherknight authored Jun 19, 2024
2 parents 280d4eb + 8ad69f6 commit adc698c
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/recursive_open_struct.rb
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,14 @@ def method_missing(mid, *args)
end
end

def freeze
@table.each_key do |key|
new_ostruct_member!(key)
end

super
end

# TODO: Rename to new_ostruct_member! once we care less about Rubies before
# 2.4.0.
def new_ostruct_member(name)
Expand Down
36 changes: 36 additions & 0 deletions spec/recursive_open_struct/open_struct_behavior_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -108,5 +108,41 @@
it { expect(subject.methods.map(&:to_sym)).to_not include :asdf= }
end # describe #methods
end # describe handling of arbitrary attributes

describe "handling of freezing" do
let(:hash) { { :asdf => 'John Smith' } }

before do
ros.freeze
end

it "can read existing keys" do
expect(ros.asdf).to eq 'John Smith'
end

it "cannot write new keys" do
expect { ros.new_key = 'new_value' }.to raise_error FrozenError
end

it "cannot write existing keys" do
expect { ros.asdf = 'new_value' }.to raise_error FrozenError
end

context "with recursive structure" do
let(:hash) { { :key => { :subkey => 42 } } }

it "can read existing sub-elements" do
expect(ros.key.subkey).to eq 42
end

it "can write new sub-elements" do
expect { ros.key.new_subkey = 43 }.not_to raise_error
end

it "can write existing sub-elements" do
expect { ros.key.subkey = 43 }.not_to raise_error
end
end
end
end # describe behavior it inherits from OpenStruct
end

0 comments on commit adc698c

Please sign in to comment.