I am learning how to design a DSL by using const_missing, but I face a
problem on getting class name:
I am not sure what you are attempting. But you should keep these facts in mind:
1. You cannot change inheritance of a class after creation.
2. A class has a name only after const assignment.
11:11:21 Temp$ ruby19 -e 'c=Class.new;p c, c.name;A=c;p c, c.name'
#<Class:0x1005309c>
nil
A
"A"
11:12:50 Temp$ ruby19 -e 'c=Class.new;p c,
c.name;Object.const_set("A",c);p c, c.name'
#<Class:0x1005304c>
nil
A
"A"
class Drawing
def initialize(&block)
instance_eval(&block)
end
def self.const_missing(constant)
klass = Class.new do
def self.<(super_klass)
puts "#{self.name} inherits from #{super_klass.name}"
end
Bad idea IMHO: Class#< is defined already with particular semantics
(inheritance check):
11:13:59 Temp$ ruby19 -e 'p Array < Enumerable'
true
Also, as I said, you cannot change inheritance after creation of a class.
def self\.\-\(association\_klass\)
puts "\#\{self\.name\} has association with
#{association_klass.name}"
end
end
const_set(constant, klass)
end
end
Drawing.new do
You are creating an instance of Drawing while you probably rather want
constants Student, Person etc. set in class Drawing.
Student < Person
Student - Courses
end
Output:
inherits from
has association with
Expected output:
Student inherits from Person
Student has association with Courses
Try this to see what's happening:
class Drawing
def initialize(&block)
instance_eval(&block)
end
def self.const_missing(constant)
p [self, constant]
klass = Class.new do
def self.<(super_klass)
# puts "#{self.name} inherits from #{super_klass.inspect}"
printf "%p < %p\n", self, super_klass
end
def self.-(association_klass)
# puts "#{self.name} has association with #{association_klass.inspect}"
printf "%p - %p\n", self, association_klass
end
end
def klass.x(cl)
printf "%p x %p\n", self, cl
end
const_set(constant, klass)
end
end
Drawing.new do
Student < Person
Student - Courses
Student.x Foo
end
p Drawing.constants
class Drawing
Student < Person
Student - Courses
Student.x Foo
end
p Drawing.constants
Kind regards
robert
···
On Tue, Jan 4, 2011 at 6:29 PM, Samnang Chhun <samnang.chhun@gmail.com> wrote:
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/