Syntactic sugar for common idiom

  • Thread starter George Moschovitis
  • Start date
G

George Moschovitis

Hello everyone,

the following idiom is very useful:

module MyModule
def self.append_features(base)
super; base.extend(ClassMethods)
end

module ClassMethods

def a_class_method
puts 'class'
end
end
end

class MyClass
include MyModule
end

MyClass.a_class_method # => 'class'

I think it would be a good idea to have some form of syntactic sugar
for this idiom in Ruby 1.9/2.0

Any ideas ?

-g.
 
J

Joel VanderWerf

George said:
Hello everyone,

the following idiom is very useful:

module MyModule
def self.append_features(base)
super; base.extend(ClassMethods)
end

module ClassMethods

def a_class_method
puts 'class'
end
end
end

class MyClass
include MyModule
end

MyClass.a_class_method # => 'class'

I think it would be a good idea to have some form of syntactic sugar
for this idiom in Ruby 1.9/2.0

Any ideas ?

Don't wait :)

class Module
private
def when_included_provide_class_methods(&bl)
unless @__class_methods_module
@__class_methods_module = Module.new

def self.append_features(base)
super
base.extend(@__class_methods_module)
end
end

@__class_methods_module.class_eval(&bl)
end
end

module MyModule
when_included_provide_class_methods {
def a_class_method
puts 'class'
end
}
end

class MyClass
include MyModule
end

MyClass.a_class_method # => 'class'
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,710
Latest member
bernietqt

Latest Threads

Top