lib/scoped_from/query.rb in scoped_from-0.2 vs lib/scoped_from/query.rb in scoped_from-0.3
- old
+ new
@@ -1,18 +1,17 @@
module ScopedFrom
class Query
+ FALSE_VALUES = %w( false no n off 0 ).freeze
ORDER_DIRECTIONS = %w( asc desc ).freeze
TRUE_VALUES = %w( true yes y on 1 ).freeze
attr_reader :params
# Available options are: - :only : to restrict to specified keys.
# - :except : to ignore specified keys.
- # - :include_blank : to include blank values
- # (default false).
def initialize(scope, params, options = {})
@scope = scope.scoped
@options = options
self.params = params
end
@@ -44,10 +43,14 @@
end
scope.instance_variable_set('@__query', self)
scope
end
+ def false?(value)
+ FALSE_VALUES.include?(value.to_s.strip.downcase)
+ end
+
def order_to_sql(value)
order = parse_order(value)
"#{order[:column]} #{order[:direction].upcase}" if order.present?
end
@@ -69,19 +72,26 @@
params = params.params if params.is_a?(self.class)
params = CGI.parse(params.to_s) unless params.is_a?(Hash)
@params = ActiveSupport::HashWithIndifferentAccess.new
params.each do |name, value|
values = [value].flatten
- values.delete_if(&:blank?) unless @options[:include_blank]
next if values.empty?
if name.to_s == 'order'
order = parse_order(values.last)
@params[name] = "#{order[:column]}.#{order[:direction]}" if order.present?
elsif @scope.scope_without_argument?(name)
- @params[name] = true if values.any? { |value| true?(value) }
- elsif @scope.scope_with_one_argument?(name) || @options[:include_columns].present? && @scope.column_names.include?(name.to_s)
+ @params[name] = true if values.all? { |value| true?(value) }
+ elsif @scope.scope_with_one_argument?(name)
value = values.many? ? values : values.first
@params[name] = @params[name] ? [@params[name], value].flatten : value
+ elsif @options[:exclude_columns].blank? && @scope.column_names.include?(name.to_s)
+ if @scope.columns_hash[name.to_s].type == :boolean
+ @params[name] = true if values.all? { |value| true?(value) }
+ @params[name] = false if values.all? { |value| false?(value) }
+ else
+ value = values.many? ? values : values.first
+ @params[name] = @params[name] ? [@params[name], value].flatten : value
+ end
end
end
@params.slice!(*[@options[:only]].flatten) if @options[:only].present?
@params.except!(*[@options[:except]].flatten) if @options[:except].present?
end
\ No newline at end of file