Permalink
Switch branches/tags
Nothing to show
Find file
Fetching contributors…
Cannot retrieve contributors at this time
127 lines (90 sloc) 2.58 KB

XML generator

Follow these steps to create a tiny XML generator: xml.rb

We can use it like this:

  • Look at sample_html.rb
  • Need to write XML class with xml_generate() method.
  • Line 9-22 is our tiny DSL code to create the output (xml format text). It'll be stored to sample_twitters.html file at the last line.
  • Line 4-6 is the input data, just a sample for this practice.
  • Look at the output: sample_twitters.html and a screenshot.

Step 1 ------ Let's start! Create two files: sample_html.rb and xml.rb

sample_html.rb has the following features.

  • create a XML object
  • call xml_generate() method
  • at first, the input is only one line: content "Let's start!"
  • store the output (created xml)

xml.rb has the following three instance methods.

  • initialize
  • content
  • xml_generate

Hint: instance_eval


Look at the input and output for Step 1.


Step 2 ------ Improve to accept the following inputs.
html do
  body do
    content "Let's start!"
  end
end

Hint: method_missing


Look at the input and output for Step 2.


Step 3 ------ Improve to accept the following inputs.
html do
  body do
    content "Let's start!"
    form :action => '/page', :method => 'post' do
      input :type => 'text', :name => 'str', :maxlength => 3, :size => 3
      input :type => 'submit', :value => 'page'
    end
  end
end

Hint: hash


Look at the input and output for Step 3.


Step 4 ------ Improve to accept the following inputs. Use [this pic](./XML_generator/b-satoshi.jpg) as a avatar.
html do
  body do
    twitters.each do |tw|
      img :src => tw.avatar, :alt => tw.name, :width => 25, :height => 25
      content [" : " , tw.text]
      br
      br
    end
    form :action => '/page', :method => 'post' do
      input :type => 'text', :name => 'str', :maxlength => 3, :size => 3
      input :type => 'submit', :value => 'page'
    end
  end
end

Hint: no need to use any more metaprogramming tech.


Look at the input and output for Step 4.


Step 5 ------ We want to replace XML.new.xml_generate to XML.generate.

Hint: define class method


Let's discuss your code in the relevant thread in the Second Week Forum.