Fix "no id given" message in method_missing

The following Ruby code throws the "no id given" error shown at the end. How can 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>'

      

+3


source to share


1 answer


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 occurs when you call super

internally method_missing

after changing the value of the first parameter to something other than a symbol. Fix it? Do not do this. For example, the method from the original question could 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

      

Also, don't forget to explicitly pass the character as the first parameter super

:

def method_missing(property,*args)
  property = property.to_s
  # ...
  if @asset.respond_to?(property)
    # ...
  else
    super( property.to_sym, *args )
  end
end

      

+3


source







All Articles