Skip to content

Instantly share code, notes, and snippets.

@damncabbage
Created January 9, 2013 10:45
Show Gist options
  • Save damncabbage/4492259 to your computer and use it in GitHub Desktop.
Save damncabbage/4492259 to your computer and use it in GitHub Desktop.
# Consider the following
class ApplicationController < ActionController::Base
helper_method :current_filter
private
def current_filter
ActiveSupport::StringInquirer.new(params[:filter] || '')
end
end
# Then in your controllers and/or views you can do the following:
current_filter # Get the current value
current_filter.blank? # Check if a filter is present
current_filter.unpaid? # Check if the current filter has the value unpaid.
<% # Before %>
<%= link_to 'All', invoices_path(filter: nil), class: ("current" if params[:filter].blank?) %>
<%= link_to 'Only unpaid', invoices_path(filter: "unpaid"), class: ("current" if params[:filter] == "unpaid") %>
<%= render @invoices %>
<% # After %>
<%= link_to_if current_filter.blank?, "All", invoices_path(filter: current_filter), class: 'current' %>
<%= link_to_if current_filter.unpaid?, "Only unpaid", invoices_path(filter: current_filter), class: 'current' %>
<%= render @invoices %>
# Before
class InvoicesController < ActiveRecord::Base
def index
if params[:filter] == "unpaid"
@invoices = Invoice.unpaid
else
@invoices = Invoice.all
end
end
end
# After
class InvoicesController < ActiveRecord::Base
def index
@invoices = Invoice.unpaid if current_filter.unpaid?
@invoices ||= Invoice.all
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment