require 'mega/preinitialize' class Module # Shorthand notation for creating attributes. # # attr :r, :w!, :a= # # is equivalent to # # attr_reader :r # attr_writer :w # attr_accessor :a # # A pure writer notation is not provided b/c it is so rare. # A "tester" shorthand is also provided (see #attr_checker) # # attr :q? # # translates into # # def q? # @q ? true : @q # end #-- # :NOTE: Add this? # def q!(b=true) # @q = (b ? true : b) # end #++ # # Default values are also now possible using a hash. # # cattr :a, :b => 10 # # In this example @b will be initialized to 10 prior to running the # initilaize routine. Attributes with default values must always # appear at the end of the list. # # Compatability is maintained with the old version of #attr. # So it is still possible to write: # # attr :a, true # # It has been expanded to allow multiple names as well: # # attr :a, :b, :c, true # def attr(*args) # Allows compatibility with old definition, while also # extending the capabilites to allow multiple parameters. if TrueClass === args.last or FalseClass === args.last or NilClass === args.last if args.pop args.concat( args.collect{ |a| a = a.to_s.strip case a.slice(-1,1) when '=' a[0..-2] when '?' "#{a[0..-2]}=" else "#{a}=" end } ) end end # for default values hargs = {} hargs = args.pop if Hash===args.last unless hargs.empty? (class << self; self; end).instance_eval do default_instance_variables.update(hargs) end end make = {} (args.flatten+hargs.keys).each { |a| t = a.to_s.slice(-1,1) n = a.to_s.chomp('?').chomp('=').to_sym m = a.to_sym case t when '?' make[m] = %{ def #{n}? ; @#{n} ? true : @#{n} ; end } when '=' make[m] = %{ def #{n}=(x) ; @#{n} = x ; end } make[n] = %{ def #{n} ; @#{n} ; end } else make[m] = %{ def #{n} ; @#{n} ; end } end } class_eval make.values.join("\n") return make.keys end end #Module