困境:
我处于需要跨多个视图和控制器显示用户活动的情况。代码开始有点味道,所以我非常感谢一些清理它的指导。
我有一个用户控制器,它有一个“显示”(/user_id/)视图,可以在侧边栏中呈现最近的活动,还有一个“活动”(user_id/activity)视图,可以呈现所有用户的活动。我还有一个“页面”控制器,它有一个“仪表板”视图,它也呈现用户的活动。
编码:
users_controller.rb
好像:
@activities = []
@activities += @user.skills.map { |skill| Activity.new("skill", skill, skill.created_at) }
@activities += @user.unions.map { |union| Activity.new("union", union, union.created_at) }
@activities += @user.companies.map { |company| Activity.new("company", company, company.created_at) }
@activities += @user.clients.map { |client| Activity.new("client", client, client.created_at) }
@activities += @user.schools.map { |school| Activity.new("school", school, school.created_at) }
@activities += @following_list.map { |following| Activity.new("following", following, following.created_at) }
@activities += @recommended.map { |recommend| Activity.new("recommend", recommend, recommend.created_at) }
@activities += @user.statuses.all(:limit => 5, :order => "created_at DESC").map { |status| Activity.new("status", status, status.created_at) }
sorted_activities = @activities.sort_by(&:date).reverse
@activities = sorted_activities[0..(4)]
pages_controller.rb
好像:
@your_activity = []
@your_activity += current_user.skills.map { |skill| ActivityDashboard.new("#{current_user.first_name} #{current_user.last_name}","#{current_user.id}","#{current_user.avatar}","skill", skill, skill.created_at) }
@your_activity += current_user.unions.map { |union| ActivityDashboard.new("#{current_user.first_name} #{current_user.last_name}","#{current_user.id}","#{current_user.avatar}","union", union, union.created_at) }
@your_activity += current_user.companies.map { |company| ActivityDashboard.new("#{current_user.first_name} #{current_user.last_name}","#{current_user.id}","#{current_user.avatar}","company", company, company.created_at) }
@your_activity += current_user.clients.map { |client| ActivityDashboard.new("#{current_user.first_name} #{current_user.last_name}","#{current_user.id}","#{current_user.avatar}","client", client, client.created_at) }
@your_activity += current_user.schools.map { |school| ActivityDashboard.new("#{current_user.first_name} #{current_user.last_name}","#{current_user.id}","#{current_user.avatar}","school", school, school.created_at) }
@your_activity += current_user.statuses.map { |status| ActivityDashboard.new("#{current_user.first_name} #{current_user.last_name}","#{current_user.id}","#{current_user.avatar}","status", status, status.created_at) }
sorted_activities = @your_activity.sort_by(&:date).reverse
@your_activity = sorted_activities[0..(35)]