我有一个需要跨多个 Rails 控制器使用的方法。为了使我的代码保持干燥,我将此方法拆分为一个扩展模块,然后我可以将其包含到任何需要使用它的控制器中,如下所示:
# app/controllers/jobs_controller.rb
require "extensions/job_sorting_controller_extensions"
class JobsController < ApplicationController
include Extensions::JobSortingControllerExtensions
def index
@jobs = Job.order(job_sort_order)
end
end
# lib/extensions/job_sorting_controller_extensions.rb
module Extensions
module JobSortingControllerExtensions
# Prevent sql injection and control the direction of the sort depending
# on which option is selected. Remember the sort by storing in session.
def job_sort_order
if params[:job_sort].present?
job_sort = case params[:job_sort]
# This makes jobs which have no due date at all go to the bottom
# of the list. INFO: http://stackoverflow.com/a/8949726/574190
# If due_date ever becomes required then this can be simplified.
when "due_date" then "coalesce(due_date, '3000-12-31') asc"
when "created_at" then "created_at desc"
end
session[:job_sort] = job_sort
end
# Set the session :job_sort to a default if it's empty at this point.
session[:job_sort] ||= "created_at desc"
end
end
end
如您所见,这job_sort_order
需要访问会话。问题是我似乎无法从 mixin 访问会话。我没有收到错误或任何东西,会话永远不会设置。
我相当确定该job_sort_order
方法可以正常工作,因为如果我将整个方法复制/粘贴回控制器而不是从 mixin 中使用它,那么一切都会按我的意愿工作。
有没有办法从 mixin 访问会话?