Is it possible to add a core method to the Module class in Ruby? I want to do something like this (messed around with the idea yesterday, just whipped this together in a second):
module MyModule
base do
has_many :something
end
end
# implementation, doesn't work though... reason for the question
Module.class_eval do
def self.base(&block)
class_eval do
def self.included(base)
base.class_eval(&block)
end
end
end
end
If I create a module, I can't access that method:
$ module User; end
$ User.base
NoMethodError: undefined method `base' for User:Module
Any ways to do this?
Update
This works! Thanks @Jörg W Mittag. Makes it much easier to read for Rails has_many
and such:
class Module
def base(&block)
metaclass = class << self; self; end
# add the method using define_method instead of def x.say so we can use a closure
metaclass.send :define_method, :included do |base|
base.class_eval(&block) unless block.nil?
base.class_eval <<-EOF
extend #{name}::ClassMethods
include #{name}::InstanceMethods
EOF
end
block
end
end
Like this example:
module UserRoleBehavior
base do
has_many :user_roles
has_many :roles, :through => :user_roles
end
module ClassMethods
# ...
end
module InstanceMethods
# ...
end
end
class User < ActiveRecord::Base
include UserRoleBehavior
end
Cheers!