简体   繁体   中英

Metaprogramming with ruby, operator overloading and instance_eval

For example i've class like :

class QueryDSL
  def initialize(&block)
    instance_eval &block
  end

  def ==(value)
    "bla bla '#{value}'"
  end

  def test(param)
    param + param
  end
end

and class Query like :

class Query
  def self.where(&block)
    QueryDSL.new(&block)
  end
end

I suspect when execute :

Query.where{test == 9}

the output should be :

"bla bla 9 bla bla 9"

But i've got exception like :

`test': wrong number of arguments (0 for 1) (ArgumentError)

Is there any mistake from my code ? Thanks

Your problem is that you're calling the QueryDSL#test method with no arguments when it is defined to take one argument, hence the

`test': wrong number of arguments (0 for 1) (ArgumentError)

error.

Either change the test method to not take arguments or to have a default for param or supply the argument in your block:

Query.where { test(6) == 9 }

That still won't call your == operator though, test doesn't return a QueryDSL instance so the == operator for whatever it does return will be used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM