lib/blendris/model.rb in blendris-0.5 vs lib/blendris/model.rb in blendris-0.6
- old
+ new
@@ -38,47 +38,26 @@
# to ensure that all objects that represent the same key return the same id.
def id
Digest::SHA1.hexdigest key
end
- # TODO: Create the methods in the initialize method instead of depending
- # on method_missing to dispatch to the correct methods. This will make
- # these objects better for mocking and stubbing.
- def method_missing(method_sym, *arguments)
- (name, setter) = method_sym.to_s.scan(/(.*[^=])(=)?/).first
-
- if node = redis_symbol(name)
- if setter
- if self.class.local_parameters.find {|p| p.kind_of?(Symbol) && p.to_s == name}
- raise BlendrisCannotSetKeyValue.new(name)
- end
-
- return node.set(*arguments)
- else
- return node.get
- end
- end
-
- super
- end
-
# Look up the given symbol by its name. The list of symbols are defined
# when the model is declared.
- # TODO: This can also probably go away when I remove the need for method_missing.
- def redis_symbol(name)
+ def [](name)
+ name = name.to_s
+
subkey = self.subkey(name)
- options = self.class.redis_symbols[name.to_s]
+ options = self.class.redis_symbols[name]
return unless options
on_change = lambda { self.fire_on_change_for name }
options = options.merge(:model => self, :on_change => on_change)
options[:type].new subkey, options
end
- alias :[] :redis_symbol
# Calculate the key to address the given child node.
def subkey(child)
sanitize_key "#{self.key}:#{child}"
end
@@ -134,11 +113,11 @@
redis.sadd index_key, key
obj = new(key, :verify => false)
parameters.each_with_index do |parm, i|
- obj.redis_symbol(parm).set args[i]
+ obj[parm].set args[i]
end
obj
end
@@ -154,11 +133,11 @@
def each
RedisSet.new(index_key).each {|k| yield new(k)}
end
def index_key
- "index:model:#{self.name}"
+ "blendris:index:model:#{self.name}"
end
# Defines a new data type for Blendris:Model construction.
def type(name, klass)
(class << self; self; end).instance_eval do
@@ -166,10 +145,22 @@
varname = args.shift.to_s
options = args.shift || {}
options[:type] = klass
redis_symbols[varname] = options
+
+ # Declare the getter for this field.
+ define_method(varname) do
+ self[varname].get
+ end
+
+ # Declare the setter for this field, if it is not a key field.
+ unless local_parameters.find {|p| p.to_s == varname}
+ define_method("#{varname}=") do |value|
+ self[varname].set value
+ end
+ end
end
end
end
# Variables stored in the Redis database.
@@ -178,17 +169,9 @@
end
# Parameters used when creating a new copy of this model.
def local_parameters
@local_parameters ||= []
- end
-
- # Take a value and attempt to make it fit the given field.
- def cast_value(symbol, value)
- options = redis_symbols[symbol.to_s]
- raise ArgumentError.new("#{self.name} is missing its #{symbol}") unless options
-
- options[:type].cast_to_redis value, options
end
# Define a block to call when one of the given symbol values changes.
def on_change(*symbols, &block)
symbols.flatten!