Skip to content

Commit

Permalink
Merge pull request #76 from IlyaUmanets/raise_error_on_missing_method
Browse files Browse the repository at this point in the history
Raise NoMethodError if raise_on_missing option is enabled
  • Loading branch information
aetherknight authored May 28, 2024
2 parents 324b23c + 281566d commit 394b1eb
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,23 @@ ros = RecursiveOpenStruct.new(h, preserve_original_keys: true)
ros.to_h # => { 'fear' => 'is', 'the' => 'mindkiller' }
```

### Optional: Raise error on missing attribute

This option allows to raise an error if you try to call an attribute you didn't specify in hash

```ruby
h = { 'fear' => 'is', 'the' => 'mindkiller' } }
ros = RecursiveOpenStruct.new(h, raise_on_missing: true)
ros.undefined # => undefined method `undefined' for #<RecursiveOpenStruct fear="is", the="mindkiller">
```

The default behaviour returns nil

```ruby
h = { 'fear' => 'is', 'the' => 'mindkiller' } }
ros = RecursiveOpenStruct.new(h)
ros.undefined # => nil
```

## Installation

Expand Down
7 changes: 6 additions & 1 deletion lib/recursive_open_struct.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ def self.default_options
{
mutate_input_hash: false,
recurse_over_arrays: false,
preserve_original_keys: false
preserve_original_keys: false,
raise_on_missing: false
}
end

Expand Down Expand Up @@ -124,6 +125,10 @@ def method_missing(mid, *args)
if @table.key?(_get_key_from_table_(key))
new_ostruct_member!(key)
public_send(mid)
elsif @options[:raise_on_missing]
err = NoMethodError.new "undefined method `#{mid}' for #{self}", mid, args
err.set_backtrace caller(1)
raise err
end
else
err = NoMethodError.new "undefined method `#{mid}' for #{self}", mid, args
Expand Down
24 changes: 24 additions & 0 deletions spec/recursive_open_struct/indifferent_access_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,30 @@
end
end

context 'when undefined method' do
context 'when raise_on_missing is enabled' do
subject(:recursive) { RecursiveOpenStruct.new(recursive_hash, raise_on_missing: true) }
let(:recursive_hash) { {:foo => [ {'bar' => [ { 'foo' => :bar} ] } ] } }

specify 'raises NoMethodError' do
expect {
recursive.undefined_method
}.to raise_error(NoMethodError)
end
end

context 'when raise_on_missing is disabled' do
context 'preserves the original keys' do
subject(:recursive) { RecursiveOpenStruct.new(recursive_hash) }
let(:recursive_hash) { {:foo => [ {'bar' => [ { 'foo' => :bar} ] } ] } }

specify 'returns nil' do
expect(recursive.undefined_method).to be_nil
end
end
end
end

end

end
Expand Down

0 comments on commit 394b1eb

Please sign in to comment.