Parent

Files

PropertyHash

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

Public Class Methods

new(properties={}) click to toggle source
# File lib/hashery/propertyhash.rb, line 53
def initialize(properties={})
  super()
  fixed = self.class.properties.merge(properties)
  replace(fixed)
end
properties() click to toggle source
# File lib/hashery/propertyhash.rb, line 36
def self.properties
  @properties ||= (
    parent = ancestors[1]
    if parent.respond_to?(:properties)
      parent.properties
    else
      {}
    end
  )
end
property(key, opts={}) click to toggle source
# File lib/hashery/propertyhash.rb, line 48
def self.property(key, opts={})
  properties[key] = opts[:default]
end

Public Instance Methods

<<(a) click to toggle source
# File lib/hashery/propertyhash.rb, line 78
def <<(a)
  k,v = *a
  self[k] = v
end
[]=(k,v) click to toggle source
# File lib/hashery/propertyhash.rb, line 60
def []=(k,v)
  assert_key!(k)
  super(k,v)
end
accept_key!(k,v=nil) click to toggle source

Add a new acceptable key. TODO: Should this be supported?

# File lib/hashery/propertyhash.rb, line 85
def accept_key!(k,v=nil)
  self[k] = v
end
merge!(h) click to toggle source
# File lib/hashery/propertyhash.rb, line 72
def merge!(h)
  h.keys.each{ |k| assert_key!(k) }
  super(h)
end
update(h) click to toggle source
# File lib/hashery/propertyhash.rb, line 66
def update(h)
  h.keys.each{ |k| assert_key!(k) }
  super(h)
end

[Validate]

Generated with the Darkfish Rdoc Generator 2.