Sha256: f4aee7ea06edd95079b51d3fdfb74a49bad24739a4b19033c2de41c806da3306
Contents?: true
Size: 1.94 KB
Versions: 4
Compression:
Stored size: 1.94 KB
Contents
# = aobject.rb # # == Developer Notes # # NOTE Add validity tests? require 'facets/core/kernel/meta_eval' require 'facets/core/hash/rekey' # class AObject def self.instance_attributes @@attributes ||= [] end # Define an attribute. def self.attr(name) name = name.to_s.downcase instance_attributes << name define_method(name) do @attributes[name] end define_method("#{name}=") do |v| @attributes[name] = v end end # Subclasses have to call super in initialize. def initialize( keys=nil, &yld ) init = @@attributes.collect{|a|[a,nil]}.flatten @attributes = Hash[*init] return unless keys or yld keys = (keys||yld).to_h keys.rekey!{ |k| k.to_s.downcase } @attributes.update(keys) end # def attribute(name) @attributes[name.to_s.downcase] end alias :at :attribute # def attributes @@attributes.keys end # Bracket accessors. def key?(name) @attribuites.key?(name.to_s.downcase) end def [](name) @attributes[name.to_s.downcase] end def []=(name, value) @attributes[name.to_s.downcase] = value end # Hash conversion. def to_hash(all=false) @attributes end alias :to_h :to_hash # YAML conversion. def to_yaml @attributes.to_yaml end # Arbitrary information. def method_missing( s, *a, &b ) s = s.to_s if s[-1,1] == '=' meta_eval { attr s.chomp('=') } send(s,*a,&b) else super end end end # _____ _ # |_ _|__ ___| |_ # | |/ _ \/ __| __| # | | __/\__ \ |_ # |_|\___||___/\__| # =begin test class TestAObject < Test::Unit::TestCase class X < AObject attr :a attr :b attr :c def a self[:a] || 1 end def c self[:c] + 1 end end def test_001 x = X.new assert_equal( 1, x.a ) x.b = 2 assert_equal( 2, x.b ) x.c = 3 assert_equal( 4, x.c ) end end =end
Version data entries
4 entries across 4 versions & 1 rubygems
Version | Path |
---|---|
facets-1.8.0 | work/more/aobject.rb |
facets-1.8.20 | work/more/aobject.rb |
facets-1.8.49 | work/more/aobject.rb |
facets-1.8.8 | work/more/aobject.rb |