Class: XMLMunger::ListHeuristics

Inherits:
Object
  • Object
show all
Defined in:
lib/xmlmunger/list_heuristics.rb

Instance Method Summary collapse

Constructor Details

#initialize(list) ⇒ ListHeuristics

Returns a new instance of ListHeuristics.

Raises:

  • (ArgumentError)


7
8
9
10
# File 'lib/xmlmunger/list_heuristics.rb', line 7

def initialize(list)
  raise ArgumentError, "Argument must be an array" unless list.is_a?(Array)
  @list = list
end

Instance Method Details

#common_type(of = nil) ⇒ Object



24
25
26
27
28
# File 'lib/xmlmunger/list_heuristics.rb', line 24

def common_type(of = nil)
      @common_types ||= {}
                 of ||= @list
  @common_types[of] ||= of.map{|x|x.class.ancestors}.reduce(:&).first
end

#empty?Boolean

Returns:

  • (Boolean)


12
13
14
# File 'lib/xmlmunger/list_heuristics.rb', line 12

def empty?
  @empty ||= @list.count.zero?
end

#multiple?Boolean

Returns:

  • (Boolean)


20
21
22
# File 'lib/xmlmunger/list_heuristics.rb', line 20

def multiple?
  @multiple ||= @list.count > 1
end

#shared_key_hashes?Boolean

Returns:

  • (Boolean)


34
35
36
37
38
39
40
# File 'lib/xmlmunger/list_heuristics.rb', line 34

def shared_key_hashes?
  @shared_key_hashes ||=
    multiple? &&
      common_type == Hash &&
        (keys = @list.first.keys) &&
          @list[1..-1].all? { |hash| hash.keys == keys }
end

#singleton?Boolean

Returns:

  • (Boolean)


16
17
18
# File 'lib/xmlmunger/list_heuristics.rb', line 16

def singleton?
  @singleton ||= @list.count == 1
end

#skipped_typesObject



30
31
32
# File 'lib/xmlmunger/list_heuristics.rb', line 30

def skipped_types
  @skipped_types ||= [:strings]
end

#to_variable_hashObject



42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/xmlmunger/list_heuristics.rb', line 42

def to_variable_hash
  return {} if empty?
  return {nil => @list.first} if singleton?
  if shared_key_hashes?
    merged = merge_hashes(@list)
    typed = classify(merged)
  else
    type, data = identity(@list)
    typed = { nil => { type: type, data: data } }
  end
  apply(typed)
end