Sha256: f8846f78da583cd83983ab24a5b20792ab1d03eee6d417bbe8cade2ac7205761

Contents?: true

Size: 1.77 KB

Versions: 7

Compression:

Stored size: 1.77 KB

Contents

#--
# StaticHash
#
# Copyright (c) 2005 Thomas Sawyer
#
# Ported 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
# ==========================================================================
#
#  2004-06-01 Trans  * Ported to Calibre
#
# ==========================================================================
#++

#: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

7 entries across 7 versions & 1 rubygems

Version Path
facets-1.0.3 packages/more/lib/facet/statichash.rb
facets-1.2.0 lib/facets/more/statichash.rb
facets-1.2.1 lib/facets/more/statichash.rb
facets-1.3.0 lib/facets/more/statichash.rb
facets-1.3.1 lib/facets/more/statichash.rb
facets-1.3.2 lib/facets/more/statichash.rb
facets-1.3.3 lib/facets/more/statichash.rb