我是Ruby和Sinatra的新手,但我读过一些关于Rails的内容。 Rails主人告诉我们要做的一件事就是将代码留出模板。
嗯,这是我的代码,就在我的模板中需要信息的地方。它可以工作但是,为了学习最佳实践,我怎样才能将这个模板移出我的app.rb文件,而不是在依赖于模板的每个代码块(CRUD)中重复它?
<h2>Status</h2>
<ul>
<li>Received<span><%= Inbox.count %></span></li>
<li>Sent<span><%= Outbox.all(:processed => 1).count %></span></li>
<li><Scheduled<span><%= Outbox.all(:error => -1).count %></span></li>
<li>Error<span><%= Outbox.all(:error.not => [-1,0]).count %></span></li>
</ul>
感谢指点。
答案 0 :(得分:3)
只需将计数加载到您定义路径的实例变量中:
get('/or_so') do
@inbox_count = Inbox.count
@sent_count = Outbox.all(:processed => 1).count
@scheduled_count = Outbox.all(:error => -1).count
@errored_count = Outbox.all(:error.not => [-1,0])
erb :your_template
end
如果您要在多个页面上加载这些内容,还有before
before(/this|insane|regexp|to|grep|locations/) do
# assign variables
end
答案 1 :(得分:0)
作为@Beat Richartz答案的替代品 - 不是因为它错了,而是因为有很多替代方案......
Helpers。 e.g。
helpers do
def mailbox_stats
@mailbox_stats ||= {
:inbox_count => Inbox.count
:sent_count => Outbox.all(:processed => 1).count
:scheduled_count => Outbox.all(:error => -1).count
:errored_count => Outbox.all(:error.not => [-1,0])
}
end
end
并在模板中:
<h2>Status</h2>
<ul>
<li>Received<span><%= mailbox_stats[:inbox_count] %></span></li>
<li>Sent<span><%= mailbox_stats[:sent_count] %></span></li>
<li><Scheduled<span><%= mailbox_stats[:scheduled_count] %></span></li>
<li>Error<span><%= mailbox_stats[:errored_count] %></span></li>
</ul>
Settings可能不是最好的想法,但可以这样做,也许如果你想设置一些默认值:
config do
set :mailbox_stats, {
:inbox_count => 0
:sent_count => 0
:scheduled_count => 0
:errored_count => 0
}
end
before do
if @user.has? :inbox # or something relevant
settings.mailbox_stats.replace( {
:inbox_count => Inbox.count
:sent_count => Outbox.all(:processed => 1).count
:scheduled_count => Outbox.all(:error => -1).count
:errored_count => Outbox.all(:error.not => [-1,0])
})
end
end
<h2>Status</h2>
<ul>
<li>Received<span><%= settings.mailbox_stats[:inbox_count] %></span></li>
<li>Sent<span><%= settings.mailbox_stats[:sent_count] %></span></li>
<li><Scheduled<span><%= settings.mailbox_stats[:scheduled_count] %></span></li>
<li>Error<span><%= settings.mailbox_stats[:errored_count] %></span></li>
</ul>
get('/or_so') do
erb :your_template, :locals => { :mailbox_stats => {
:inbox_count => Inbox.count
:sent_count => Outbox.all(:processed => 1).count
:scheduled_count => Outbox.all(:error => -1).count
:errored_count => Outbox.all(:error.not => [-1,0])
}
}
end
在模板中:
<h2>Status</h2>
<ul>
<li>Received<span><%= mailbox_stats[:inbox_count] %></span></li>
<li>Sent<span><%= mailbox_stats[:sent_count] %></span></li>
<li><Scheduled<span><%= mailbox_stats[:scheduled_count] %></span></li>
<li>Error<span><%= mailbox_stats[:errored_count] %></span></li>
</ul>
我可能会使用帮手。