3 ms·
OK. Like so: module SpecialBehavioursForClass def extended(klass) klass.class_eval { ...do anything you like to classes including these behaviours as tho
by mjw 18y ago
OK. Like so:
module SpecialBehavioursForClass
def extended(klass)
klass.class_eval { ...do anything you like to classes including these behaviours as though you're in their class definition block itself... }
end
def special_class_method
...
end
def give_this_class_an_attribute(x)
attr_accessor :x
end
end
then
Class MySpecialClass
extend SpecialBehavioursForClass
give_this_class_an_attribute :abc
end
(note how there's already a class method 'attr_accessor' which does this - but just to reinforce how you'd go about making something similar yourself)
then:
MySpecialClass.is_a?(SpecialBehavioursForClass)
returns true.
However, MySpecialClass.class == Class
it's not actually an instance of a metaclass as these don't exist in Ruby.
You can achieve the exact same things though, using Modules, class methods, and the .inherited / .included / .extended callbacks.
- mjw 18y agoSorry it bolloxed my formatting. Note to these people: tell us how your code formatting works, somewhere near the goddamn input field