RyanScottLewis
RyanScottLewis

Reputation: 14016

method_missing Within instance_eval

Full code: http://friendpaste.com/5TdtGPZaEK0DbDBa2DCUyB

class Options
    def method_missing(method, *args, &block)
        p method
    end
end

options = Options.new

options.instance_eval do
    foo
    foo = "It aint easy being cheesy!"
end

puts "#===---"
options.foo
options.foo = "It still aint easy being cheesy!"

This returns:

:foo
#===---
:foo
:foo=

Because it is treating foo = "" as a local variable within instance_eval, it's not recognize it as a method.

How would I make instance_eval treat it as a method?

Upvotes: 2

Views: 396

Answers (2)

Chuck
Chuck

Reputation: 237010

The expression foo = "" will never be a method call. It is a local variable assignment. This is a fact of Ruby's syntax. In order to call a setter, you have to specify a receiver explicitly. This is why most Ruby pseudo-DSLs use the Dwemthy-style:

class Dragon < Creature
  life 1340     # tough scales
  strength 451  # bristling veins
  charisma 1020 # toothy smile
  weapon 939    # fire breath
end

That avoids the equals sign problem.

Upvotes: 5

mckeed
mckeed

Reputation: 9818

Do self.foo = "" to make it treat it as a method.

Upvotes: 2

Related Questions