Sinatra可变范围

请使用以下代码:

### 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 ,以及所有可用于整个脚本的变量以及视图。 我尝试将它们作为全局变量,但没有骰子。

可能不是“最干净”的方法,但将它们设置为选项应该有效:
– > http://www.sinatrarb.com/configuration.html 🙂

设置:

 set :foo, 'bar' 

得到:

 "foo is set to " + settings.foo 

使它们成为常量。 反正他们应该不是吗? 他们不会改变。

通过全部大写来创建一个常量。

如果您还有其他问题,请阅读有关Ruby Variable Scopes的这篇文章。 http://www.techotopia.com/index.php/Ruby_Variable_Scope

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

玩得开心。 @reply我,当你完成你的新博客(我猜这是这是为了什么)。

来自Sinatra自述文件 :


访问模板中的变量

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

 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 

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


第三种选择是为它们设置访问器作为辅助方法。 (整个申请和观点可以使用。)

什么也有效:

 @@foo = "bar" 

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