Class: NumRu::Attribute

Inherits:
Hash
  • Object
show all
Defined in:
lib/numru/gphys/attribute.rb

Overview

class Attribute < Hash

A Hash class compatible with NetCDF attributes.

  • Values are restricted to NetCDFAttr values

  • Keys must be String or Symbol (Symbol is converted into String such that they are used interchangeably. E.g., attr == attr )

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeAttribute

Returns a new instance of Attribute.



23
24
25
# File 'lib/numru/gphys/attribute.rb', line 23

def initialize
	 super
end

Class Method Details

.[](*keyval) ⇒ Object

< class methods > ##



30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/numru/gphys/attribute.rb', line 30

def [](*keyval)
   attr = new
   0.step(keyval.length-1,2){ |i|
      key,val = keyval[i],keyval[i+1]
      if key.is_a?(Symbol)
  key=key.to_s
      elsif ! key.is_a?(String)
  raise ArgumentError,"Attribute key must be String or Symbol: #{key} -- #{key.class}."
      end
      attr[key]=val
   }
   attr
end

Instance Method Details

#[](key) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
# File 'lib/numru/gphys/attribute.rb', line 62

def [](key)
	 if key.is_a?(Symbol)
	    key = key.to_s
	 elsif ! key.is_a?(String)
	    raise ArgumentError, "Attribute key must be Symbol or String: #{key} -- #{key.class}." 
	 end
	 if /^[A-Za-z_]\w*$/ !~ key
	   raise ArgumentError, "Attribute key must match /^[A-Za-z_]\w*$/"
   end
   super(key)
end

#[]=(key, val) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/numru/gphys/attribute.rb', line 74

def []=(key, val)
	 if _val_allowed?(val)
	    if key.is_a?(Symbol)
  key = key.to_s
	    elsif ! key.is_a?(String)
  raise ArgumentError, "Attribute key must be Symbol or String: #{key} -- #{key.class}." 
	    end
	    super(key, val)
	 else
	    raise ArgumentError, "Not allowed as an attribute value: #{val} (String or NArray/Array of numerics are required`)" 
	 end
	 val
end

#copy(to = nil) ⇒ Object

< methods > ##



47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/numru/gphys/attribute.rb', line 47

def copy(to=nil)
	 # deep copy (clone), or addition to "to" if given.
	 if to == nil
	    to = NumRu::Attribute.new
	 end
	 self.each{|key, val|
	    if(val)
  to[key] = val.clone
	    else
  to[key] = val
	    end
	 }
	 to
end

#rename(key_from, key_to) ⇒ Object



88
89
90
91
92
93
# File 'lib/numru/gphys/attribute.rb', line 88

def rename(key_from, key_to)
	 v = self[key_from]
	 if v==nil; raise "attribute #{key_from} does not exist"; end
   self[key_to]=v
	 self.delete(key_from)
end