| new | -> | postinitialize_new |
Creates a class-variable attribute that can be accessed both on an instance and class level.
NOTE This used to be a Module method. But turns out it does not work as expected when included. The class-level method is not carried along. So it is now just a Class method. Accordingly, mattr has been deprecated.
CREDIT: David Heinemeier Hansson
Creates a class-variable attr_accessor that can be accessed both on an instance and class level.
class MyClass
cattr_accessor :a
end
MyClass.a = 10
MyClass.a #=> 10
mc = MyClass.new
mc.a #=> 10
CREDIT: David Heinemeier Hansson
Creates a class-variable attr_reader that can be accessed both on an instance and class level.
class MyClass
@@a = 10
cattr_reader :a
end
MyClass.a #=> 10
MyClass.new.a #=> 10
CREDIT: David Heinemeier Hansson
Creates a class-variable attr_writer that can be accessed both on an instance and class level.
class MyClass
cattr_writer :a
def a
@@a
end
end
MyClass.a = 10
MyClass.a #=> 10
MyClass.new.a = 29
MyClass.a #=> 29
CREDIT: David Heinemeier Hansson
For Class, class_extend is the same as class_eval. The alternative is to "undef_method :class_extend", but this seems uneccessarily limited.
List all descedents of this class.
class X ; end class A < X; end class B < X; end X.descendents #=> [A,B]
NOTE: This is a intesive operation. Do not expect it to be super fast.
Prepend an "aspect module" to a class.
class Firetruck
def put_out_fire(option)
"Put out #{option}"
end
end
module FastFiretruck
def put_out_fire(option)
super("very #{option}!")
end
end
Firetruck.prepend(FastFiretruck)
ft = Firetruck.new
ft.put_out_fire('fast') #=> "Put out very fast!"
Implementation of this method has some limitations, in that it works by overriding new and allocate.
CREDIT: Trans
TODO: Perhaps rename this to preallocate, b/c of the way it works. It is not really a clean prepend, like that of Module#prepend.