Metafun
A library for extending Ruby native metaprogramming capabilities
Install
gem install
Usage
Delegator
Delegator delegates easily methods from a given module into a target object. The delegated methods have private access to the original module properties. Its main purpose is to easy deploy DSLs
require "metafun/delegator"
extend Metafun::Delegator
module TheModule
@@local_var = "Hello delegation"
def self.take_action
@@local_var
end
end
delegate TheModule, :take_action
puts take_action # At this stage, this is exactly the same
# as calling TheModule.take_action
Why Delegator and not just include TheModule
? Because for most non-trivial DSLs, you want to keep an internal state in the module object, and is not a good idea to store the internal state on Object:main. You might as well wish to disable the DSL API to stop pollution of the default namespace, and it should be possible to do that transparently.
Inspired in Sinatra’s Delegator.
Switch Maker
Switch Maker makes a friendly semantic switch out of a symbol. For example
require "metafun/switchmaker"
class Klass
switch :cache
end
# Default is false
Klass.cache? # > false
# This is how you set it. It accepts :on/:off, :yes/:no,
# true/false, 1/0...
Klass.cache :on
Klass.cache? # > true
# ... and procs
Klass.cache lambda { false }
Klass.cache? # > false
Kitchen List
-
Delegator should work aswell with Singletons and make-instance-and-die classes.
-
Make specs instead of features
-
-
Switch Maker should accept blocks, not just procs
Copyright 2011 Xavier Via
GPL License