Class: Giter8::Pairs

Inherits:
Object
  • Object
show all
Defined in:
lib/giter8/pairs.rb

Overview

Pairs represents a set of property pairs

Instance Method Summary collapse

Constructor Details

#initialize(map = {}) ⇒ Pairs

Creates a new Pairs instance, optionally with a given map.



7
8
9
10
11
12
13
14
15
# File 'lib/giter8/pairs.rb', line 7

def initialize(map = {})
  @pairs = map.map do |e|
    if e.is_a? Pair
      e
    else
      Pair.new(*e)
    end
  end
end

Instance Method Details

#each(&block) ⇒ Object

When a block is provided, invokes the block once for each Pair included in this set. Otherwise, returns an Enumerator for this instance.



36
37
38
# File 'lib/giter8/pairs.rb', line 36

def each(&block)
  @pairs.each(&block)
end

#each_pairObject

Invokes a given block once for each element in this set, providing the element’s key and value as arguments, respectively.



42
43
44
45
46
# File 'lib/giter8/pairs.rb', line 42

def each_pair
  each do |p|
    yield p.key, p.value
  end
end

#fetch(name, default = nil) ⇒ Object

Returns the value associated with a given name, or an optional default argument. In case no default is provided, nil is returned.



30
31
32
# File 'lib/giter8/pairs.rb', line 30

def fetch(name, default = nil)
  find(name) || default
end

#find(name) ⇒ Object

Attempts to find a Pair instance with a given name among all propertines in the current set. Returns a Pair object, or nil, if the provided name does not match any Pair.



21
22
23
24
25
26
# File 'lib/giter8/pairs.rb', line 21

def find(name)
  v = find_pair(name.to_sym)
  return nil if v.nil?

  v.value
end

#find_pair(name) ⇒ Object

Returns a Pair value with a given name, or nil, in case no Pair matches the provided name.



50
51
52
# File 'lib/giter8/pairs.rb', line 50

def find_pair(name)
  @pairs.find { |e| e.key == name.to_sym }
end

#key?(name) ⇒ Boolean

Returns whether a Pair with the provided name exists in the set

Returns:

  • (Boolean)


60
61
62
# File 'lib/giter8/pairs.rb', line 60

def key?(name)
  !find(name).nil?
end

#merge(pairs) ⇒ Object

Merges a provided Hash or Pairs instance into the current set



65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/giter8/pairs.rb', line 65

def merge(pairs)
  pairs = Pairs.new(pairs) if pairs.is_a? Hash

  pairs.each_pair do |k, v|
    pair = find_pair(k)
    if pair.nil?
      @pairs << Pair.new(k, v)
    else
      idx = @pairs.index(pair)
      pair.value = v
      @pairs[idx] = pair
    end
  end
end

#to_hObject

Returns the current props represented as a Hash



55
56
57
# File 'lib/giter8/pairs.rb', line 55

def to_h
  @pairs.map { |e| [e.key, e.value] }.to_h
end