A decorator object that provides the DSL-ish interface to the various Config
objects. It derives its interface on the fly from columns of the class it's created with and a DSLMethods mixin if the target class defines one.
The decorated object
Create an instance of the specified targetclass
using the specified opts
as initial values. The first pair of opts
will be used in the filter to find any previous instance and delete it.
# File lib/mongrel2/config/dsl.rb, line 24
def initialize( targetclass, opts={} )
self.log.debug "Wrapping a %p" % [ targetclass ]
@targetclass = targetclass
# Use the first pair as the primary key
unless opts.empty?
first_pair = Hash[ *opts.first ]
@targetclass.filter( first_pair ).destroy
end
@target = @targetclass.new( opts )
self.decorate_with_column_declaratives( @target )
self.decorate_with_custom_declaratives( @targetclass )
end
Add a declarative singleton method for the columns of the adapted_object
.
# File lib/mongrel2/config/dsl.rb, line 56
def decorate_with_column_declaratives( adapted_object )
columns = adapted_object.columns
self.log.debug " decorating for columns: %s" % [ columns.map( &:to_s ).sort.join(', ') ]
columns.each do |colname|
# Create a method that will act as a writer if called with an
# argument, and a reader if not.
method_body = Proc.new do |*args|
if args.empty?
self.target.send( colname )
else
self.target.send( "#{colname}=", *args )
end
end
# Install the method
self.singleton_class.send( :define_method, colname, &method_body )
end
end
Mix in methods defined by the “DSLMethods” mixin defined by the class of the object being adapted.
# File lib/mongrel2/config/dsl.rb, line 80
def decorate_with_custom_declaratives( objectclass )
return unless objectclass.const_defined?( :DSLMethods )
self.singleton_class.send( :include, objectclass.const_get(:DSLMethods) )
end
# File lib/mongrel2/config/dsl.rb, line 50
def singleton_class
class << self; self; end
end