Class: Moo::Model::Template

Inherits:
Object show all
Defined in:
lib/moo/model/template.rb

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(template_filename) ⇒ Template

get the filename, check it exists, but don’t load it up until we need to



52
53
54
55
56
57
58
59
60
# File 'lib/moo/model/template.rb', line 52

def initialize(template_filename)
  unless File.exists? template_filename
    raise ArgumentError, "Template file provided doesn't exist: #{template_filename}"
  end
  @filename = template_filename
  @code = File.basename @filename, '.xml'
  @product = @code.split('_')[0]
  @xml_doc = nil
end

Class Attribute Details

.allObject (readonly)

Returns the value of attribute all.



7
8
9
# File 'lib/moo/model/template.rb', line 7

def all
  @all
end

Instance Attribute Details

#codeObject

Returns the value of attribute code.



48
49
50
# File 'lib/moo/model/template.rb', line 48

def code
  @code
end

#filenameObject (readonly)

Returns the value of attribute filename.



47
48
49
# File 'lib/moo/model/template.rb', line 47

def filename
  @filename
end

#productObject (readonly)

Returns the value of attribute product.



47
48
49
# File 'lib/moo/model/template.rb', line 47

def product
  @product
end

Class Method Details

.codesObject

all template codes



36
37
38
39
# File 'lib/moo/model/template.rb', line 36

def codes
  load unless loaded? 
  @all.map { |t| t.code } 
end

.loadObject

Load all the templates into objects



10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/moo/model/template.rb', line 10

def load
  @all = [] #contains all template objects

  template_dir = Gem.datadir('moo') + '/templates/'

  template_files = Dir.entries(template_dir).reject do |t|
    t == '.' || t == '..'
  end

  template_files.each do |f|
    path = template_dir + f
    @all << Template.new(path)
  end
end

.loaded?Boolean

True if templates loaded, false otherwise

Returns:

  • (Boolean)


31
32
33
# File 'lib/moo/model/template.rb', line 31

def loaded?
  !@all.nil?
end

.unloadObject

Discard all the template objects



26
27
28
# File 'lib/moo/model/template.rb', line 26

def unload
  @all = nil
end

.with_code(code) ⇒ Object



41
42
43
44
# File 'lib/moo/model/template.rb', line 41

def with_code(code)
  load unless loaded?
  @all.select { |t| t.code == code }[0]
end

Instance Method Details

#loadObject

load the data from the file into the object



63
64
65
66
67
68
69
70
# File 'lib/moo/model/template.rb', line 63

def load
  doc = Nokogiri::XML(open(filename))
  xml_template_code = doc.css('Code')[0].content
  unless code == xml_template_code
    raise StandardError, "template codes '#{code}' and '#{xml_template_code}' don't match"
  end
  @xml_doc = doc
end

#to_xmlObject



72
73
74
75
# File 'lib/moo/model/template.rb', line 72

def to_xml
  load if @xml_doc.nil? 
  @xml_doc.to_s
end