【问题标题】:Constants in Padrino/Sinatra routesPadrino/Sinatra 路线中的常量
【发布时间】:2012-09-11 14:41:00
【问题描述】:

在 Sinatra/Padrino 中,哪里是添加常量以供在路由内部使用的合理位置?

我正在使用 Padrino 挂载多个应用程序,因此我希望所有应用程序都可以使用常量。 (所有应用都继承自一个基类。)

我使用Sinatra.helpers 来添加在路由内部使用的方法。

我希望对常量采用类似的方法。

更新

这似乎是一个范围界定问题,但我不知道在这种情况下出了什么问题。

这是一个演示问题的精简 padrino 应用程序:

app.rb

class MyProject < Padrino::Application
  register Padrino::Rendering
  register Padrino::Mailer
  register Padrino::Helpers

  MY_CONST = 123
end

controllers.rb

MyProject.controller do
  get "/" do
    p self.class            # => MyProject
    p self.class.constants  # => [:DATA_ATTRIBUTES, ... <snip>..., :MY_CONST, ... <snip>... ]
    p MyProject::MY_CONST   # => 123
    p MY_CONST              # => NameError - uninitialized constant MY_CONST
  end
end

【问题讨论】:

  • 你可以添加一个类常量,它们应该在任何地方都可用,就像类变量一样。
  • 在应用程序类中?添加到扩展 Padrino::Application 的应用程序类的常量在路由中不可用。

标签: ruby sinatra padrino


【解决方案1】:

好的,显然我遇到了一个问题,即 Ruby 如何在 instance_evaled 的 proc 中处理常量查找。

这是重新创建错误的无 Padrino 方法:

class Thing

  MY_CONST = 123

  def doStuff (&block)
    p "doStuff: #{self.class}"        # => "doStuff: Thing"
    p "doStuff: #{MY_CONST}"          # => "doStuff: 123"

    instance_eval &block
  end

  def doOtherStuff (&block)
    p "doOtherStuff: #{self.class}"   # => "doOtherStuff: Thing"
    p "doOtherStuff: #{MY_CONST}"     # => "doOtherStuff: 123"

    yield 
  end
end

t = Thing.new

t.doStuff do 
  doOtherStuff do
    p self.class             # => Thing
    p self.class.constants   # => [:MY_CONST]
    p Thing::MY_CONST        # => 123
    p MY_CONST               # => NameError: uninitialized constant MY_CONST
  end
end

相关问题:Constant Lookup with instance_eval in Ruby 1.9

相关博文:http://jfire.io/blog/2011/01/21/making-sense-of-constant-lookup-in-ruby/

看来我的选择仅限于:

  1. 使用全局常量
  2. 完全指定常量(例如:上例中的 Thing::MY_CONST)
  3. 改用方法

【讨论】:

    【解决方案2】:

    嗯,可能我没看懂,不过你可以用apps.rb

    Padrino.configure do
       set :foo, :bar
    end
    

    那么您应该能够在所有应用程序中检索您的 var。

    或者在 boot 或 apps.rb 中添加一些类似:

    MY_CONST = 1
    MyConst = 1
    

    【讨论】:

    • 好酷。我现在可以在我的路线中使用“settings.foo”。这就是进步:-) 我仍然希望我的路线可以使用常量,就好像它们是本地的一样(即:无范围)。这不可能吗?
    • 再次感谢。我还假设将常量添加到 app.rb 会正常工作。但我仍然有问题。我已经用示例代码更新了这个问题。谢谢。
    • 如果您想在全局环境中使用它,请将其保留在课堂之外,否则请查看NameError 的最后部分,它会显示uninitialized constant MY_CONST for ...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多