Class: Treet::Hash

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/treet/hash.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source) ⇒ Hash

when loading an Array (at the top level), members are always sorted so that array comparisons will be order-independent



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/treet/hash.rb', line 14

def initialize(source)
  d = case source
  when Hash
    source
  when String
    # treat as filename
    JSON.load(File.read(source))
  else
    if source.respond_to?(:to_hash)
      initialize(source.to_hash)
    else
      raise "Invalid source data type #{source.class} for Treet::Hash"
    end
  end

  @data = normalize(d)
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



7
8
9
# File 'lib/treet/hash.rb', line 7

def data
  @data
end

Class Method Details

.digestify(data) ⇒ Object



75
76
77
78
79
80
81
82
# File 'lib/treet/hash.rb', line 75

def self.digestify(data)
  case data
  when Hash
    Digest::SHA1.hexdigest(data.to_a.sort.flatten.join)
  else # String
    data
  end
end

Instance Method Details

#==(target) ⇒ Object



62
63
64
# File 'lib/treet/hash.rb', line 62

def ==(target)
  eql?(target)
end

#compare(target) ⇒ Object

def normalized_data

data.each_with_object({}) do |(k,v),h|
  h[k.to_s] = case v
  when Array
    v.sort_by {|x| x.hash}
  else
    v
  end
end

end def hash

data.hash
# normalized_data.hash

end



57
58
59
60
# File 'lib/treet/hash.rb', line 57

def compare(target)
  # HashDiff.diff(data, target.to_hash)
  Treet::Hash.diff(data.to_hash, target.to_hash)
end

#eql?(target) ⇒ Boolean

Returns:

  • (Boolean)


65
66
67
# File 'lib/treet/hash.rb', line 65

def eql?(target)
  self.hash.eql?(Treet::Hash.new(target).hash)
end

#patch(diffs) ⇒ Object

apply diffs (created via the ‘#compare` function) to create a new object



69
70
71
72
73
# File 'lib/treet/hash.rb', line 69

def patch(diffs)
  # newhash = Treet::Hash.patch(self.to_hash, diffs)
  newhash = Treet::Hash.patch(data, diffs)
  Treet::Hash.new(newhash)
end

#to_hashObject



38
39
40
# File 'lib/treet/hash.rb', line 38

def to_hash
  data #.to_hash
end

#to_repo(root, opts = {}) ⇒ Object



32
33
34
35
36
# File 'lib/treet/hash.rb', line 32

def to_repo(root, opts = {})
  construct(data, root)
  repotype = opts[:repotype] || Treet::Repo
  repotype.new(root, opts)
end