Class: Hashery::PropertyHash
Overview
A PropertyHash is the same as a regular Hash except it strictly limits the allowed keys.
There are two ways to use it.
1) As an object in itself.
h = PropertyHash.new(:a=>1, :b=>2)
h[:a] #=> 1
h[:a] = 3
h[:a] #=> 3
But if we try to set key that was not fixed, then we will get an error.
h[:x] = 5 #=> ArgumentError
2) As a superclass.
class MyPropertyHash < PropertyHash
property :a, :default => 1
property :b, :default => 2
end
h = MyPropertyHash.new
h[:a] #=> 1
h[:a] = 3
h[:a] #=> 3
Again, if we try to set key that was not fixed, then we will get an error.
h[:x] = 5 #=> ArgumentError
Class Method Summary (collapse)
Instance Method Summary (collapse)
- - (Object) <<(a)
- - (Object) []=(k, v)
-
- (Object) accept_key!(k, v = nil)
Add a new acceptable key.
-
- (PropertyHash) initialize(properties = {})
constructor
A new instance of PropertyHash.
- - (Object) merge!(h)
- - (Object) update(h)
Methods inherited from Hash
Methods included from CoreExt
#rekey, #rekey!, #to_h, #to_hash
Constructor Details
- (PropertyHash) initialize(properties = {})
A new instance of PropertyHash
55 56 57 58 59 |
# File 'lib/hashery/property_hash.rb', line 55 def initialize(properties={}) super() fixed = self.class.properties.merge(properties) replace(fixed) end |
Class Method Details
+ (Object) properties
38 39 40 41 42 43 44 45 46 47 |
# File 'lib/hashery/property_hash.rb', line 38 def self.properties @properties ||= ( parent = ancestors[1] if parent.respond_to?(:properties) parent.properties else {} end ) end |
+ (Object) property(key, opts = {})
50 51 52 |
# File 'lib/hashery/property_hash.rb', line 50 def self.property(key, opts={}) properties[key] = opts[:default] end |
Instance Method Details
- (Object) <<(a)
80 81 82 83 |
# File 'lib/hashery/property_hash.rb', line 80 def <<(a) k,v = *a self[k] = v end |
- (Object) []=(k, v)
62 63 64 65 |
# File 'lib/hashery/property_hash.rb', line 62 def []=(k,v) assert_key!(k) super(k,v) end |
- (Object) accept_key!(k, v = nil)
Add a new acceptable key. TODO: Should this be supported?
87 88 89 |
# File 'lib/hashery/property_hash.rb', line 87 def accept_key!(k,v=nil) self[k] = v end |
- (Object) merge!(h)
74 75 76 77 |
# File 'lib/hashery/property_hash.rb', line 74 def merge!(h) h.keys.each{ |k| assert_key!(k) } super(h) end |
- (Object) update(h)
68 69 70 71 |
# File 'lib/hashery/property_hash.rb', line 68 def update(h) h.keys.each{ |k| assert_key!(k) } super(h) end |