0

I have a method that I need to use across several Rails controllers. In an effort to keep my code DRY I've split this method out into an extension module which I can then include into whichever controllers need to use it like this:

# 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

As you can see, that job_sort_order needs access to the session. The problem is that I don't seem to be able to access the session from the mixin. I don't get an error or anything, the session just never gets set.

I'm fairly sure that the job_sort_order method works correctly because everything works as I want it to if I copy/paste the whole method back into the controller rather than using it from the mixin.

Is there a way to access the session from the mixin?

David Tuite
  • 22,258
  • 25
  • 106
  • 176

1 Answers1

0

there are several ways to get grip in what's happening. use stupid puts to inspect your session object. use a debugger or pry to step into your implementation.

from what i see in your code, i think that your module actually has access to the session. otherwise it would throw a name-error, because session would be unknown as it's not defined in your module.

if the value of your session object does not persist between requests, than i guess that something is wrong with your session handling. are there other things persisted in your session?

phoet
  • 18,688
  • 4
  • 46
  • 74