Parametric Mixin
Parametric Mixins provides parameters for mixin modules. Module parameters can be set at the time of inclusion or extension using Module#[] method, then parameters can be accessed via the mixin_parameters method.
module MyMixin include Paramix def hello puts "Hello from #{mixin_parameters[MyMixin][:name]}!" end end class MyClass include Mixin[:name => 'Ruby'] end m = MyClass.new m.hello -> 'Hello from Ruby!'
You can view the full set of parameters via the mixin_parameters class method, which returns a hash keyed on the included modules.
MyClass.mixin_parameters #=> {MyMixin=>{:name=>'Ruby'}} MyClass.mixin_parameters[MyMixin] #=> {:name=>'ruby'}
The include Praamix is equivalent to:
def [](parameters) Paramix.new(self, parameters) end
Paramix.new can also take a block that injects code into the class or module including the parametric mixin. This is useful as an alternative to using the included callback for creating dynamic mixins.. For example:
def self.[](parameters) Paramix.new(self, parameters) do attr_accessor mixin_params[MyMixin][:name] end end
As opposed to:
module Mixin def self.included(base) base.class_eval do attr_accessor mixin_params[MyMixin][:name] end end end
[ show source ]
# File lib/more/facets/paramix.rb, line 107 def self.append_features(base) (class << base; self; end).class_eval do define_method(:[]) do |parameters| # TODO until 1.9 no &block Delegator.new(base, parameters) end end end
It you want to define the module‘s ::[] method by hand. You can use Paramix.new instead of Paramix::Delegator.new.
[ show source ]
# File lib/more/facets/paramix.rb, line 118 def self.new(delegate_module, parameters={}, &base_block) Delegator.new(delegate_module, parameters, &base_block) end