Class: LWAC::Resource

Inherits:
Object
  • Object
show all
Defined in:
lib/lwac/export/resources.rb

Overview


This is similar to ruby’s Struct system, in that it creates an object based on the input parameters, with the exception that it can be efficiently and recursively described.

Instance Method Summary collapse

Constructor Details

#initialize(name, params = {}) ⇒ Resource

Construct a resource from a hash of parameters and a name.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/lwac/export/resources.rb', line 21

def initialize(name, params = {})
  @params = []
  params.each{ |p, v|
    if(p) then
      # Parse param
      param   = sanitise_paramname(p)
      raise "Duplicate parameters for resource #{name}: #{param}." if @params.include? param
      val     = (v.is_a? Hash) ? Resource.new(param, v) : v

      eval("@#{param} = val")
      self.class.__send__(:attr_accessor, param)
      @params << param
    end
  }
  @name     = name
end

Instance Method Details

#__nameObject

Expose name to people who may wish to iterate over them



68
69
70
# File 'lib/lwac/export/resources.rb', line 68

def __name
  @name
end

#__paramsObject

Expose parameters to people who may wish to iterate over them



63
64
65
# File 'lib/lwac/export/resources.rb', line 63

def __params
  @params
end

#describe(trunc = [17, 50], indent = 0, notitle = false) ⇒ Object

Describe this resource in a nice terminal-friendly way

* trunc --- how to truncate the keys[0] and values[1]
* indent --- base indent
* notitle --- Don't output a header


42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/lwac/export/resources.rb', line 42

def describe(trunc = [17, 50], indent=0, notitle=false)
  str = "{\n"
  str = "#{" "*indent}#{@name}#{str}" if not notitle
  @params.each{|p|
    # Load the value
    val = eval("@#{p}")

    # Output the string
    str += "#{" "*indent}  #{p.truncate(trunc[0])}: "
    if val.is_a? Resource
      str += "#{val.describe(trunc, indent + 2, true)}" 
    else
      str += "#{val.to_s.truncate(trunc[1]).gsub("\n", '\n').gsub("\r", '\r').gsub("\t", '\t')}"
    end
    str += "\n"
  }
  str += "#{" "*indent}}"
  return str
end