Last Updated: February 25, 2016
·
1.191K
· managr

Serializing ActiveRecord scopes

Sometimes you might find it useful to serialize ActiveRecord scope to persist it or passed it to i.e. sidekiq/resque worker.

Super simple solution is to use to_sql on the ActiveRecord scope:

ActiveRecord.where('created_at > ?', Time.now).to_sql

But persisting sql queries might not be the most elegant solution.

Starting from 0.6.0.rc has_scope gem has change the initialisation scheme which enables it to be used without controller.

module Scope
  def self.included(base)
    base.has_scope :with_name_like
    base.has_scope :with_title_like
  end
end

class PostsController < ApplicationController
  include Scope

  def index
    search_params = params[:post_search] || {}
    @posts = apply_scopes(Post, search_params)
  end
end

class PostProcessor
  include HasScope
  include Scope

  def process(scope_hash)
    posts = apply_scopes(Post.all, scope_hash)
    # ....
  end
end