module Attributes VERSION = '3.3.0' def self.version() VERSION end def attributes *a, &b unless a.empty? hashes, names = a.partition{|x| Hash === x} names_and_defaults = {} hashes.each{|h| names_and_defaults.update h} names.flatten.compact.each{|name| names_and_defaults.update name => nil} names_and_defaults.each do |name, default| init = b || lambda { default } ivar, getter, setter, query = "@#{ name }", "#{ name }", "#{ name }=", "#{ name }?" define_method(setter) do |value| instance_variable_set ivar, value end define_method(getter) do |*value| unless value.empty? send setter, value.shift else defined = instance_eval "defined? #{ ivar }" send setter, instance_eval(&init) unless defined instance_variable_get ivar end end alias_method query, getter (attributes << name).uniq! attributes end else begin __attribute_list__ rescue NameError singleton_class = class << self self end singleton_class.module_eval <<-code attribute_list = [] define_method('attribute_list'){ attribute_list } alias_method '__attribute_list__', 'attribute_list' code __attribute_list__ end end end %w( __attributes__ __attribute__ attribute ).each{|dst| alias_method dst, 'attributes'} end class Object def attributes *a, &b sc = class << self self end sc.attributes *a, &b end %w( __attributes__ __attribute__ attribute ).each{|dst| alias_method dst, 'attributes'} end class Module; include Attributes; end