From: shevegen@...
Date: 2019-05-01T17:47:57+00:00
Subject: [ruby-core:92519] [Ruby trunk Feature#15815] Add option to raise NoMethodError for OpenStruct

Issue #15815 has been updated by shevegen (Robert A. Heiler).


> Note that you might be able to write users.map{@[:id]} in the next version and
> avoid using an OpenStruct altogether.

I think that the idiom, or "mental mode", e. g. how users use ruby, is a bit different
between the two examples. At the least to me, "OpenStruct" is instantly recognizable
and "exception: true" is also no longer a rare idiom, after some core methods accepted
it; the map {@[:id] variant, at the least to me, is slightly harder to understand for
my brain. But anyway, that's just my opinion - to the suggestion itself, one described
use case:

> But I want to prevent typo for a key name. 

Although I personally do not use struct and openstruct a lot, even though I think it is
a cool idea (prototypical objects all the way, at all times), to me the suggestion appears
useful. So I am in light support of the suggestion; I don't feel particularly strong
either way, though. (May help for people to comment who actually use struct and openstruct
a lot.)

----------------------------------------
Feature #15815: Add option to raise NoMethodError for OpenStruct
https://bugs.ruby-lang.org/issues/15815#change-77883

* Author: mtsmfm (Fumiaki Matsushima)
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 
----------------------------------------
GitHub PR: https://github.com/ruby/ruby/pull/2164

Currently, `OpenStruct#method_missing` returns `nil` even if the key isn't registered.

```ruby
require 'ostruct'
os = OpenStruct.new({a: 1})
os.a #=> 1
os.b #=> nil
```

I'd like to add `exception` option to raise `NoMethodError` in such case.

```ruby
require 'ostruct'
os = OpenStruct.new({a: 1}, exception: true)
os.a #=> 1
os.b #=> NoMethodError
```

## Use case

I sometimes use OpenStruct as a JSON API response wrapper.
It's useful to use method call instead of key access (`obj[:key]`) because we can use `Symbol#to_proc` if it's a method (for example `users.map(&:id)`)

But I want to prevent typo for a key name. Currently `users.map(&:idd)` just returns `[nil,...]`

Even if we have this `exception` option, we can't enable this option for JSON parser easily though:

```ruby
JSON.parse(response, object_class: Class.new(OpenStruct) { def initialize(hash); super(hash, exception: true); end })
```

What do you think?

----

I've searched with "openstruct nomethoderror" on bugs.ruby-lang.org though, please let me know if it's duplicated.
https://bugs.ruby-lang.org/search?utf8=%E2%9C%93&scope=&q=nomethoderror+openstruct



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>