2010-01-25 74 views
8

看看下面的代碼:西納特拉變量的作用域

### 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,以及所有那些提供給整個腳本變量,以及意見。我試圖讓他們成爲全局變量,但沒有骰子。

回答

9

未必是 「最乾淨」 的方式做到這一點,但將它們設置爲選項應該工作:
- >http://www.sinatrarb.com/configuration.html :)

設置:

set :foo, 'bar' 

越來越:

"foo is set to " + options.foo 
+4

使用'options'不會後重新啓動服務器拋出一個警告:'Sinatra :: Base#選項已被棄用,將被刪除,改爲使用#settings。' 改爲使用'settings'。 – briangonzalez 2012-11-19 16:11:08

9

使它們成爲常數。反正它們應該不是嗎?他們不會改變。

通過將其寫入所有大寫字母來保持不變。

如果您還有其他問題,請閱讀關於Ruby變量作用域的文章。 http://www.techotopia.com/index.php/Ruby_Variable_Scope

另一個乾淨選項可能是一個配置類,其中init方法加載YAML,然後設置變量。

玩得開心。 @當你完成你的新博客時,請回復我(我猜這就是這個原因)。

5

Sinatra README


在模板

模板訪問變量相同的上下文中的路由處理程序中評價。在路由執行器設置實例變量是direcly訪問的模板:

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 

從其他模板中呈現模板,因爲諧音時,這通常使用。


第三種選擇是將它們的訪問器設置爲輔助方法。 (這是還提供整個應用程序和觀點

1

什麼也可以工作:

@@foo = "bar" 

但不要忘了這個變化