Sinatra 变量范围 [英] Sinatra Variable Scope
本文介绍了Sinatra 变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
输入以下代码:
### 依赖需要红宝石"需要'sinatra'需要数据映射器"### 配置config = YAML::load(File.read('config.yml'))name = config['config']['name']description = config['config']['description']用户名 = 配置['配置']['用户名']密码 = config['config']['password']主题 = config['config']['theme']set :public, 'views/themes/#{theme}/static'### 楷模DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/marvin.db")班级帖子包括 DataMapper::Resource属性:id,序列号属性:名称,字符串属性:正文,文本属性:created_at,日期时间属性:slug,字符串结尾班级页面包括 DataMapper::Resource属性:id,序列号属性:名称,字符串属性:正文,文本属性:slug,字符串结尾DataMapper.auto_migrate!### 控制器得到'/'做@posts = Post.get(:order => [:id_desc])哈姆勒:主题/#{主题}/索引"结尾得到 '/:year/:month/:day/:slug' 做年 = 参数[:年]月 = 参数[:月]天=参数[:天]弹头 = 参数[:弹头]哈姆:主题/#{主题}/post.haml"结尾得到 '/:slug' 做哈姆勒:主题/#{主题}/page.haml"结尾得到 '/admin' 做哈姆:管理员/索引.haml"结尾
我想让 name
以及所有这些变量可用于整个脚本以及视图.我试着让它们成为全局变量,但没有骰子.
解决方案
可能不是最干净"的方法,但将它们设置为选项应该可行:
--> http://www.sinatrarb.com/configuration.html :)>
设置:
set :foo, 'bar'
得到:
"foo 设置为" + settings.foo
Take the following code:
### 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
I want to make name
, and all those variables available to the entire script, as well as the views. I tried making them global variables, but no dice.
解决方案
Might not be the "cleanest" way to do it, but setting them as options should work:
--> http://www.sinatrarb.com/configuration.html :)
setting:
set :foo, 'bar'
getting:
"foo is set to " + settings.foo
这篇关于Sinatra 变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文