Skip to content

Tips and tricks (hacky)

Jens Ljungblad edited this page Oct 16, 2019 · 2 revisions

Limit records via a reusable "per page" filter

Create a reusable filter:

# app/services/filters/per_page.rb
module Filters
  module PerPage
    extend ActiveSupport::Concern

    included do
      filter :per_page
    end

    def filter_per_page(rel, val)
      @per_page = Integer(val) rescue nil
      rel
    end

    def per_page
      @per_page || 25
    end
  end
end

Include into your service classes:

# app/services/article_service.rb
class ArticleService
  include Godmin::Resources::ResourceService

  filter :title
  filter :author_name
  include ::Filters::PerPage # the filter will appear at the end
end

Auto-assign filter values

Caveat: The URL will no longer reflect the filters' state.

# app/services/article_service.rb
def resources(params)
  params[:filter] ||= ActionController::Parameters.new # when no active filters yet
  params[:filter][:author_name] || params[:filter][:author_name] = 'John Doe'

  super(params)
end