Pablo Castellazzi
Pablo Castellazzi

Reputation: 4184

How to overwrite defined? operator?

if you have something like:

module Real
  A = 1
end

when you do defined?(Real::A) you get 'constant' which is a truish value. Now if i do something like:

module Virtual
  def self.constants
    [:A] + super
  end
  def self.const_missing(sym)
    return 1 if sym == :A
    super
  end
  def self.const_defined?(sym)
    return true if sym == :A
    super
  end
end

defined?(Virtual::A) return nil. Is there some way to overwrite defined? behaviour to take metaprogrammed constants into acccount?

Upvotes: 3

Views: 82

Answers (1)

Dominik Honnef
Dominik Honnef

Reputation: 18430

defined? is actually an operator (and not just syntactic sugar like +) and as such cannot be redefined. The proper solution would be to not use defined? for checking but aforementioned const_defined?. defined? isn't intended for meta-programming and works on the parser level, which is why it can give rather detailed information on the type of expression.

Upvotes: 3

Related Questions