ruby-core

Mailing list archive

[ruby-core:64716] [ruby-trunk - Bug #10194] OpenStruct does not throw an exception when calling missing method with no arguments.

From: andrew@...
Date: 2014-09-02 20:39:07 UTC
List: ruby-core #64716
Issue #10194 has been updated by Andrew Vit.


The design of OpenStruct is to allow all method calls. (It is similar to a Hash but with method access.)

You can use a regular Struct if you need strict properties, or something from the Hashie gem might do what you're looking for.

----------------------------------------
Bug #10194: OpenStruct does not throw an exception when calling missing method with no arguments.
https://bugs.ruby-lang.org/issues/10194#change-48609

* Author: Alex Pogrebnyak
* Status: Rejected
* Priority: Normal
* Assignee: 
* Category: lib
* Target version: 
* ruby -v: ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-linux]
* Backport: 2.0.0: UNKNOWN, 2.1: UNKNOWN
----------------------------------------
Below is the sample that shows the problem:
    #!/usr/bin/env ruby
    
    require 'ostruct'
    
    class TestMethodMissing < OpenStruct
      def initialize ()
    
        super(
          { "foo" => "bar" }
        )
    
      end
    
    
      def main()
    
        self.no_such_method
    
        puts "BUG! Should fail on the previous line"
      end
    
    end
    
    TestMethodMissing.new( ).main( )


I expect when calling `self.no_such_method` to generate an error.

The error can be traced to `ostruct.rb` `method_missing` implementation

Here is the dump of the method with `>>` showing the trouble line:

    def method_missing(mid, *args) # :nodoc:
      mname = mid.id2name
      len = args.length
      if mname.chomp!('=')
        if len != 1
          raise ArgumentError, "wrong number of arguments (#{len} for 1)", caller(1)
        end
        modifiable[new_ostruct_member(mname)] = args[0]
      elsif len == 0
    >>    @table[mid]
      else
         err = NoMethodError.new "undefined method `#{mid}' for #{self}", mid, args
        err.set_backtrace caller(1)
        raise err
      end
    end


There should be a check that `@table[mid]` does not return `nil`, and in case of `nil` raise an error







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

In This Thread

Prev Next