You can define methods in an anonymous module by passing the Module.new block, make each instance method in the module private and extend your class with the module
class Class def define_private_class_methods(&block) mod = Module.new(&block) mod.instance_methods.each { |m| mod.send(:private, m) } extend(mod) end end
This has the desired result:
class Person define_private_class_methods do def method_one 123 end end end Person.send(:method_one)
... and as a bonus, it also gives you the super method: (perhaps a little used)
class Person def self.method_one super * 2 end end Person.method_one #=> 456
Of course, you do not need to use extend , you can also define methods manually manually:
class Class def define_private_class_methods(&block) mod = Module.new(&block) mod.instance_methods.each do |m| define_singleton_method(m, mod.instance_method(m)) private_class_method(m) end end end
An important module is an anonymous module, so you have a (temporary) container for defining methods.
source share