Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fix "no id given" message in method_missing

Tags:

ruby

The following Ruby code raises the confusing error "no id given" shown at the end. How do I avoid this problem?

class Asset; end

class Proxy < Asset
  def initialize(asset)
    @asset
  end
  def method_missing(property,*args)
    property = property.to_s
    property.sub!(/=$/,'') if property.end_with?('=')
    if @asset.respond_to?(property)
      # irrelevant code here
    else
      super
    end
  end
end

Proxy.new(42).foobar
#=> /Users/phrogz/test.rb:13:in `method_missing': no id given (ArgumentError)
#=>   from /Users/phrogz/test.rb:13:in `method_missing'
#=>   from /Users/phrogz/test.rb:19:in `<main>'
like image 876
Phrogz Avatar asked Jun 23 '26 12:06

Phrogz


1 Answers

The core of this problem can be shown with this simple test:

def method_missing(a,*b)
  a = 17
  super
end

foobar #=> `method_missing': no id given (ArgumentError)

This error arises when you call super inside method_missing after changing the value of the first parameter to something other than a symbol. The fix? Don't do that. For example, the method from the original question can be rewritten as:

def method_missing(property,*args)
  name = property.to_s
  name.sub!(/=$/,'') if name.end_with?('=')
  if @asset.respond_to?(name)
    # irrelevant code here
  else
    super
  end
end

Alternatively, be sure to explicitly pass a symbol as the first parameter to super:

def method_missing(property,*args)
  property = property.to_s
  # ...
  if @asset.respond_to?(property)
    # ...
  else
    super( property.to_sym, *args )
  end
end
like image 99
Phrogz Avatar answered Jun 26 '26 02:06

Phrogz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!