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

95 lines
2.8 KiB
Ruby
Raw Normal View History

class Item < ActiveRecord::Base
2010-05-16 17:45:30 -07:00
include SwfAssetParent
SwfAssetType = 'object'
2010-05-16 17:45:30 -07:00
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-15 11:14:17 -07:00
cattr_reader :per_page
@@per_page = 30
2010-05-15 11:01:15 -07:00
scope :alphabetize, order('name ASC')
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)
@species_support_ids_array = nil
replacement = replacement.join(',') if replacement.is_a?(Array)
write_attribute('species_support_ids', replacement)
end
def supported_species
2010-05-20 19:09:55 -07:00
@supported_species ||= species_support_ids.empty? ? Species.all : species_support_ids.sort.map { |id| Species.find(id) }
end
def self.search(query)
raise ArgumentError, "Please provide a search query" unless query
query = query.strip
raise ArgumentError, "Search queries should be at least 3 characters" if query.length < 3
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)
raise ArgumentError, "Species \"#{self.humanize}\" does not exist" unless species
# TODO: add a many-to-many table to handle this relationship, if
# performance becomes an issue
ids = items[:species_support_ids]
condition = ids.eq('').or(ids.matches_any(
species.id,
"#{species.id},%",
"%,#{species.id},%",
"%,#{species.id}"
))
elsif @property == 'description' || @property.blank?
column = @property == 'description' ? :description : :name
condition = items[column].matches("%#{self}%")
else
raise ArgumentError, "Unknown search filter \"#{@property}\""
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