lib/direction.rb in direction-0.0.3 vs lib/direction.rb in direction-0.0.4

- old
+ new

@@ -13,34 +13,39 @@ # # This will define methods on instances that forward to the # provided receiver while enforcing encapsulation of the # relationship between objects. module Direction + + # Forward messages and return self, protecting the encapsulation of the object def command(options) - method_defs = [] - options.each_pair do |key, value| - Array(key).map do |command_name| - method_defs.unshift %{ - def #{command_name}(*args, &block) - #{value}.__send__(:#{command_name}, *args, &block) - self - end - } + Direction.define_methods(self, options) do |message, accessor| + %{ + def #{message}(*args, &block) + #{accessor}.__send__(:#{message}, *args, &block) + self end + } end - self.class_eval method_defs.join(' '), __FILE__, __LINE__ end + # Forward messages and return the result of the forwarded message def query(options) + Direction.define_methods(self, options) do |message, accessor| + %{ + def #{message}(*args, &block) + #{accessor}.__send__(:#{message}, *args, &block) + end + } + end + end + + def self.define_methods(mod, options) method_defs = [] - options.each_pair do |key, value| - Array(key).map do |command_name| - method_defs.unshift %{ - def #{command_name}(*args, &block) - #{value}.__send__(:#{command_name}, *args, &block) - end - } + options.each_pair do |method_names, accessor| + Array(method_names).map do |message| + method_defs.unshift yield(message, accessor) end end - self.class_eval method_defs.join(' '), __FILE__, __LINE__ + mod.class_eval method_defs.join("\n"), __FILE__, __LINE__ end end