Class: CfnDsl::JSONable

Inherits:
Object
  • Object
show all
Extended by:
Functions
Includes:
Functions, RefCheck
Defined in:
lib/cfndsl/jsonable.rb

Overview

This is the base class for just about everything useful in the DSL. It knows how to turn DSL Objects into the corresponding json, and it lets you create new built in function objects from inside the context of a dsl object.

Instance Method Summary collapse

Methods included from Functions

FnAnd, FnBase64, FnEquals, FnFindInMap, FnFormat, FnGetAZs, FnGetAtt, FnIf, FnJoin, FnNot, FnOr, FnSelect, Ref

Methods included from RefCheck

#build_references

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &_block) ⇒ Object



163
164
165
166
167
168
# File 'lib/cfndsl/jsonable.rb', line 163

def method_missing(meth, *args, &_block)
  error = "Undefined symbol: #{meth}"
  error = "#{error}(" + args.inspect[1..-2] + ')' unless args.empty?
  error = "#{error}\n\nTry '#{titleize(meth)}' instead" if incorrect_capitalization?(meth)
  CfnDsl::Errors.error(error, 1)
end

Instance Method Details

#declare(&block) ⇒ Object



159
160
161
# File 'lib/cfndsl/jsonable.rb', line 159

def declare(&block)
  instance_eval(&block) if block_given?
end

#incorrect_capitalization?(method) ⇒ Boolean

Returns:

  • (Boolean)


170
171
172
# File 'lib/cfndsl/jsonable.rb', line 170

def incorrect_capitalization?(method)
  method != titleize(method) && respond_to?(titleize(method))
end

#ref_childrenObject



155
156
157
# File 'lib/cfndsl/jsonable.rb', line 155

def ref_children
  instance_variables.map { |var| instance_variable_get(var) }
end

#titleize(method) ⇒ Object



174
175
176
177
178
# File 'lib/cfndsl/jsonable.rb', line 174

def titleize(method)
  method.to_s.clone.tap do |m|
    m[0] = m[0, 1].upcase
  end.to_sym
end

#to_json(*a) ⇒ Object

Use instance variables to build a json object. Instance variables that begin with a single underscore are elided. Instance variables that begin with two underscores have one of them removed.



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/cfndsl/jsonable.rb', line 137

def to_json(*a)
  hash = {}
  instance_variables.each do |var|
    name = var[1..-1]

    if name =~ /^__/
      # if a variable starts with double underscore, strip one off
      name = name[1..-1]
    elsif name =~ /^_/
      # Hide variables that start with single underscore
      name = nil
    end

    hash[name] = instance_variable_get(var) if name
  end
  hash.to_json(*a)
end