Module: Timl

Defined in:
lib/timl.rb,
lib/timl/timl.rb

Constant Summary collapse

VERSION =
'0.1'
ROOTDIR =
File.expand_path(File.dirname(__FILE__) + '/..')
SPECDIR =
ROOTDIR + '/spec'

Class Method Summary collapse

Class Method Details

.define_tags(*args) ⇒ Object

Dynamically defines a tag method so we don’t have to hit method_missing all the time.



4
5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/timl/timl.rb', line 4

def self.define_tags *args
  args.each do |tag|
    self.class.instance_eval do
      define_method tag do |*args, &block|
        @@out <<  "<#{tag.to_s}#{parameterize args.first}>"
        result = module_eval(&block)
        @@out <<  result unless result.nil? || result.start_with?('<')
        @@out <<  "</#{tag.to_s}>"
        @@out
      end
    end
  end
end

.method_missing(name, *args, &block) ⇒ Object



54
55
56
57
# File 'lib/timl/timl.rb', line 54

def self.method_missing name, *args, &block
  define_tags name
  method(name).call args, &block
end

.start(format = :pretty, &block) ⇒ Object

Start a Timl XML string. This is the main method for creating XML with Timl. It accepts a format as its first parameter, which can either be :flat or :pretty (defaults to :pretty). The :flat parameter gives you back XML that has no indentation. The :pretty option runs the generated XML through the REXML document formatter, which is a little slower but gives great readability.

Timl.start then takes a block, which kicks off the DSL. Here’s a simple example:

Timl.start :flat do
  p { "This is a paragraph." }
end

#=> <p>This is a paragraph.</p>

For more example please refer to the README.



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/timl/timl.rb', line 38

def self.start format = :pretty, &block
  @@out = ""
  module_eval &block
  case format
  when :pretty
    doc = REXML::Document.new(@@out)
    doc.write(xml = '', 2)
  when :flat
    xml = @@out
  else
  end

  @@out = ""
  xml
end