class Gyroscope::SearchBase
Public Class Methods
new(attrs)
click to toggle source
Calls superclass method
# File lib/gyroscope/search_base.rb, line 31 def initialize(attrs) super(normalize_order(attrs.dup)) end
Public Instance Methods
search()
click to toggle source
# File lib/gyroscope/search_base.rb, line 39 def search # is there a more generic ActiveModel validation error? unless valid? Rails.logger.debug("the errors: #{errors.inspect}") fail ValidationError.new(self) end build_search_scope end
target_model()
click to toggle source
# File lib/gyroscope/search_base.rb, line 35 def target_model "::#{self.class.name.demodulize}".constantize end
Private Instance Methods
allowed_order_keys()
click to toggle source
# File lib/gyroscope/search_base.rb, line 109 def allowed_order_keys target_model.new.persistable_attribute_names.map do |key| "#{target_model.table_name}.#{key}" end end
base_scope()
click to toggle source
# File lib/gyroscope/search_base.rb, line 74 def base_scope scope = target_model if attributes[:page] || attributes[:per_page] scope = pagination_scope(scope) end if attributes[:order] scope = scope.order(attributes[:order]) end scope end
build_search_scope()
click to toggle source
# File lib/gyroscope/search_base.rb, line 95 def build_search_scope base_scope end
normalize_order(attrs)
click to toggle source
# File lib/gyroscope/search_base.rb, line 52 def normalize_order(attrs) order = attrs[:order] || attrs["order"] return attrs unless order.present? if order.is_a?(Hash) attrs[:order] = order.map {|(column, direction)| tablize_order("#{column} #{direction}")}.join(",") else attrs[:order] = tablize_order(order) end attrs end
pagination_scope(scope)
click to toggle source
# File lib/gyroscope/search_base.rb, line 87 def pagination_scope(scope) pagination_scope = {} pagination_scope[:page] = attributes[:page] if attributes[:page] pagination_scope[:per_page] = attributes[:per_page] if attributes[:per_page] scope.paginate(pagination_scope) end
tablize_order(ordering)
click to toggle source
# File lib/gyroscope/search_base.rb, line 66 def tablize_order(ordering) unless /\./.match ordering "#{target_model.table_name}.#{ordering}" else ordering end end
validate_order()
click to toggle source
# File lib/gyroscope/search_base.rb, line 99 def validate_order return unless attributes[:order] attributes[:order].split(",").each do |order| key, direction = order.split(' ') errors.add(:order, 'Ordering on disallowed key') unless allowed_order_keys.include? key errors.add(:order, 'Invalid sort direction') unless direction && %w(asc desc).include?(direction.downcase) end end