【问题标题】:Sinatra Variable ScopeSinatra 变量范围
【发布时间】:2010-01-25 21:39:52
【问题描述】:

取以下代码:

### Dependencies
require 'rubygems'
require 'sinatra'
require 'datamapper'

### Configuration
config = YAML::load(File.read('config.yml'))

name = config['config']['name']
description = config['config']['description']
username = config['config']['username']
password = config['config']['password']
theme = config['config']['theme']

set :public, 'views/themes/#{theme}/static'

### Models
DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/marvin.db")

class Post
  include DataMapper::Resource
  property :id, Serial
  property :name, String
  property :body, Text
  property :created_at, DateTime
  property :slug, String
end

class Page
  include DataMapper::Resource
  property :id, Serial
  property :name, String
  property :body, Text
  property :slug, String
end

DataMapper.auto_migrate!

### Controllers
get '/' do
  @posts = Post.get(:order => [ :id_desc ])
  haml :"themes/#{theme}/index"
end

get '/:year/:month/:day/:slug' do
  year = params[:year]
  month = params[:month]
  day = params[:day]
  slug = params[:slug]

  haml :"themes/#{theme}/post.haml"
end

get '/:slug' do
  haml :"themes/#{theme}/page.haml"
end

get '/admin' do
  haml :"admin/index.haml"
end

我想让name,以及所有这些变量都可用于整个脚本以及视图。我尝试将它们设为全局变量,但没有骰子。

【问题讨论】:

    标签: ruby sinatra scope


    【解决方案1】:

    可能不是“最干净”的方法,但将它们设置为选项应该可以工作:
    --> http://www.sinatrarb.com/configuration.html :)

    设置:

    set :foo, 'bar'
    

    得到:

    "foo is set to " + settings.foo
    

    【讨论】:

    • 使用options 不会引发警告:Sinatra::Base#options is deprecated and will be removed, use #settings instead. 请改用settings
    【解决方案2】:

    使它们成为常量。无论如何,他们应该不是吗?他们不会改变。

    通过全部大写来制作一个常量。

    如果您还有其他问题,请阅读这篇关于 Ruby 变量作用域的文章。 http://www.techotopia.com/index.php/Ruby_Variable_Scope

    另一个干净的选项可能是配置类,其中 init 方法加载 YAML,然后设置变量。

    玩得开心。 @reply me when you're done your new blog(我猜这就是它的用途)。

    【讨论】:

      【解决方案3】:

      来自Sinatra README


      访问模板中的变量

      模板在与路由处理程序相同的上下文中进行评估。在路由处理程序中设置的实例变量可以通过模板直接访问:

      get '/:id' do
        @foo = Foo.find(params[:id])
         haml '%h1= @foo.name'
      end
      

      或者,指定局部变量的显式哈希:

      get '/:id' do
        foo = Foo.find(params[:id])
        haml '%h1= foo.name', :locals => { :foo => foo }
      end
      

      这通常在将模板呈现为其他模板中的部分时使用。


      第三种选择是为它们设置访问器作为辅助方法。 (在整个应用程序和视图中可用。)

      【讨论】:

        【解决方案4】:

        什么也有效:

        @@foo = "bar"
        

        但不要忘记在此更改后重新启动服务器

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-08-10
          • 1970-01-01
          • 2014-01-31
          • 2011-02-10
          • 2020-02-07
          • 2012-12-23
          相关资源
          最近更新 更多