ruby - Sinatra 变量作用域

标签 ruby sinatra scope

采用以下代码:

### 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 和所有这些变量对整个脚本以及 View 可用。我试着让它们成为全局变量,但没有成功。

最佳答案

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

设置:

set :foo, 'bar'

获得:

"foo is set to " + settings.foo

关于ruby - Sinatra 变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2135854/

相关文章:

ruby 类型问题

ruby - 通过 send_file 发送文件后,如何删除 Sinatra 中的文件?

ruby - 在redis订阅中捕获客户端连接断开

javascript - 为什么这个 javascript 值在它声明的范围内为空,但在更窄的范围内却不是

Javascript函数变量作用域

python - Lambda、可调用类实例和作用域;为什么它在 Python 2.7 中不起作用?

php - 从 HTML 表单运行 ruby​​ 脚本

ruby-on-rails - Controller Inheritance 如何实现抽象 Controller

ruby-on-rails - 仅转换具有回形针样式的特定文件类型的图像

html - 西纳特拉和 HAML : auto-escape/convert unsafe HTML characters for a whole template?