lib/woyo/world/attributes.rb in woyo-world-0.0.1 vs lib/woyo/world/attributes.rb in woyo-world-0.0.2

- old
+ new

@@ -3,26 +3,46 @@ module Attributes module ClassMethods - def attributes *attrs - @attributes ||= [] # class instance variable in ClassMethods scope - return @attributes if attrs.empty? - @attributes = attrs # todo: allow additions to existing attributes - @attributes.each do |attr| - class_eval(" - def #{attr}= arg - attributes[:#{attr}] = @#{attr} = arg - end - def #{attr}(arg=nil) - if arg.nil? - @#{attr} + def create_attribute_methods_with_define_method attr, default = nil + define_method "#{attr}=" do |arg| + attributes[attr] = arg + end + define_method attr do |arg = nil| + if arg.nil? + unless attributes.has_key? attr + if default.respond_to? :call + if default.arity == 0 + attributes[attr] = default.call # todo: is this the same as ? ... instance_eval &default + else + attributes[attr] = default.call(self) + end else - self.#{attr} = arg + attributes[attr] = default end end - ") + attributes[attr] + else + attributes[attr] = arg + end + end + end + + def attributes *attrs + @attributes ||= [] + return @attributes if attrs.empty? + attrs.each do |attr| + if attr.kind_of? Hash + attr.each do |attr_sym,default_value| + @attributes << attr_sym + create_attribute_methods_with_define_method attr_sym, default_value + end + else + @attributes << attr + create_attribute_methods_with_define_method attr + end end end end