Class: Envo::State

Inherits:
Object
  • Object
show all
Defined in:
lib/envo/state.rb

Defined Under Namespace

Classes: Patch

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(env) ⇒ State

Returns a new instance of State.



3
4
5
6
# File 'lib/envo/state.rb', line 3

def initialize(env)
  @real_env = env.to_h
  @work_env = nil
end

Instance Attribute Details

#real_envObject (readonly)

Returns the value of attribute real_env.



8
9
10
# File 'lib/envo/state.rb', line 8

def real_env
  @real_env
end

Instance Method Details

#diffObject



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

def diff
  return Patch.new if !@work_env

  real_names = @real_env.keys
  work_names = @work_env.keys

  removed_names = real_names - work_names
  added_names = work_names - real_names
  preserved_names = real_names - removed_names

  changed = preserved_names.map { |v|
    r = @real_env[v]
    w = @work_env[v]

    r == w ? nil : [v, w]
  }.compact.to_h

  added = added_names.map { |v| [v, @work_env[v]] }.to_h

  Patch.new(removed_names, changed, added)
end

#get(name) ⇒ Object



22
23
24
# File 'lib/envo/state.rb', line 22

def get(name)
  work_env[name]
end

#set(name, val) ⇒ Object



10
11
12
13
14
15
16
# File 'lib/envo/state.rb', line 10

def set(name, val)
  if val == nil
    unset(name)
  else
    work_env[name] = val.to_s
  end
end

#unset(name) ⇒ Object



18
19
20
# File 'lib/envo/state.rb', line 18

def unset(name)
  work_env.delete(name)
end

#work_envObject



26
27
28
29
30
31
32
33
# File 'lib/envo/state.rb', line 26

def work_env
  return @work_env if @work_env
  # if @real_env is ENV, we can use to_h to clone it into the work env
  # however it can be an actual hash in which case to_h will return the same one
  # and we would have to use clone
  # so to make this work in all cases we preform a manual shallow copy
  @work_env = @real_env.map { |k, v| [k, v] }.to_h
end