一个例子:
cacl.rb
module Calculator
class Adder
def compute( a, b )
a.to_f + b.to_f
end
end
class Subtractor
def compute( a, b )
a.to_f - b.to_f
end
end
class Multiplier
def compute( a, b )
a.to_f * b.to_f
end
end
class Divider
def compute( a, b )
a.to_f / b.to_f
end
end
class Sine
def compute( a )
Math.sin( a )
end
end
class Calculator
def initialize( operations )
@operations = operations
end
def method_missing( op, *args )
if @operations.has_key?(op)
@operations[op].compute( *args )
else
super
end
end
def respond_to?( op )
@operations.has_key?(op) or super
end
end
def register_services( registry )
registry.namespace! :calc do
namespace! :operations do
add { Adder.new }
subtract { Subtractor.new }
multiply { Multiplier.new }
divide { Divider.new }
sin { Sine.new }
end
calculator { Calculator.new( operations ) }
end
end
module_function :register_services
end
上面的类是一些实现类,可以被下面代码调用:
require 'needle'
require 'calc'
reg = Needle::Registry.new
Calculator.register_services( reg )
reg.calc.define! do
intercept( :calculator ).
with! { logging_interceptor }.
with_options( :exclude=>%w{divide multiply add} )
$add_count = 0
operations.intercept( :add ).
doing do |chain,ctx|
$add_count += 1
chain.process_next( ctx )
end
end
calc = reg.calc.calculator
puts "add(8,5): #{calc.add( 8, 5 )}"
puts "subtract(8,5): #{calc.subtract( 8, 5 )}"
puts "multiply(8,5): #{calc.multiply( 8, 5 )}"
puts "divide(8,5): #{calc.divide( 8, 5 )}"
puts "sin(pi/3): #{calc.sin( Math::PI/3 )}"
puts "add(1,-6): #{calc.add( 1, -6 )}"
puts
puts "'add' invoked #{$add_count} times"
参考资料:
1.Needle主页:http://needle.rubyforge.org
2.Dependency Injection in Ruby :http://onestepback.org/index.cgi/Tech/Ruby/DependencyInjectionInRuby.rdoc