我有一个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
是的,这将做。 –