Author liubin http://www.ruby-cn.org/
IOC (inversion of control), that is, the inversion of control in Chinese, is also called di (dependency injection), that is, dependent injection. In Java, there are many such containers, such as spring. There are also such containers in ruby, such as needle and Copland. The authors of both works are jamis buck. For more information about di/IOC, see Martin Fowler's Inversion of control and the dependency injection pattern.
Features:
- Supports injection of type 2 (setter) and Type 3 (constructor ).
- Provide AOP hooks for service methods to implement Interception
- Hierarchical namespace
- Lifecycle Management (delayed initialization, Singleton mode, etc)
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 ()
Math. Sin ()
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
The above classes are implementation classes that can be called by the following code:
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"
References:
1. Needle home page: http://needle.rubyforge.org
2. Dependency injection in Ruby: http://onestepback.org/index.cgi/Tech/Ruby/DependencyInjectionInRuby.rdoc