Robert Klemme
2/23/2005 9:02:00 AM
"Iwan van der Kleyn" <none@none.net> schrieb im Newsbeitrag
news:421B8C3F.8010300@none.net...
>
> >>So therefore my question: how would I be able to add class methods to
a
> >>class through a Module?
>
> > module Validation
> > def self.included(cl)
> > def cl.validate_members(*a) puts "validate_members: #{a.inspect}"
end
> > def cl.rule_set(set) puts "rule_set: #{set.inspect}" end
> > end
> > end
>
> Works like a charm. Thanks! This one I completely overlooked in the
> Pickaxe book.
Additional note: if you want to be more flexible and more efficient you
can do this:
module Validation
module ClassMethods
def validate_members(*a) puts "validate_members: #{a.inspect}" end
def rule_set(set) puts "rule_set: #{set.inspect}" end
end
def self.included(cl) cl.extend ClassMethods end
end
>> class Test
>> include Validation
>> validate_members :attr1, :attr2
>> rule_set :strict
>> end
validate_members: [:attr1, :attr2]
rule_set: :strict
=> nil
>> class <<Test; ancestors end
=> [Validation::ClassMethods, Class, Module, Object, Kernel]
Advantage is that you have only one definition of those class methods plus
you can change them later.
And if you want to make that recursively work, just do this:
module Validation
module ClassMethods
def validate_members(*a) puts "validate_members: #{a.inspect}" end
def rule_set(set) puts "rule_set: #{set.inspect}" end
# this is the crucial bit:
def inherited(cl) cl.extend ClassMethods end
end
def self.included(cl) cl.extend ClassMethods end
end
>> class Test
>> include Validation
>> validate_members :attr1, :attr2
>> rule_set :strict
>> end
validate_members: [:attr1, :attr2]
rule_set: :strict
=> nil
>> class DerivedTest < Test
>> validate_members :attr1, :attr2
>> rule_set :strict
>> end
validate_members: [:attr1, :attr2]
rule_set: :strict
=> nil
Kind regards
robert