From 83d08b00179b3f75a04d34b4835768e860dc7a58 Mon Sep 17 00:00:00 2001 From: kikito Date: Wed, 2 Sep 2015 13:21:05 +0200 Subject: [PATCH] Implements the HasFilters controller concern --- app/controllers/concerns/has_filters.rb | 13 +++++++ spec/controllers/concerns/has_filters_spec.rb | 37 +++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 app/controllers/concerns/has_filters.rb create mode 100644 spec/controllers/concerns/has_filters_spec.rb diff --git a/app/controllers/concerns/has_filters.rb b/app/controllers/concerns/has_filters.rb new file mode 100644 index 000000000..3dd3cc295 --- /dev/null +++ b/app/controllers/concerns/has_filters.rb @@ -0,0 +1,13 @@ +module HasFilters + extend ActiveSupport::Concern + + class_methods do + def has_filters(valid_filters, *args) + before_filter(*args) do + @valid_filters = valid_filters + @current_filter = params[:filter] + @current_filter = @valid_filters.first unless @valid_filters.include?(@current_filter) + end + end + end +end diff --git a/spec/controllers/concerns/has_filters_spec.rb b/spec/controllers/concerns/has_filters_spec.rb new file mode 100644 index 000000000..af094e9ec --- /dev/null +++ b/spec/controllers/concerns/has_filters_spec.rb @@ -0,0 +1,37 @@ +require 'rails_helper' + +describe 'HasFilters' do + + class FakeController < ActionController::Base; end + + controller(FakeController) do + include HasFilters + has_filters ['all', 'pending', 'reviewed'], only: :index + + def index + render text: "#{@current_filter} (#{@valid_filters.join(' ')})" + end + end + + it "has the valid filters set up" do + get :index + expect(response.body).to eq('all (all pending reviewed)') + end + + describe "the current filter" do + it "defaults to the first one on the list" do + get :index + expect(response.body).to eq('all (all pending reviewed)') + end + + it "can be changed by the filter param" do + get :index, filter: 'pending' + expect(response.body).to eq('pending (all pending reviewed)') + end + + it "defaults to the first one on the list if given a bogus filter" do + get :index, filter: 'foobar' + expect(response.body).to eq('all (all pending reviewed)') + end + end +end