Sha256: 7c7993b63d7fb3de0eb98487804f5fbb61fb9e8e51d930dba918a0a0638dab68

Contents?: true

Size: 1.97 KB

Versions: 66

Compression:

Stored size: 1.97 KB

Contents

require 'cfndsl/plurals'
require 'cfndsl/names'

# Adds some dsl module helpers
class Module
  private

  # Create setter methods
  #
  # Usage:
  #    class Something
  #      dsl_attr_setter :Thing
  #    end
  #
  # Generates a setter method like this one for each symbol in *symbols:
  #
  # def Thing(value)
  #   @Thing = value
  # end
  #
  def dsl_attr_setter(*symbols)
    symbols.each do |symbol|
      class_eval do
        CfnDsl.method_names(symbol) do |method|
          define_method(method) do |value|
            instance_variable_set("@#{symbol}", value)
          end
        end
      end
    end
  end

  # Create object declaration methods.
  #
  # Usage:
  #   Class Something
  #     dsl_content_object :Stuff
  #   end
  #
  # Generates methods like this:
  #
  # def Stuff(name, *values, &block)
  #   @Stuffs ||= {}
  #   @Stuffs[name] ||= CfnDsl::#{symbol}Definition.new(*values)
  #   @Stuffs[name].instance_eval &block if block_given?
  #   return @Stuffs[name]
  # end
  #
  # The effect of this is that you can then create named sub-objects
  # from the main object. The sub objects get stuffed into a container
  # on the main object, and the block is then evaluated in the context
  # of the new object.
  #
  def dsl_content_object(*symbols)
    symbols.each do |symbol|
      plural = CfnDsl::Plurals.pluralize(symbol) # @@plurals[symbol] || "#{symbol}s"
      pluralvar = "@#{plural}".to_sym
      definition_class = CfnDsl.const_get("#{symbol}Definition")
      class_eval do
        CfnDsl.method_names(symbol) do |method|
          define_method(method) do |name, *values, &block|
            name = name.to_s
            hash = instance_variable_get(pluralvar)
            unless hash
              hash = {}
              instance_variable_set(pluralvar, hash)
            end
            hash[name] ||= definition_class.new(*values)
            hash[name].instance_eval(&block) if block
            return hash[name]
          end
        end
      end
    end
  end
end

Version data entries

66 entries across 66 versions & 1 rubygems

Version Path
cfndsl-0.16.13 lib/cfndsl/module.rb
cfndsl-0.16.12 lib/cfndsl/module.rb
cfndsl-0.16.11 lib/cfndsl/module.rb
cfndsl-0.16.10 lib/cfndsl/module.rb
cfndsl-0.16.9 lib/cfndsl/module.rb
cfndsl-0.16.8 lib/cfndsl/module.rb
cfndsl-0.16.7 lib/cfndsl/module.rb
cfndsl-0.16.6 lib/cfndsl/module.rb
cfndsl-0.16.5 lib/cfndsl/module.rb
cfndsl-0.16.3 lib/cfndsl/module.rb
cfndsl-0.16.2 lib/cfndsl/module.rb
cfndsl-0.16.1 lib/cfndsl/module.rb
cfndsl-0.15.3 lib/cfndsl/module.rb
cfndsl-0.15.2 lib/cfndsl/module.rb
cfndsl-0.15.1 lib/cfndsl/module.rb
cfndsl-0.15.0 lib/cfndsl/module.rb
cfndsl-0.14.0 lib/cfndsl/module.rb
cfndsl-0.13.1 lib/cfndsl/module.rb
cfndsl-0.13.0 lib/cfndsl/module.rb
cfndsl-0.12.11 lib/cfndsl/module.rb