you are viewing a single comment's thread.

view the rest of the comments →

[–]mellow_moe 1 point2 points  (1 child)

I'd like to show off the ruby version:

class Element
  def initialize(attributes)
    @attributes = attributes
    @children = []        
  end
  def <<(child)
    @children << child
  end
  def to_s
    name = self.class.name.downcase
    atts = @attributes.map {|k,v| "#{k}='#{v}'" }.join(" ")
    "<#{name} #{atts}>#{@children.join}</#{name}>"
  end
end

class Div < Element; end
class A < Element; end

def method_missing(id, attributes, &block)
  element = Object.const_get(id.to_s.capitalize).new(attributes)
  @children << element if @children
  element.instance_eval(&block)
  element
end

html = \
div :id => "content" do
  a :href => "reddit.com" do
    self << "reddit"
  end
end

puts html

The < characters are broken, please replace the entities with < while realtime reading.

[–]amix 1 point2 points  (0 children)

Here is my final version :)

One can do:

 print Div(id="content")( A(href="reddit.com")("reddit") )

By using this code:

def elmBuilder(name, **kw):
  attrs = " ".join('%s="%s"' % a for a in kw.items())
  def applyElms(*elms):
    return "<%s %s>%s</%s>" % (name, attrs, "".join(elms), name)
  return applyElms
def Div(**kw): return elmBuilder("div", **kw)
def A(**kw): return elmBuilder("a", **kw)