module HasResources

HasResources provides methods for a class to contain and query a set of resources

Public Class Methods

included(base) click to toggle source
# File lib/geoengineer/utils/has_resources.rb, line 5
def self.included(base)
  base.extend(ClassMethods)
end

Public Instance Methods

all_resources() click to toggle source

Overridden By Template, Project and Environment, requires explicit override to avoid easy mistakes

# File lib/geoengineer/utils/has_resources.rb, line 26
def all_resources
  raise NotImplementedError, "Including class must override this method"
end
create_resource(type, id, &block) click to toggle source

Factory to create resource and attach

# File lib/geoengineer/utils/has_resources.rb, line 67
def create_resource(type, id, &block)
  # This will look for a class that is defined by the type so it can override functionality
  # For example, if `type='aws_security_group'` then the class would be `AwsSecurityGroup`
  clazz = self.class.get_resource_class_from_type(type)

  res = clazz.new(type, id, &block)
  resources << res # Add the resource
  res
end
find_resource(type, id) click to toggle source
# File lib/geoengineer/utils/has_resources.rb, line 30
def find_resource(type, id)
  all_resources.select { |r| r.type == type && r.id == id }.first
end
find_resource_by_ref(ref) click to toggle source
# File lib/geoengineer/utils/has_resources.rb, line 34
def find_resource_by_ref(ref)
  return nil unless ref.start_with?("${")
  ref = ref.delete('${').delete('}')
  type, name = ref.split('.')
  find_resource(type, name)
end
resources() click to toggle source
# File lib/geoengineer/utils/has_resources.rb, line 19
def resources
  @_resources = [] unless @_resources
  @_resources
end
resources_grouped_by(resources_to_group = all_resources) { |r| ... } click to toggle source

Returns: { value1: [ ], value2: [ ] }

# File lib/geoengineer/utils/has_resources.rb, line 42
def resources_grouped_by(resources_to_group = all_resources)
  resources_to_group.each_with_object({}) do |r, c|
    value = yield r
    c[value] ||= []
    c[value] << r
    c
  end
end
resources_of_type(type) click to toggle source
# File lib/geoengineer/utils/has_resources.rb, line 62
def resources_of_type(type)
  all_resources.select { |r| r.type == type }
end
resources_of_type_grouped_by(&block) click to toggle source

Returns: { type1: { value1: [ ] }, type2: { value2: [ ] } }

# File lib/geoengineer/utils/has_resources.rb, line 52
def resources_of_type_grouped_by(&block)
  grouped = resources_grouped_by(all_resources, &:type)

  grouped_arr = grouped.map do |type, grouped_resources|
    [type, resources_grouped_by(grouped_resources, &block)]
  end

  grouped_arr.to_h
end