Search code examples
rubymethod-missing

Ruby -- force method_missing *args to be hash?


I want to define a method_missing function for one of my classes, and I want to be able to pass in a hash as the argument list instead of an array. Like this:

MyClass::get_by_id {:id => id}
MyClass::get_by_id {:id => id, :filters => filters}
MyClass::get_by_id {:id => id, :filters => filters, :sort => sort}

As far as I can tell, the args list gets passed in as an array, so keys get dropped and there's no way to tell which arguments is which. Is there a way to force Ruby to treat the argument list in method_missing as a hash?


Solution

  • What issue are you having? This works for me:

    class MyClass
      def self.method_missing name, args
        puts args.class
        puts args.inspect
      end
    end
    
    MyClass.foobar :id => 5, :filter => "bar"
    # Hash
    # {:id=>5, :filter=>"bar"}