lib/ampere/model.rb in ampere-0.1.2 vs lib/ampere/model.rb in ampere-0.1.3

- old
+ new

@@ -78,10 +78,19 @@ self end # Saves this record to the database. def save + self.class.unique_indices.each do |idx| + # For each uniquely-indexed field, look up the index for that field, + # and throw an exception if this record's value for that field is in + # the index already. + if Ampere.connection.hexists("ampere.index.#{self.class.to_s.downcase}.#{idx}", instance_variable_get("@#{idx}")) then + raise "Cannot save non-unique value for #{idx}" + end + end + # Grab a fresh GUID from Redis by incrementing the "__guid" key if @id.nil? then @id = "#{self.class.to_s.downcase}.#{Ampere.connection.incr('__guid')}" end @@ -162,10 +171,11 @@ # Declares a field. See the README for more details. def self.field(name, options = {}) @fields ||= [] @field_defaults ||= {} @indices ||= [] + @unique_indices ||= [] @field_types ||= {} @fields << name # attr_accessor :"#{name}" @@ -258,27 +268,37 @@ end end # Defines an index. See the README for more details. def self.index(field_name, options = {}) + # TODO There has just got to be a better way to handle this. @fields ||= [] @field_defaults ||= {} @indices ||= [] + @unique_indices ||= [] @field_types ||= {} + if field_name.class == String or field_name.class == Symbol then + # Singular index raise "Can't index a nonexistent field!" unless @fields.include?(field_name) elsif field_name.class == Array then + # Compound index field_name.each{|f| raise "Can't index a nonexistent field!" unless @fields.include?(f)} field_name.sort! else raise "Can't index a #{field_name.class}" end @indices << field_name + @unique_indices << field_name if options[:unique] end def self.indices @indices + end + + def self.unique_indices + @unique_indices end # Finds an array of records which match the given conditions. This method is # much faster when all the fields given are indexed. def self.where(options = {})