Sha256: 87e953b3ad1add77061c4accdb94ccaf3feb3c4662a3379dff8d2fa676c56071

Contents?: true

Size: 1.13 KB

Versions: 2

Compression:

Stored size: 1.13 KB

Contents

class Fragment
  attr_accessor :out

  def self.please(&block); self.new(&block).out; end

  def initialize(&block)
    @out = ""
    instance_eval(&block) if block_given?
  end

  def method_missing(meth, args={}, &block); tag(meth, args, &block); end

  def tag(name, attributes={})
    @out << "<#{name}"
    if attributes.kind_of?(String)
      @out << ' ' << attributes
    else
      @out << attributes.delete_if{|k,v| v.nil? or v==false }.map{|(k,v)| " #{k}='#{_fragment_escape_entities(v)}'" }.join
    end
    if block_given?
      @out << ">"
      text = yield
      @out << text.to_str if text != @out and text.respond_to?(:to_str)
      @out << "</#{name}>"
    else
      @out << ' />'
    end
  end

  def _fragment_escape_entities(s)
    s.to_s.gsub(/&/, '&amp;').gsub(/"/, '&quot;').gsub(/'/, '&apos;').gsub(/</, '&lt;').gsub(/>/, '&gt;')
  end
  
  # Override Kernel methods
  def p(args={}, &block); tag(:p, args, &block); end
  def select(args={}, &block); tag(:select, args, &block); end
  
  # More
  def write(s=''); @out << s; end
  def doctype; write "<!DOCTYPE html>\n"; end
  def comment(s=''); write "\n<!-- #{s} -->\n"; end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
fragment-0.0.2 lib/fragment.rb
fragment-0.0.1 lib/fragment.rb