Skip to content

Instantly share code, notes, and snippets.

@luisguzman02
Created August 27, 2019 16:07
Show Gist options
  • Save luisguzman02/e21642319f33f97c6a0740c8b08b88ce to your computer and use it in GitHub Desktop.
Save luisguzman02/e21642319f33f97c6a0740c8b08b88ce to your computer and use it in GitHub Desktop.

Revisions

  1. luisguzman02 created this gist Aug 27, 2019.
    26 changes: 26 additions & 0 deletions filterable.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    module Filterable
    extend ActiveSupport::Concern

    included do
    scope :filtered, ->(values) {
    current = all
    filters.each do |key, method|
    if values.try(:key?, key) && current.respond_to?(method)
    current = current.send(method, values[key])
    end
    end
    current
    }
    end

    module ClassMethods
    def add_filter(filter_key, method_name, callable = nil)
    scope(method_name, callable) if callable
    filters[filter_key] = method_name
    end

    def filters
    @filters ||= {}
    end
    end
    end