Method: CfnDsl::Types.define_array_method

Defined in:
lib/cfndsl/types.rb

.define_array_method(klass, singular_method, type, variable) ⇒ Object



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/cfndsl/types.rb', line 217

def self.define_array_method(klass, singular_method, type, variable)
  type.class_eval do
    CfnDsl.method_names(singular_method).each do |method_name|
      define_method(method_name) do |value = nil, *rest, fn_if: nil, &block|
        existing = instance_variable_get(variable)
        # For no-op invocations, get out now
        return existing if value.nil? && rest.empty? && !block

        # We are going to modify the value in some
        # way, make sure that we have an array to mess
        # with if we start with nothing
        existing ||= instance_variable_set(variable, [])

        # special case for just a block, no args
        if value.nil? && rest.empty? && block
          val = klass.new
          existing.push(fn_if ? FnIf(fn_if, val, Ref('AWS::NoValue')) : val)
          val.instance_eval(&block)
          return existing
        end

        # Glue all of our parameters together into
        # a giant array - flattening one level deep, if needed
        array_params = []
        if value.is_a?(Array)
          array_params.concat(value)
        else
          array_params.push value
        end

        rest.each do |v|
          if v.is_a?(Array)
            array_params.concat(rest)
          else
            array_params.push v
          end
        end
        # Here, if we were given multiple arguments either
        # as method [a,b,c], method(a,b,c), or even
        # method( a, [b], c) we end up with
        # array_params = [a,b,c]
        #
        # array_params will have at least one item
        # unless the user did something like pass in
        # a bunch of empty arrays.
        if block
          array_params.each do |array_params_value|
            value = klass.new
            existing.push(fn_if ? FnIf(fn_if, value, Ref('AWS::NoValue')) : value)
            # This line never worked before, the useful thing to do is pass the array value to the block
            value.instance_exec(array_params_value, &block)
          end
        else
          # List of parameters with no block -
          # hope that the user knows what he is
          # doing and stuff them into our existing
          # array
          array_params.each do |v|
            existing.push v
          end
        end
        return existing
      end
    end
  end
end