lib/fragment.rb in fragment-0.0.2 vs lib/fragment.rb in fragment-1.0.0
- old
+ new
@@ -1,43 +1,52 @@
class Fragment
- attr_accessor :out
+ attr_accessor :to_s
- def self.please(&block); self.new(&block).out; end
+ def self.create(&block); self.new(false,&block).to_s; end
+ def self.create_here(&block); self.new(true,&block).to_s; end
- def initialize(&block)
- @out = ""
- instance_eval(&block) if block_given?
+ def initialize outer_scope=false, &block
+ @to_s = ""
+ return self unless block_given?
+ unless outer_scope
+ instance_eval(&block)
+ else
+ block.call(self)
+ end
+ self
end
def method_missing(meth, args={}, &block); tag(meth, args, &block); end
- def tag(name, attributes={})
- @out << "<#{name}"
+ def tag name, attributes={}
+ @to_s << "<#{name}"
if attributes.kind_of?(String)
- @out << ' ' << attributes
+ @to_s << ' ' << attributes
else
- @out << attributes.delete_if{|k,v| v.nil? or v==false }.map{|(k,v)| " #{k}='#{_fragment_escape_entities(v)}'" }.join
+ @to_s << attributes.delete_if{|k,v| v.nil? or v==false }.map{|(k,v)| " #{k}='#{_fragment_escape_html(v)}'" }.join
end
if block_given?
- @out << ">"
+ @to_s << ">"
text = yield
- @out << text.to_str if text != @out and text.respond_to?(:to_str)
- @out << "</#{name}>"
+ @to_s << text.to_str if text != @to_s and text.respond_to?(:to_str)
+ @to_s << "</#{name}>"
else
- @out << ' />'
+ @to_s << ' />'
end
end
- def _fragment_escape_entities(s)
- s.to_s.gsub(/&/, '&').gsub(/"/, '"').gsub(/'/, ''').gsub(/</, '<').gsub(/>/, '>')
- 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
+ # Helpers
+
+ def write(s=''); @to_s << s; end
def doctype; write "<!DOCTYPE html>\n"; end
def comment(s=''); write "\n<!-- #{s} -->\n"; end
+ def _fragment_escape_html(s)
+ s.to_s.gsub(/&/, '&').gsub(/"/, '"').gsub(/'/, ''').gsub(/</, '<').gsub(/>/, '>')
+ end
-end
\ No newline at end of file
+end
+