我有一個Rails 3應用程序,並正在執行配置文件完整性某種功能。當用戶登錄時,應用程序應該向他/她展示製作「完整」配置文件的進度。爲了說明我正在使用在應用程序初始化時填充了需求的單例類。單例有一個數組@requirements
。它使用我的初始化程序正確填充。當我點擊ProfileController
時,顯示需求。但是,在第一個分支請求ProfileController#completeness
列表否@requirements
。單例中的數組是空的。我相信單身人士不會在控制器請求中返回相同的實例。我在哪裏錯了?跨控制器的Rails單身對象清除
注意:這個類只是持有要求,而不是特定用戶在實現它們方面的進展。需求很少改變,所以我想避免數據庫查找。
# lib/profile_completeness.rb
require 'singleton'
class ProfileCompleteness
include Singleton
include Enumerable
attr_reader :requirements
def add_requirement(args)
b = Requirement.new(args)
@requirements << b
b
end
def clear
@requirements = []
end
def each(&block)
@requirements.each { |r| block.call(r) }
end
class Requirement
# stuff
end
end
-
# config/initializers/profile_completeness.rb
collection = ProfileCompleteness.instance()
collection.clear
collection.add_requirement({ :attr_name => "facebook_profiles",
:count => 1,
:model_name => "User",
:instructions => "Add a Facebook profile" })
-
class ProfileController < ApplicationController
def completeness
@requirements = ProfileCompleteness.instance
end
end
-
<!-- app/views/profile/completeness.html.erb -->
<h2>Your Profile Progress</h2>
<table>
<%- @requirements.each do |requirement|
complete_class = requirement.is_fulfilled_for?(current_user) ? "complete" : "incomplete" -%>
<tr class="profile_requirement <%= complete_class -%>">
<td>
<%- if requirement.is_fulfilled_for?(current_user) -%>
✓
<%- end -%>
</td>
<td><%= raw requirement.instructions %></td>
</tr>
<%- end -%>
</table>
<p><%= link_to "Profile", profile_path -%></p>
ProfileComplete類只保存需求,而不是特定用戶的進度。向班級詢問用戶完成多少要求是很容易的。需求很少會改變,所以我想保存一個數據庫查詢。 –
看到我的編輯;) – sled
是的,這將做。 –