class Rails::Surrender::FilterBuilder
apply filtering directives to the given resource, based on the given filter controls
Attributes
filter[R]
resource[R]
Public Class Methods
new(resource:, filter:)
click to toggle source
# File lib/rails/surrender/helpers/filter_builder.rb, line 9 def initialize(resource:, filter:) @resource = resource @filter = filter end
Public Instance Methods
build!()
click to toggle source
# File lib/rails/surrender/helpers/filter_builder.rb, line 14 def build! return resource unless resource.is_a?(ActiveRecord::Relation) filter.each do |term| scope, value = term.first send_filter_for(scope, value) end resource end
Private Instance Methods
filter_method(scope)
click to toggle source
prepend filter_by so that only filter_by scope methods are reachable.
# File lib/rails/surrender/helpers/filter_builder.rb, line 41 def filter_method(scope) "filter_by_#{scope}".gsub('.', '_').to_sym end
filter_method_id(scope)
click to toggle source
# File lib/rails/surrender/helpers/filter_builder.rb, line 45 def filter_method_id(scope) "#{filter_method(scope)}_id".to_sym end
send_filter_for(scope, value)
click to toggle source
# File lib/rails/surrender/helpers/filter_builder.rb, line 28 def send_filter_for(scope, value) if resource.respond_to?(filter_method(scope)) # filter exists on model? @resource = @resource.send(filter_method(scope), value) elsif resource.respond_to?(filter_method_id(scope)) # resolved it by appending _id? @resource = @resource.send(filter_method_id(scope), value) else raise Error, I18n.t('surrender.error.query_string.filter.not_available', param: scope) end end