Author Liubin http://www.ruby-cn.org/ IOC (Inversion of Control), is also the control reversal of Chinese, sometimes called Di (Dependency Injection), depending on injection. In Java, there are many containers, such as Spring. Such containers are also present in Ruby, such as NEEDLE and COPLAND, the authors of these two works are Jamis Buck. About what is di / oc, you can see Classic Articles: Martin Fowler
Inversion of Control and The Dependency Injection Pattern.
Features:
Support for Type 2 and Type 3 (constructor) to provide AOP hooks to provide AOP hook implementation interception hierarchical namespace lifecycle management (delay initialization, single case mode, etc.)
An example: 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 Module_Function: Register_Services
The class above the end is some implementation classes, which can be called by the following code: Require 'Needle'Require' Calc '
REG = Needle :: registry.newcalculator.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) Endend
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): # {CACC.DIVIDE (8, 5)} "PUTS" SIN (PI / 3): # {CACC.SIN (Math :: PI / 3)} "PUTS" add (1, -6): # {CALC.ADD (1, -6)} "
Putsputs "'add' invoked # {$ add_count} Times" Reference: 1.Needle Home: http://needle.rubyforge.org2.dependency inJection In Ruby: http: //onestepback.org/index.cgi/tech/tech/tech/tech/tech/tech/tech/tech/tech Ruby / dependencyinjectioninruby.rdoc