classAppSetting<ActiveRecord::Baseattr_accessible:value,:listattr_accessor:listafter_initialize:initbefore_save:covert_formatvalidates_inclusion_of:singleton_guard,:in=>[0]defcovert_formatself.value=self.list.to_jsonenddefload_listbeginself.list=JSON.parse(self.value)rescueJSON::ParserError=>msglogger.error("AppSetting: Can not load list!")self.list={}endenddef[](key)self.list[key]enddef[]=(key,value)self.list[key]=valueself.saveenddefinitself.value||="{}"self.list||=load_listself.singleton_guard||=0end# class method# singletondefAppSetting.instancebeginfind(1)rescueActiveRecord::RecordNotFoundrow=AppSetting.newrow.singleton_guard=0row.save!rowendenddefAppSetting.[](key)AppSetting.instance[key]enddefAppSetting.[]=(key,value)AppSetting.instance[key]=valueendend
3.为了方便 AppSetting 的使用,重载了操作符 ‘[]’, ‘[]=’
4.使用示例
1234
# set site_name to "example site". AppSetting will save when set the valueAppSetting["site_name"]="example site"# get "site_name" and assign it to variable site_namesite_name=AppSetting["site_name"]