1
0
Fork 0
forked from OpenNeo/impress

Simplify filter API a bit

Not doing the tricks with `is_positive` anymore, instead just calling different functions altogether at the call site.

Also, instead of classes, I feel like this is a lot more concise to just write as class methods that create certain instances of a trivial `Filter` data class. Without the tricks of `is_positive` in play, the value of classes goes way down imo.
This commit is contained in:
Matchu 2023-07-26 11:46:10 -07:00
parent 2ac806333d
commit 4d722dd5c5

View file

@ -35,13 +35,15 @@ class Item
case key case key
when 'name' when 'name'
filters << NameFilter.new(value, locale, is_positive) filters << (is_positive ?
Filter.name_includes(value, locale) :
Filter.name_excludes(value, locale))
when 'is' when 'is'
case value case value
when 'nc' when 'nc'
filters << NCFilter.new(is_positive) filters << (is_positive ? Filter.is_nc : Filter.is_not_nc)
when 'np' when 'np'
filters << NPFilter.new(is_positive) filters << (is_positive ? Filter.is_np : Filter.is_not_np)
else else
message = I18n.translate('items.search.errors.not_found.label', message = I18n.translate('items.search.errors.not_found.label',
:label => "is:#{value}") :label => "is:#{value}")
@ -67,56 +69,50 @@ class Item
private private
class NameFilter # A Filter is basically a wrapper for an Item scope, with extra info about
def initialize(value, locale, is_positive) # how to convert it into a search query string.
@value = value class Filter
@locale = locale def initialize(query, text)
@is_positive = is_positive @query = query
@text = text
end end
def to_query def to_query
@is_positive ? @query
Item.name_includes(@value, @locale) :
Item.name_excludes(@value, @locale)
end end
def to_s def to_s
sign = @is_positive ? '' : '-' @text
if /\s/.match(@value)
sign + '"' + @value + '"'
else
sign + @value
end
end
end end
class NCFilter def inspect
def initialize(is_positive) "#<#{self.class.name} #{@text.inspect}>"
@is_positive = is_positive
end end
def to_query def self.name_includes(value, locale)
@is_positive ? Item.is_nc : Item.is_np text = /\s/.match(value) ? '"' + value + '"' : value
self.new Item.name_includes(value, locale), text
end end
def to_s def self.name_excludes(value, locale)
sign = @is_positive ? '' : '-' text = '-' + (/\s/.match(value) ? '"' + value + '"' : value)
sign + 'is:nc' self.new Item.name_excludes(value, locale), text
end
end end
class NPFilter def self.is_nc
def initialize(is_positive) self.new Item.is_nc, 'is:nc'
@is_positive = is_positive
end end
def to_query def self.is_not_nc
@is_positive ? Item.is_np : Item.is_nc self.new Item.is_np, '-is:nc'
end end
def to_s def self.is_np
sign = @is_positive ? '' : '-' self.new Item.is_np, 'is:np'
sign + 'is:np' end
def self.is_not_np
self.new Item.is_nc, '-is:np'
end end
end end
end end