ruby-on-rails - Rails/Ruby 错误地显示变量未定义

标签 ruby-on-rails ruby

在调试控制台中,当应用程序运行时(使用 binding.pry 中断它),我可以看到我的变量 Rails.configuration.hardcoded_current_user_key 已设置:

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

但它似乎没有被定义:

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

然而它可以很好地存储和测试它的值:

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

这是怎么回事?

最佳答案

这是因为 Rails 配置 implements respond_to? 但不是 respond_to_missing?defined? 只有 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

recommended实现 respond_to_missing?method_missing,我也想知道为什么 Rails 会那样做。

关于ruby-on-rails - Rails/Ruby 错误地显示变量未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40184952/

相关文章:

ruby-on-rails - 在 RUBY 中检测到隐藏 BOM 字符时如何引发错误

ruby-on-rails - 新 Rails 项目 : 'bundle install' can't install rails in gemfile

ruby - Rspec - 如何 stub 第 3 方异常

ruby-on-rails - rails : renaming a controller and corresponding model

javascript - 在Rails 3中从observe_field更改为JQuery

ruby-on-rails - Rails - 出于测试目的实现可选片段缓存的最佳方法

ruby-on-rails - 如何使用 Nginx 设置防止 XML 文件被 Google on Rails 索引?

ruby-on-rails - 在选择 Rails 中设置提示值

ruby - 什么是 Ruby 调试器技巧、调整和最佳实践?

ruby-on-rails - 结合 Ruby on Rails 和 Backbone