1
0
Fork 0
forked from OpenNeo/impress
impress/app/models/item.rb

77 lines
2.1 KiB
Ruby
Raw Normal View History

class Item < ActiveRecord::Base
set_table_name 'objects' # Neo & PHP Impress call them objects, but the class name is a conflict (duh!)
set_inheritance_column 'inheritance_type' # PHP Impress used "type" to describe category
2010-05-14 15:41:40 -07:00
# Not defining validations, since this app is currently read-only
def species_support_ids
@species_support_ids_array ||= read_attribute('species_support_ids').split(',').map(&:to_i)
end
def species_support_ids=(replacement)
replacement = replacement.join(',') if replacement.is_a?(Array)
write_attribute('species_support_ids', replacement)
end
def self.search(query)
query = query.strip if query
raise ArgumentError, "Please provide a search query" if query.blank?
query_conditions = [Condition.new]
in_phrase = false
query.each_char do |c|
if c == ' ' && !in_phrase
query_conditions << Condition.new
elsif c == '"'
in_phrase = !in_phrase
elsif c == ':' && !in_phrase
query_conditions.last.to_property!
2010-05-15 09:43:54 -07:00
elsif c == '-' && !in_phrase && query_conditions.last.empty?
query_conditions.last.negate!
else
query_conditions.last << c
end
end
query_conditions.inject(self) do |scope, condition|
condition.narrow(scope)
end
end
private
class Condition < String
def to_property!
@property = self.clone
self.replace ''
end
2010-05-15 09:43:54 -07:00
def negate!
@negative = true
end
def narrow(scope)
2010-05-15 09:43:54 -07:00
items = Table(:objects)
if @property == 'species'
species = Species.find_by_name(self)
# TODO: add a many-to-many table to handle this relationship
2010-05-15 09:43:54 -07:00
condition = items[:species_support_ids].matches_any(
species.id,
"#{species.id},%",
"%,#{species.id},%",
"%,#{species.id}"
)
else
2010-05-15 09:43:54 -07:00
matcher = "%#{self}%"
condition = items[:name].matches(matcher).or(
items[:description].matches(matcher)
)
end
2010-05-15 09:43:54 -07:00
condition = condition.not if @negative
scope.where(condition)
end
def inspect
@property ? "#{@property}:#{super}" : super
end
end
2010-05-14 15:41:40 -07:00
end