Project

General

Profile

Actions

Feature #15815

open

Add option to raise NoMethodError for OpenStruct

Added by mtsmfm (Fumiaki Matsushima) over 5 years ago. Updated 8 months ago.

Status:
Assigned
Target version:
-
[ruby-core:92513]

Description

GitHub PR: https://github.com/ruby/ruby/pull/2164

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

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.

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:

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

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0