Skip to content

Commit 394b1eb

Browse files
authored
Merge pull request #76 from IlyaUmanets/raise_error_on_missing_method
Raise NoMethodError if raise_on_missing option is enabled
2 parents 324b23c + 281566d commit 394b1eb

File tree

3 files changed

+47
-1
lines changed

3 files changed

+47
-1
lines changed

Diff for: README.md

+17
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,23 @@ ros = RecursiveOpenStruct.new(h, preserve_original_keys: true)
6262
ros.to_h # => { 'fear' => 'is', 'the' => 'mindkiller' }
6363
```
6464

65+
### Optional: Raise error on missing attribute
66+
67+
This option allows to raise an error if you try to call an attribute you didn't specify in hash
68+
69+
```ruby
70+
h = { 'fear' => 'is', 'the' => 'mindkiller' } }
71+
ros = RecursiveOpenStruct.new(h, raise_on_missing: true)
72+
ros.undefined # => undefined method `undefined' for #<RecursiveOpenStruct fear="is", the="mindkiller">
73+
```
74+
75+
The default behaviour returns nil
76+
77+
```ruby
78+
h = { 'fear' => 'is', 'the' => 'mindkiller' } }
79+
ros = RecursiveOpenStruct.new(h)
80+
ros.undefined # => nil
81+
```
6582

6683
## Installation
6784

Diff for: lib/recursive_open_struct.rb

+6-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ def self.default_options
2323
{
2424
mutate_input_hash: false,
2525
recurse_over_arrays: false,
26-
preserve_original_keys: false
26+
preserve_original_keys: false,
27+
raise_on_missing: false
2728
}
2829
end
2930

@@ -124,6 +125,10 @@ def method_missing(mid, *args)
124125
if @table.key?(_get_key_from_table_(key))
125126
new_ostruct_member!(key)
126127
public_send(mid)
128+
elsif @options[:raise_on_missing]
129+
err = NoMethodError.new "undefined method `#{mid}' for #{self}", mid, args
130+
err.set_backtrace caller(1)
131+
raise err
127132
end
128133
else
129134
err = NoMethodError.new "undefined method `#{mid}' for #{self}", mid, args

Diff for: spec/recursive_open_struct/indifferent_access_spec.rb

+24
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,30 @@
160160
end
161161
end
162162

163+
context 'when undefined method' do
164+
context 'when raise_on_missing is enabled' do
165+
subject(:recursive) { RecursiveOpenStruct.new(recursive_hash, raise_on_missing: true) }
166+
let(:recursive_hash) { {:foo => [ {'bar' => [ { 'foo' => :bar} ] } ] } }
167+
168+
specify 'raises NoMethodError' do
169+
expect {
170+
recursive.undefined_method
171+
}.to raise_error(NoMethodError)
172+
end
173+
end
174+
175+
context 'when raise_on_missing is disabled' do
176+
context 'preserves the original keys' do
177+
subject(:recursive) { RecursiveOpenStruct.new(recursive_hash) }
178+
let(:recursive_hash) { {:foo => [ {'bar' => [ { 'foo' => :bar} ] } ] } }
179+
180+
specify 'returns nil' do
181+
expect(recursive.undefined_method).to be_nil
182+
end
183+
end
184+
end
185+
end
186+
163187
end
164188

165189
end

0 commit comments

Comments
 (0)