Sha256: 30d6b4cfc1db2358d260934bc5d5df28150c8bbf4ce61bafad5604e4f5d42e97

Contents?: true

Size: 1.75 KB

Versions: 1

Compression:

Stored size: 1.75 KB

Contents

#--
# StaticHash
#
# Copyright (c) 2005 Thomas Sawyer
#
# from Gavin Kistner's WriteOnceHash in basiclibrary.rb
# Copyright (c) 2004 Gavin Kistner
#
# Reuse License
#
# It is covered under the license viewable at http://phrogz.net/JS/_ReuseLicense.txt
# Reuse or modification is free provided you abide by the terms of that license.
# (Including the first two lines above in your source code usually satisfies
# the conditions.)
#
# ==========================================================================
#  Revision History
# ==========================================================================
#
#  04.06.01 trans  Ported to Mega
#
# ==========================================================================
#++

#:title: StaticHash
#
# A Hash object which raises an error if any
# previously-defined key attempts to be set again.
#
# == Synopsis
#
#   foo = Hash::Static.new
#   foo['name'] = 'Tom'    #=> 'Tom'
#   foo['age']  = 30       #=> 30
#   foo['name'] = 'Bob'
#
# _produces_
#
#   Error: StaticHash has value for key 'name' in object:
#       {"name"=>"Tom", "age"=>30} (RuntimeError)  
#
# == Author(s)
#
# * Gavin Kistner
#

class StaticHash < Hash

  # Set a value for a key;
  # raises an error if that key already exists with a different value.
  def []=(key,val)
    if self.has_key?(key) && self[key]!=val
      raise ArgumentError, "StaticHash already has value for key '#{key.to_s}'"
    end
    super
  end

end



#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#

=begin testing

require 'test/unit'

class TC_StaticHash < Test::Unit::TestCase 

  def setup
    @sh1 = StaticHash.new
  end

  def test_assign
    @sh1["x"] = 1
    assert_raises( ArgumentError ){  @sh1["x"] = 2 }
  end

end

=end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
facets-0.9.0 lib/mega/statichash.rb