lib/couchpillow/document.rb in couchpillow-0.2.0 vs lib/couchpillow/document.rb in couchpillow-0.3.0
- old
+ new
@@ -23,10 +23,11 @@
@data[:created_at] = Time.now.utc
@data[:updated_at] = Time.parse(@data[:updated_at]) if @data[:updated_at]
raise TypeError if @data[:_type] && @data[:_type] != self.class._type
@data[:_type] = self.class._type
+ rename!
end
def [] key
@data[key.to_s.to_sym]
@@ -111,10 +112,19 @@
@data.has_key?(k) && method.call(@data[k])
end
end
+ def rename!
+ self.class.rename_keys.each do |from, to|
+ @data.has_key?(from) and
+ @data[to] = @data[from] and
+ @data.delete(from)
+ end
+ end
+
+
def self.get id
new(CouchPillow.db.get(id), id)
end
@@ -126,12 +136,14 @@
def self._type
@type
end
- def self.design_doc value
- @ddoc = value
+ # Rename an existing key to a new key. This is invoked right after initialize.
+ #
+ def self.rename from, to
+ rename_keys << [from.to_s.to_sym, to.to_s.to_sym]
end
# Validate the presence of a particular key, and the value of that key
# cannot be nil.
@@ -139,19 +151,31 @@
def self.validate_presence key
validate key, "is missing", PRESENCE_LAMBDA
end
+ # Validate the type of a particular key.
+ #
+ def self.validate_type key, type
+ validate key, "is not the correct type. Expected a #{type}", lambda { |v| v.is_a? type }
+ end
+
+
# Validate the presence of a particular key using a custom validation method.
# Implies the Document must contain the key.
#
def self.validate key, message, block
raise ValidationError, "Provide validation method for key #{key}" unless block
validate_keys << [key, message, block]
end
private
+
+
+ def self.rename_keys
+ @rename_keys ||= []
+ end
def self.validate_keys
@validate_key ||= []
end