Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails/Ruby incorrectly showing variable not defined

In debugging console, while app running (using binding.pry to interrupt it), I can see that my variable Rails.configuration.hardcoded_current_user_key is set:

pry(#<TasksController>)> Rails.configuration.hardcoded_current_user_key
=> "dev"

But it doesn't appear to be defined:

pry(#<TasksController>)> defined?(Rails.configuration.hardcoded_current_user_key)
=> nil

Yet it works fine to store and test its value:

pry(#<TasksController>)> tempVar = Rails.configuration.hardcoded_current_user_key
=> "dev"
pry(#<TasksController>)> defined?(tempVar)
=> "local-variable"

What is going on?

like image 512
Ben Wheeler Avatar asked Jul 18 '26 23:07

Ben Wheeler


1 Answers

This is because Rails config implements respond_to? but not respond_to_missing?, and defined? only recognizes respond_to_missing?:

class X
  def respond_to?(name, include_all = false)
    name == :another_secret || super
  end

  private

  def method_missing(name, *args, &block)
    case name
    when :super_secret
      'Bingo!'
    when :another_secret
      'Nope.'
    else
      super
    end
  end

  def respond_to_missing?(name, include_all = false)
    name == :super_secret || super
  end
end

x = X.new
puts x.super_secret          # => Bingo!
p defined?(x.super_secret)   # => "method"
puts x.another_secret        # => Nope.
p defined?(x.another_secret) # => nil

It's recommended to implement respond_to_missing? along with method_missing, I too wonder why Rails did it that way.

like image 133
Halil Özgür Avatar answered Jul 21 '26 14:07

Halil Özgür