1. Ruby!
What’s a Metaclass?
Tommy xiao’s assemble
twitter: @xds2000
understand how Ruby’s metaclass works
2. have no idea?
According to wikipedia:
In object-oriented programming, a
metaclass is a class whose instances are
classes. Just as an ordinary class defines
the behavior of certain objects, a
metaclass defines the behavior of certain
classes and their instances.
3. Get two things
(1) instances of metaclasses are classes
(2) the metaclass defines the behavior of a class.
4. So Singleton classes
aren’t Metaclasses?
In general, instances of singleton classes are
regular objects, not classes. Singleton classes
define the behavior of regular objects, not
class objects.
5. Too Complicated?
Not Understood?
In Ruby:
Not all singleton classes are metaclasses. Only
singleton classes of classes are metaclasses.
And then only weak, partial metaclasses.
6. in real coding,i will see..
eval instance_eval class_eval
class << self; self; end
Shit! i have no idea. :-(
7. use code snippets
Foo = Class.new
Foo.class_eval do
def bar
"bar"
end
end
Foo.instance_eval do
def baz
"baz"
end
end
Foo.bar #=> undefined method ‘bar’ for Foo:Class
Foo.new.bar #=> "bar"
Foo.baz #=> "baz"
Foo.new.baz #=> undefined method ‘baz’ for #<Foo:0x7dce8>
8. matz = Object.new
def matz.speak
"Place your burden to machine's
shoulders"
end
What’s going on here is that we’re adding the speak
method to matz’s metaclass, and the matz object
inherits from its metaclass and then Object.
9. Key Concepts
the metaclass is invisible in Ruby
atz = Object.new
def matz.speak
"Place your burden to machine's
shoulders"
end
matz.class #=> Object
In fact, matz’s “class” is its invisible metaclass.
10. Key Concepts
get access to the metaclass
metaclass = class << matz; self; end
metaclass.instance_methods.grep(/speak/) #=> ["speak"]
it seems as though there are so many rules.
11. in fact only single concept
control over the self in a
given part of the code.
12. use sample code to prove our views
# use self.def define class method
Dragon.class_eval do # use instance_eval
is same effect(why?)
def self.foo
puts "bar"
end
end
Dragon.foo # bar
because self is which evaluates to
receiver(Dragon)
13. Dragon.instance_eval do
define_method("foo2") { puts "bar" }
end
Dragon.foo2 rescue puts "fails" #
undefined method(why?)
implicit self, which evaluates to receiver(Dragon)
so here actually define instance method.
14. metaclass = (class << Dragon; self; end)
metaclass.instance_eval do # use
class_eval is same effect(why?)
define_method("foo") { puts "bar" }
end
Dragon.foo
because self is which evaluates to
receiver(metaclass)
15. Dragon.class.instance_eval do # use
class_eval is ok
define_method("foo") { puts "bar" }
end
Dragon.foo # bar
String.foo # bar, all class pollut!! bad
idea!!
because self is which evaluates to
receiver(Class)