From: marcandre-ruby-core@... Date: 2020-09-26T06:56:30+00:00 Subject: [ruby-core:100164] [Ruby master Feature#15815] Add option to raise NoMethodError for OpenStruct Issue #15815 has been updated by marcandre (Marc-Andre Lafortune). I'm proposing to add `OpenStruct::Strict`, that will not return `nil` for unknown attributes and instead raise a `NotMethodError`. See PR https://github.com/ruby/ruby/pull/3594 (last commit) Usage with `JSON` is easy: ```ruby JSON.parse(response, object_class: OpenStruct::Strict) ``` This seems to me to avoid issues that other solutions had: * Any other solutions is difficult to use with `JSON.parse` API * I considered adding `OpenStruct#strict!` (returning `self` after mutating it), seems the 2nd best option. * `OpenStruct.new({...}, exception: true)` made it difficult to remain compatible with `OpenStruct.new(using: 'keyword arguments')`. Also seemed confusing API. * `OpenStruct.new(...) { block to handle unknown attribute }` was longer to write, and potentially less/not Ractor compatible, and not serializable in general. The downside to `OpenStruct::Strict` is that it makes adding any other configuration more difficult. Given the fact that `OpenStruct` is to mature now though, I feel it is not an actual issue. Anyone wanting to subclass has to pick a base class (or define it's own `respond_to_unknown_attribute!`). Comments welcome. ---------------------------------------- Feature #15815: Add option to raise NoMethodError for OpenStruct https://bugs.ruby-lang.org/issues/15815#change-87735 * Author: mtsmfm (Fumiaki Matsushima) * Status: Open * Priority: Normal * Assignee: marcandre (Marc-Andre Lafortune) ---------------------------------------- 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: