require 'pervasives' module Attributes VERSION = '3.5.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, banger = "@#{ name }", "#{ name }", "#{ name }=", "#{ name }?", "#{ name }!" define_method(setter) do |value| __pervasive__('instance_variable_set', ivar, value) end define_method(getter) do |*value| unless value.empty? __pervasive__('send', setter, value.shift) else defined = __pervasive__('instance_eval', "defined? #{ ivar }") __pervasive__('send', setter, __pervasive__('instance_eval', &init)) unless defined __pervasive__('instance_variable_get', ivar) end end define_method(banger) do __pervasive__('send', setter, __pervasive__('instance_eval', &init)) __pervasive__('instance_variable_get', ivar) end alias_method query, getter (attributes << name.to_s).uniq! attributes end else begin __attribute_list__ rescue NameError singleton_class = class << self self end klass = self singleton_class.module_eval do attribute_list = [] define_method('attribute_list'){ klass == self ? attribute_list : raise(NameError) } alias_method '__attribute_list__', 'attribute_list' end __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