Module: AttributeHelper::ClassMethods
- Defined in:
- lib/wakame/util.rb
Instance Method Summary collapse
- #attr_attributes ⇒ Object
- #def_attribute(name, *args) ⇒ Object
- #get_attr_attribute(attr_name) ⇒ Object
- #merged_attr_attributes ⇒ Object
-
#update_attribute(name, v) ⇒ Object
Update attr_attributes[:default] value.
Instance Method Details
#attr_attributes ⇒ Object
206 207 208 |
# File 'lib/wakame/util.rb', line 206 def attr_attributes @attr_attributes ||= {} end |
#def_attribute(name, *args) ⇒ Object
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 |
# File 'lib/wakame/util.rb', line 236 def def_attribute(name, *args) attr = begin if args.size == 0 {:default=>nil} else case args[0] when Hash args[0].dup else {:default=>args[0]} end end end (attr_attributes[name.to_sym] ||= {}).merge!(attr) attr = self.merged_attr_attributes if attr[:read_only] if self.respond_to? "#{name}=".to_sym class_eval %Q{ undef_method "#{name}=".to_sym } end else class_eval <<-__E__ def #{name}=(v) @#{name}=v end public :#{name}= __E__ end class_eval <<-__E__ def #{name} if @#{name}.nil? a = self.class.get_attr_attribute(:#{name}) if a defval = a[:default] @#{name} = case defval when Proc defval.call(self) else defval.dup rescue defval end end end @#{name} end public :#{name} __E__ end |
#get_attr_attribute(attr_name) ⇒ Object
222 223 224 |
# File 'lib/wakame/util.rb', line 222 def get_attr_attribute(attr_name) merged_attr_attributes[attr_name] end |
#merged_attr_attributes ⇒ Object
210 211 212 213 214 215 216 217 218 219 220 |
# File 'lib/wakame/util.rb', line 210 def merged_attr_attributes hash = {} deep_merge = proc {|key,v1,v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &deep_merge) : v2} self.ancestors.reverse.each { |klass| next unless klass.include?(AttributeHelper) hash.merge!(klass.attr_attributes, &deep_merge) } hash end |
#update_attribute(name, v) ⇒ Object
Update attr_attributes[:default] value. This works for existing name key.
228 229 230 231 232 233 234 |
# File 'lib/wakame/util.rb', line 228 def update_attribute(name, v) attr_attr = get_attr_attribute(name.to_sym) raise "No such defined attribute: #{name}" if attr_attr.nil? attr_attributes[name.to_sym] ||= {} attr_attributes[name.to_sym].merge!({:default=>v}) name end |