Class: Burlap::Hash

Inherits:
ActiveSupport::OrderedHash show all
Defined in:
lib/burlap/hash.rb

Overview

todo: subclass ::Hash once this is 1.9.2 only

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from ActiveSupport::OrderedHash

#[]=, #clear, #delete, #delete_if, #each, #each_key, #each_value, #initialize, #initialize_copy, #invert, #keys, #merge, #merge!, #reject, #reject!, #replace, #shift, #to_a, #to_hash, #to_yaml, #to_yaml_type, #values

Constructor Details

This class inherits a constructor from ActiveSupport::OrderedHash

Instance Attribute Details

#__type__Object

Accessor for the type attribute, defaults to an empty string



33
34
35
# File 'lib/burlap/hash.rb', line 33

def __type__
  @__type__ ||= ""
end

Class Method Details

.[](*args) ⇒ Object

We override this to allow a type to be set upon object initialization. As we subclass Hash and call super it should behave exactly the same as Hash#[].

NB: we actually subclass ActiveSupport::OrderedHash for ordered hash support in ruby 1.8.x, which means we don't behave exactly like Hash#[] on 1.8.x. Sucks.

Examples:

Burlap::Hash[:one => :two] # => => :two, type == "" Burlap::Hash[=> :two, "fred"] # => => :two, type == "fred"



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/burlap/hash.rb', line 20

def self.[] *args
  if args.size == 2 && args[1].is_a?(::String)
    h = super(args[0].to_a)
    h.__type__ = args[1]
    h
  elsif args.size == 1 && args[0].is_a?(::Hash)
    super(args[0].to_a)
  else
    super
  end
end

Instance Method Details

#inspectObject

Build a string for ourselves, including both type and the hash



38
39
40
41
42
# File 'lib/burlap/hash.rb', line 38

def inspect
  # we have to build our hash string manually so it's ordered, can't call #to_h.inspect under 1.8
  # as that returns an _un_ordered hash.
  "#<#{self.class} __type__=#{__type__.inspect} {#{map {|k,v| "#{k.inspect}=>#{v.inspect}"}.join(", ")}}>"
end

#to_burlapObject

Converts the hash into a string of XML, calling #to_burlap on all keys & values. Builds a element, with type set then all key/values following.



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/burlap/hash.rb', line 51

def to_burlap
  # Build the node for the type
  contents = [Burlap::Node.new(
    :name => "type",
    :value => self.__type__
  )]

  # Build nodes for all the content
  contents += self.map do |k,v|
    [k, v]
  end.flatten(1)

  content = contents.map(&:to_burlap).join("")

  Burlap::Node.new(
    :name => "map",
    :value => content
  ).to_burlap
end

#to_hObject

Return ourselves as a plain old ruby Hash



45
46
47
# File 'lib/burlap/hash.rb', line 45

def to_h
  ::Hash[self]
end