类的名称是类的名称name
:
module Foo
def whoami
self.name
end
end
class Bar
extend Foo
end
p Bar.whoami #=> "Bar"
我不会创建一些字符串;我会为每个类创建一个新的设置哈希:
module Settings
def setting(name,value=:GIT_DA_VALUE)
@_class_settings ||= {} # Create a new hash on this object, if needed
if value==:GIT_DA_VALUE
@_class_settings[name]
else
@_class_settings[name] = value
end
end
end
class Foo
extend Settings
end
class Bar
extend Settings
end
Foo.setting(:a,42)
p Foo.setting(:a), #=> 42
Foo.setting(:b), #=> nil
Bar.setting(:a) #=> nil (showing that settings are per class)
...否则我将由类对象本身索引单个全局哈希(如果需要):
module Settings
# A single two-level hash for all settings, indexed by the object
# upon which the settings are applied; automatically creates
# a new settings hash for each object when a new object is peeked at
SETTINGS = Hash.new{ |h,obj| h[obj]={} }
def setting(name,value=:GIT_DA_VALUE)
if value==:GIT_DA_VALUE
SETTINGS[self][name]
else
SETTINGS[self][name] = value
end
end
end
# Usage is the same as the above; settings are unique per class