Frage

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?

War es hilfreich?

Lösung

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"}

Andere Tipps

Is this what you are looking for ?

class Foo
    def self.method_missing(name,*args)
        p args
        p name
    end
end

Foo.bar(1,2,3) 
# >> [1, 2, 3]
# >> :bar

I'm answering my own question based on experimentation that I've done since asking. When using a hash splat on the arg list, you can pass in a hash like this:

MyClass::get_by_id(:id => id, :filters => filters)

And the argument list will look like this:

[
  {
    :id => id,
    :filters => filters
  }
]

Ruby places the key/value pairs into a single hash object at location args[0]. If you call the method like this:

MyClass::get_by_id(id, :filters => filters)

Your argument list will be this:

[
  id,
  {:filters => filters}
]

So basically, key/value pairs are merged together into a single hash and passed in order.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top