一類的名稱是一類的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
有這麼許多方法可以做到這一點(其中大部分與我們所擁有的不同)。你的硬性要求是什麼?你必須有一個使用字符串的散列嗎? – Phrogz 2012-04-24 20:45:23
@Progrog:硬性要求。是能夠將ruby對象序列化爲一個數據庫,可以在每個類(每個模型)的基礎上訪問。我正在使用gem「rails-settings-cached」,但可能有很多方法。我問這個問題主要是因爲我想了解背後的邏輯。 – jforberg 2012-04-26 10:18:33