Serge
Serge

Reputation: 12354

how to prevent ruby from defining variables

I'd like a user to input a conditional expression interactively, something like f1 == 'b' || f2 == 'd' where f1 and f2 are ruby functions. eval condition works ok. However, I'd like to prevent errors like f3 = 'c' where f3 is not defined in ruby. Ruby silently defines a local variable. I'd like to capture an error instead.

So, is there a way to prevent ruby from creating local variables or a way to capture a creation event?

Example:

#!/usr/bin/ruby

class Conditions
    def f1
        "a"
    end

    def f2
        "b"
    end

    def evalCondition(cond)
        begin
            eval cond
        rescue => ex
            puts ex
        end
    end
end


def evalCondition(cond)
    conds = Conditions.new
    conds.evalCondition(cond)
end


puts evalCondition("f1 == 'x'")
puts evalCondition("f1 == 'a' || f2 == 'b'")
puts evalCondition("f3 = 'y'")

I'd like to catch the last one as an error.

Upvotes: 0

Views: 72

Answers (1)

Cassiano Franco
Cassiano Franco

Reputation: 410

I found a way to check if some local variables is created, but you need bind a context in the eval

class Context
  def f1
    return 'a'
  end

  def f2
    return 'b'
  end

  def get_binding
    binding
  end
end

context = Context.new
bind = context.get_binding

eval("a = f1 == 'b' || f2 == 'b'", bind)
variables = eval('self.local_variables', bind)

throw "undefined variables: " + variables.join(' ') if (variables.size)

Upvotes: 1

Related Questions