pax_global_header00006660000000000000000000000064117076034240014516gustar00rootroot0000000000000052 comment=d0ca07287a1c98e2ddcfb8edd2aea2533e2d90b9 ruby-erubis-2.7.0/000077500000000000000000000000001170760342400137745ustar00rootroot00000000000000ruby-erubis-2.7.0/CHANGES.txt000066400000000000000000000561331170760342400156150ustar00rootroot00000000000000# -*- coding: utf-8 -*- # $Release: 2.7.0 $ # copyright(c) 2006-2011 kuwata-lab.com all rights reserved. - release: 2.7.0 date: 2011-04-01 enhancements: - | New option ':bufvar' supported to specify buffer variable name. ex: input = "Hello <%= name %>!" eruby = Erubis::Eruby.new(input) puts eruby.src #=> _buf = ''; _buf << "Hello "; _buf << ( name ).to_s; _buf << '!'; eruby = Erubis::Eruby.new(input, :bufvar=>'@_out') puts eruby.src #=> @_out = ''; @_out << 'Hello '; @_out << ( name ).to_s; @_out << '!'; - | New enhancer 'PrefixedLineEnhancer' which is a customizable version of PercentLineEnhancer. The difference between PrefixedLineEnhancer and PercentLineEnhancer is: * You can indent Ruby statetment lines starting with '%' * You can specify prefix character by :prefixchar option. ex: class MyEruby < Erubis::Eruby include Erubis::PrefixedLineEnhancer end input = < % for item in @items
  • <%= item %>
  • % end %% you can indent '%' lines END eruby = MyEruby.new(input, :prefixchar=>'%') # default '%' puts eruby.src output: _buf = ''; _buf << ' '; _buf.to_s - | Add helper CGI script. See 'public_html/README.txt' for details. - | Rubinius is supported as first-class Ruby implementation. - | C++ support. Try '-l cpp' command-line option. changes: - | Remove dependency to 'abstract' library. You don't need to install 'abstract' gem. - | Erubis::Eruby#load_file() now sets cache file timestamp to the same value as original eRuby file. For example, if you restore eRuby files from backup, Erubis::Eruby#load_file() can detect it and generate cache file again. ## generates cache file (A.rhtml.cache). eruby = Erubis::Eruby.load_file('A.rhtml') p File.mtime('A.rhtml') == File.mtime('A.rhtml.cache') #=> true - release: 2.6.6 date: 2010-06-27 bugfixes: - | Fixed a bug around InterporationEnhancer and FastEruby to escape back-quote. (thanks to Andrew R Jackson) - release: 2.6.5 date: 2009-07-20 bugfixes: - | Fixed bug around '-z' option. - release: 2.6.4 date: 2009-02-18 enhancements: - | Rails 2.2 and 2.3 support. - release: 2.6.3 date: 2009-02-07 bugfixes: - Enhancer name was not displayed in Ruby 1.9.1 when it was missing. - Command option argument name was not displayed correctly as a part of error message. - MethoNotFound error was raised when invalid option was specified. - release: 2.6.2 date: 2008-06-12 enhancements: - | Ruby 1.9 support. bugfixes: - | Fixed installation problem on Windows (Thanks to Tim Morgan and Allen). - release: 2.6.1 date: 2008-06-06 enhancements: - | Rails 2.1 support. (special thanks José Valim) - release: 2.6.0 date: 2008-05-05 enhancements: - | Improved support of Ruby on Rails 2.0.2. New class ActionView::TemplateHandlers::Erubis is defined and registered as default handler of *.html.erb and *.rhtml. - | '<%% %>' and '<%%= %>' are converted into '<% %>' and '<%= %>' respectively. This is for compatibility with ERB. ex1.rhtml: result: $ erubis ex1.rhtml - | '<%= -%>' removes tail spaces and newlines. This is for compatibiliy with ERB when trim mode is '-'. '<%= =%>' also removes tail spaces and newlines, and this is Erubis-original enhancement (cooler than '<%= -%>', isn't it?). ex2.rhtml:
    <%= @var -%> # or <%= @var =%>
    result (version 2.6.0): $ erubis -c '{var: "AAA\n"}' ex2.rhtml
    AAA
    result (version 2.5.0): $ erubis -c '{var: "AAA\n"}' ex2.rhtml
    AAA
    - | Erubis::Eruby.load_file() now allows you to change cache filename. ex. eruby = Erubis::Eruby.load_file("ex3.rhtml", :cachename=>'ex3.rhtml.cache') - release: 2.5.0 date: 2008-01-30 enhancements: - | Ruby on Rails 2.0 support. If you are using preprocessing, notice that _?('foo.id') will be NG because it contains period ('.') character. -------------------- [%= link_to 'Edit', edit_user_path(_?('@user.id')) %] [%= link_to 'Show', @user %] [%= link_to 'Delete', @user, :confirm=>'OK?', :method=>:delete %] <%= user_id = @user.id %> [%= link_to 'Edit', edit_user_path(_?('user_id')) %] [%= link_to 'Show', :action=>'show', :id=>_?('user_id') %] [%= link_to 'Delete', {:action=>'destroy', :id=>_?('user_id')}, {:confirm=>'OK?', :method=>:delete} %] -------------------- - | (experimental) Rails form helper methods for preprocessing are added. These helper methos are available with preprocessing. ex. _form.rhtml -------------------- Name: <%= text_field :user, :name %> Name: [%= pp_text_field :user, :name %] -------------------- preprocessed: -------------------- Name: <%= text_field :user, :name %> Name: -------------------- Ruby code: -------------------- _buf << ' Name: '; _buf << ( text_field :stock, :name ).to_s; _buf << ' Name: '; -------------------- This shows that text_filed() is called every time when rendering, but pp_text_filed() is called only once when loading template, so pp_text_field() with prepocessing is much faster than text_field(). See User's guide for details. http://www.kuwata-lab.com/erubis/users-guide.05.html#rails-formhelpers # - release: 2.4.1 date: 2007-09-25 enhancements: - | Add new section 'evaluate(context) v.s. result(binding)' to user's guide. This section describes why Erubis::Eruby#evaluate(context) is recommended rather than Erubis::Eruby#result(binding). User's Guide > Other Topics > evaluate(context) v.s. result(binding) http://www.kuwata-lab.com/erubis/users-guide.06.html#topics-context-vs-binding - | Add new command-line property '--docwrite={true|false}' to Erubis::Ejavascript. If this property is true then 'document.write(_buf.join(""));' is used as postamble and if it is false then '_buf.join("")' is used. Default is true for compatibility reason but it will be false in the future release. (This feature was proposed by D.Dribin. Thank you.) bugfix: - | When using Erubis::Eruby#evaluate(), changing local variables in templates have affected to variables accessible with TOPLEVEL_BINDING. It means that if you change variables in templates, it is possible to change variables in main program. This was a bug and is now fixed not to affect to variables in main program. ex. template.rhtml -------------------- <% for x in @items %> item = <%= x %> <% end %> -------------------- ex. main-program.rb -------------------- require 'erubis' x = 10 items = ['foo', 'bar', 'baz'] eruby = Erubis::Eruby.new(File.read('template.rhtml')) s = eruby.evaluate(:items=>items) print s $stderr.puts "*** debug: x=#{x.inspect}" #=> x="baz" (2.4.0) #=> x=10 (2.4.1) -------------------- - | PercentLineEnhancer was very slow. Now performance problem is solved. # - release: 2.4.0 date: 2007-07-19 enhancements: - | Preprocessing is supported by Ruby on Rails helper. Preprocessing makes Ruby on Rails application about 20-40 percent faster. For example, [%= link_to 'Show', :action=>'show', :id=>_?('@user.id') %] is evaluate by preprocessor and expanded into the following when template file is loaded. Show It means that link_to() is not called when template is rendered and rendering speed will be much faster in the result. See User's Guide for details. - | Erubis::Eruby#evaluate() (or Erubis::RubyEvaluator#evaluate()) now creates Proc object from @src and eval it. def evaluate(context=Context.new) context = Context.new(context) if context.is_a?(Hash) @_proc ||= eval("proc { #{@src} }", TOPLEVEL_BINDING, @filename || '(erubis)') return context.instance_eval(&@_proc) end This makes evaluate() much faster when eruby object is reused. - | Erubis::Eruby#def_method() is supported. This method defines ruby code as instance method or singleton metod. require 'erubis' s = "hello <%= name %>" eruby = Erubis::Eruby.new(s) filename = 'hello.rhtml' ## define instance method to Dummy class (or module) class Dummy; end eruby.def_method(Dummy, 'render(name)', filename) # filename is optional p Dummy.new.render('world') #=> "hello world" ## define singleton method to an object obj = Object.new eruby.def_method(obj, 'render(name)', filename) # filename is optional p obj.render('world') #=> "hello world" This is equivarent to ERB#def_method(). - | Erubis::XmlHelper.url_escape() and u() which is alias of url_escape() are added. This is equivarent to ERB#Util.url_escape(). bugfix: - Help message was not shown when '-h' is specified. Fixed. - 'def method()' was not availabe in template file. Fixed. # - release: 2.3.1 date: 2007-05-26 bugfix: - A serious bug in 'helpers/rails_helper.rb' is fixed. You must be update if you are using Erubis with Ruby on Rails. # - release: 2.3.0 date: 2007-05-23 enhancements: - | New class 'Erubis::FastEruby' is added. It is a subclass of Erubis::Eruby and includes InterpolationEnhancer. Erubis::FastEruby is compatible with and faster than Erubis::Eruby. - | New enhancer 'InterpolationEnhancer' is added. This enhancer uses expression interpolation to eliminate method call of String#<<. In the result, this enhancer makes Eruby a little faster. -------------------- ## Assume that input is '<%=name%>'. ## Eruby convert input into the following code. String#<< is called 5 times. _buf << ''; _buf << (name).to_s; _buf << ''; ## When InterpolationEnhancer is used, String#<< is called only once. _buf << %Q`#{name}`; -------------------- - | New enhancer 'ErboutEnhancer' is added. ErboutEnhancer set '_erbout' as well as '_buf' to be compatible with ERB. ex. ==================== $ cat ex.rhtml

    Hello

    $ erubis -x ex.rhtml _buf = ''; _buf << '

    Hello

    '; _buf.to_s $ erubis -xE Erbout ex.rhtml _erbout = _buf = ''; _buf << '

    Hello

    '; _buf.to_s ==================== - | [experimental] New enhancer 'DeleteIndentEnhancer' is added. This enhancer deletes indentation of HTML file. ex. ==================== $ cat ex.rhtml
    $ erubis ex.rhtml
    $ erubis -E DeleteIndent ex.rhtml
    ==================== - | Mod_ruby is supported (very thanks to Andrew R Jackson!). See users-guide and 'contrib/erubis-run.rb' for details. - | New command-line option '-X', '-N', '-U', and '-C' are added. These are intended to be a replacement of 'notext' command. '-X' shows only ruby statements and expressions. '-N' adds line numbers. '-U' compress empty lines into a line. '-C' removes empty lines. changes: - | 'helpers/rails_helper.rb' is changed to use ErboutEnhancer. The following is an examle to use Erubis with Ruby on Rails. File 'config/environment.rb': ---------------------------------------- require 'erubis/helpers/rails_helper' #Erubis::Helpers::RailsHelper.engine_class = Erubis::Eruby # or Erubis::FastEruby #Erubis::Helpers::RailsHelper.init_properties = {} #Erubis::Helpers::RailsHelper.show_src = false # set true for debugging ---------------------------------------- - | Command 'notext' has been removed. Use '-X', '-N', '-U', and '-C' instead. - | Tab characters in YAML file are expaneded automatically. If you want not to expand tab characters, add command-line optio '-T'. - | Benchmark scripts (benchmark/bench.*) are rewrited. - | Users-guide (doc/users-guide.html) is updated. # - release: 2.2.0 date: 2007-02-11 enhancements: - | Performance tuned up. Release 2.2.0 works about 8 percent faster than 2.1.0. As a result, Erubis works more than 10 percent faster than eruby. (eruby is the extension module of eRuby written in C.) - | Support of Ruby on Rails improved. If you want to use Erubis with Ruby on Rails, add the following code into your 'config/environment.rb' and restart web server. This will set Erubis as eRuby compiler in Ruby on Rails instead of ERB. -------------------- require 'erubis/helpers/rails_helper' #Erubis::Helpers::RailsHelper.engine_class = Erubis::Eruby #Erubis::Helpers::RailsHelper.init_properties = {} #Erubis::Helpers::RailsHelper.show_src = true -------------------- Methods 'capture()' and 'content_for()' of ActionView::Helpers::CaptureHelper are available. Methd ActionView::Helpers::TextHelper#concat() is also available. If Erubis::Helpers::RailsHelper.show_src is ture, Erubis prints converted Ruby code into log file (such as 'log/development.log'). - | Erubis::Engine.load_file(filename) creates cache file (filename + '.cache') automatically if cache file is old or not exist. Caching makes Erubis about 40-50 percent faster. ex. -------------------- require 'erubis' eruby = Erubis::Eruby.load_file('example.rhtml') ## cache file 'example.rhtml.cache' is created automatically -------------------- - | Command-line option '-f datafile' can take Ruby script ('*.rb') as well as YAML file ('*.yaml' or '*.yml'). ex. ==================== $ cat context.rb @title = 'Example' @list = %w[AAA BBB CCC] $ cat example.rhtml

    <%= @title %>

    $ erubis -f context.rb example.rhtml

    Example

    ==================== - | New command-line option '-c context' support. It takes context string in YAML inline style or Ruby code style. ex. YAML inline style ==================== $ erubis -c '{title: Example, list: [AAA, BBB, CCC]}' example.rhtml ==================== ex. Ruby style ==================== $ erubis -c '@title="Example"; @list=%w[AAA BBB CCC]' example.rhtml ==================== - | New command-line option '-z' (syntax checking) support. It is similar to 'erubis -x file.rhtml | ruby -wc', but it can take several filenames. ex. ==================== $ erubis -z app/views/*/*.rhtml Syntax OK ==================== - | New constant Erubis::VERSION added. changes: - | Class Erubis::Eruby changed to include Erubis::StringBufferEnhancer instead of Erubis::ArrayBufferEnhancer. This is for Ruby on Rails support. ex. ==================== $ cat example.rhtml $ erubis -x example.rhtml _buf = ''; _buf << ' '; _buf.to_s ==================== - | Erubis::StringBufferEnhancer#add_postamble() prints "_buf.to_s" instead of "_buf". This is useful for 'erubis -x file.rhtml | ruby -wc'. - | Command-line option '-T' is removed. Use '--trim=false' instead. - | License is changed to MIT License. - | Embedded pattern '<%- -%>' can be handled. # - release: 2.1.0 date: 2006-09-23 enhancements: - | Ruby on Rails support. Add the following code to your 'app/controllers/application.rb' and restart web server. -------------------- require 'erubis/helper/rails' suffix = 'erubis' ActionView::Base.register_template_handler(suffix, Erubis::Helper::RailsTemplate) #Erubis::Helper::RailsTemplate.engine_class = Erubis::EscapedEruby ## or Erubis::PI::Eruby #Erubis::Helper::RailsTemplate.default_properties = { :escape=>true, :escapefunc=>'h' } -------------------- And rename your view template as 'xxx.erubis'. If you got the "(eval):10:in `render': no block given" error, use '@content_for_layout' instead 'yield' in your layout template. - | Another eRuby engine (PIEngine) support. This engine doesn't break HTML design because it uses Processing Instructions (PI) '' as embedded pattern instead of '<% .. %>'. example.rhtml --------------------
    @!{item}@
    -------------------- compile: ==================== $ erubis -x --pi example.rhtml _buf = []; _buf << ' '; @list.each_with_index do |item, i| klass = i % 2 == 0 ? 'odd' : 'even' _buf << ' '; end _buf << '
    '; _buf << (item).to_s; _buf << '
    '; _buf.join ==================== - | Add new command 'notext' which remove text part from eRuby script and leaves only Ruby code. This is very useful for debug of eRuby script. example2.rhtml -------------------- <% @list.each_with_index do |item, i| %> <% klass = i % 2 == 0 ? 'odd' : 'even' %> <% end %>
    <%== item %>
    -------------------- command line example: ==================== $ notext example2.rhtml _buf = []; @list.each_with_index do |item, i| ; klass = i % 2 == 0 ? 'odd' : 'even' ; _buf << ( klass ).to_s; _buf << Erubis::XmlHelper.escape_xml( item ); end ; _buf.join $ notext -nc example2.rhtml 1: _buf = []; 4: @list.each_with_index do |item, i| ; 5: klass = i % 2 == 0 ? 'odd' : 'even' ; 6: _buf << ( klass ).to_s; 7: _buf << Erubis::XmlHelper.escape_xml( item ); 9: end ; 13: _buf.join ==================== - | Add new enhance 'NoCode' which removes ruby code from eRuby script and leaves only HTML text part. It is very useful to validate HTML of eRuby script. command-line example: ==================== $ erubis -x -E NoCode example2.rhtml
    ==================== changes: - License is changed to LGPL. - Command-line property '--escape=name' is renamed to '--escapefunc=name'. - When command-line option '-l perl' is specified, function 'encode_entities()' is used ad escaping function which is available wth HTML::Entities module. bugfix: - There is a certain pattern which makes Engine#convert() too slow. Now Engne#convert() is fixed not to be slown. - Command name is now displayed when '-h' is specified. # - release: 2.0.1 date: 2006-06-21 bugfix: - some minor bugs are fixed # - release: 2.0.0 date: 2006-05-20 changes: - module 'PrintEnhancer' is renamed to 'PrintEnabledEnahncer' - module 'FastEnhancer' and class 'FastEruby' is obsolete because they are integrated into Eruby class - Eruby#evaluate() calls instance_eval() instead of eval() - XmlEruby.escape_xml() is moved to XmlHelper.escape_xml() enhancements: - multi programming language support (Ruby/PHP/C/Java/Scheme/Perl/Javascript) - class Eruby runs very fast because FastEnhancer module is integrated into Eruby by default - TinyEruby class (tiny.rb) is added - module ArrayBufferEnhancer added - module ArrayEnhancer added - module BiPatternEnhancer added - module EscapeEnhancer added - module HeaderFooterEnhancer added - module NoTextEnhancer added - module PercentLineEnhancer added - module PrintEnabledEnhancer added - module PrintOutEnhancer added - module SimplifyEnhancer added - module StringBufferEnhancer added - module StringIOEnhancer added - command-line option '-b' (body only) added - command-line option '-e' (escape) added - command-line option '-l' (lang) added - command-line option '-E' (enhancer) added - command-line option '-I' (require path) added - command-line option '-K' (kanji code) added - command-line option '-S' (string to symbol) added - command-line option '-B' (call result(binding())) added # - release: 1.1.0 date: 2006-03-05 enhancements: - '<%# ... %>' is supported - PrintEnhancer, PrintEruby, and PrintXmlEruby added - release: 1.0.1 date: 2006-02-01 bugfixes: - bin/erubis is available with RubyGems # - release: 1.0.0 date: 2006-02-01 bugfixes: - first release ruby-erubis-2.7.0/MIT-LICENSE000066400000000000000000000020731170760342400154320ustar00rootroot00000000000000copyright(c) 2006-2011 kuwata-lab.com all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ruby-erubis-2.7.0/README.txt000066400000000000000000000052631170760342400155000ustar00rootroot00000000000000= README release:: 2.7.0 copyright:: copyright(c) 2006-2011 kuwata-lab.com all rights reserved. == About Erubis Erubis is an implementation of eRuby. It has the following features. * Very fast, almost three times faster than ERB and even 10% faster than eruby * Multi-language support (Ruby/PHP/C/Java/Scheme/Perl/Javascript) * Auto escaping support * Auto trimming spaces around '<% %>' * Embedded pattern changeable (default '<% %>') * Enable to handle Processing Instructions (PI) as embedded pattern (ex. '') * Context object available and easy to combine eRuby template with YAML datafile * Print statement available * Easy to extend and customize in subclass * Ruby on Rails support Erubis is implemented in pure Ruby. It requires Ruby 1.8 or higher. Erubis now supports Ruby 1.9. See doc/users-guide.html for details. == Installation * If you have installed RubyGems, just type gem install erubis. $ sudo gem install erubis * Else install abstract[http://rubyforge.org/projects/abstract/] at first, and download erubis_X.X.X.tar.bz2 and install it by setup.rb. $ tar xjf abstract_X.X.X.tar.bz2 $ cd abstract_X.X.X/ $ sudo ruby setup.rb $ cd .. $ tar xjf erubis_X.X.X.tar.bz2 $ cd erubis_X.X.X/ $ sudo ruby setup.rb * (Optional) It is able to merge 'lib/**/*.rb' into 'bin/erubis' by 'contrib/inline-require' script. $ tar xjf erubis_X.X.X.tar.bz2 $ cd erubis_X.X.X/ $ cp /tmp/abstract_X.X.X/lib/abstract.rb lib $ unset RUBYLIB $ contrib/inline-require -I lib bin/erubis > contrib/erubis == Ruby on Rails Support Erubis supports Ruby on Rails. All you have to do is to add the following code into your 'config/environment.rb' and restart web server. require 'erubis/helpers/rails_helper' #Erubis::Helpers::RailsHelper.engine_class = Erubis::Eruby #Erubis::Helpers::RailsHelper.init_properties = {} #Erubis::Helpers::RailsHelper.show_src = nil If Erubis::Helpers::RailsHelper.show_src is ture, Erubis prints converted Ruby code into log file ('log/development.log' or so). It is useful for debug. == Exploring Guide If you are exploring Eruby, see the following class at first. * Erubis::TinyEruby (erubis/tiny.rb) -- the most simple eRuby implementation. * Erubis::Engine (erubis/engine.rb) -- base class of Eruby, Ephp, Ejava, and so on. * Erubis::Eruby (erubis/engine/eruby.rb) -- engine class for eRuby. * Erubis::Converter (erubis/converter.rb) -- convert eRuby script into Ruby code. == Benchmark 'benchmark/erubybenchmark.rb' is a benchmark script of Erubis. Try 'ruby erubybenchmark.rb' in benchmark directory. == License MIT License == Author makoto kuwata ruby-erubis-2.7.0/benchmark/000077500000000000000000000000001170760342400157265ustar00rootroot00000000000000ruby-erubis-2.7.0/benchmark/Makefile000066400000000000000000000000771170760342400173720ustar00rootroot00000000000000 bench: ruby bench.rb -n 10000 clean: rm -rf bench_*.rhtml* ruby-erubis-2.7.0/benchmark/bench.rb000066400000000000000000000200641170760342400173340ustar00rootroot00000000000000#!/usr/bin/env ruby ### ### $Release: 2.7.0 $ ### copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ### require 'erb' require 'erubis' require 'erubis/tiny' require 'erubis/engine/enhanced' require 'yaml' require 'cgi' include ERB::Util begin require 'eruby' rescue LoadError ERuby = nil end def File.write(filename, content) File.open(filename, 'w') { |f| f.write(content) } end ## change benchmark library to use $stderr instead of $stdout require 'benchmark' module Benchmark class Report def print(*args) $stderr.print(*args) end end module_function def print(*args) $stderr.print(*args) end end class BenchmarkApplication TARGETS = %w[eruby ERB ERB(cached) Erubis::Eruby Erubis::Eruby(cached) Erubis::FastEruby Erubis::FastEruby(cached) Erubis::TinyEruby Erubis::ArrayBufferEruby Erubis::PrintOutEruby Erubis::StdoutEruby ] def initialize(ntimes, context, targets=nil, params={}) @ntimes = ntimes @context = context @targets = targets && !targets.empty? ? targets : TARGETS.dup @testmode = params[:testmode] || 'execute' @erubyfile = params[:erubyfile] || 'erubybench.rhtml' @printout = params[:printout] || false end attr_accessor :ntimes, :targets attr_accessor :testmode, :erubyfile, :contextfile, :printout def context2code(context, varname='context') s = '' context.each { |k, | s << "#{k} = #{varname}[#{k.inspect}]; " } return s end def perform_benchmark width = 30 $stderr.puts "*** ntimes=#{@ntimes}, testmode=#{@testmode}" Benchmark.bm(width) do |job| for target in @targets do method = "#{@testmode}_#{target.gsub(/::|-|\(/, '_').gsub(/\)/, '').downcase}" #$stderr.puts "*** debug: method=#{method.inspect}" next unless self.respond_to?(method) filename = "bench_#{(target =~ /^(\w+)/) && $1.downcase}.rhtml" title = target output = nil job.report(title) do output = self.__send__(method, filename, @context) end File.write("output.#{target.gsub(/[^\w]/,'')}", output) if @printout && output && !output.empty? end end end ## def execute_eruby(filename, context) return unless ERuby #eval context2code(context) list = context['list'] @ntimes.times do ERuby.import(filename) end return nil end def execute_erb(filename, context) #eval context2code(context) list = context['list'] output = nil @ntimes.times do eruby = ERB.new(File.read(filename)) output = eruby.result(binding()) print output end return output end def execute_erb_cached(filename, context) #eval context2code(context) list = context['list'] output = nil cachefile = filename + '.cache' File.unlink(cachefile) if test(?f, cachefile) @ntimes.times do if !test(?f, cachefile) || File.mtime(filename) > File.mtime(cachefile) eruby = ERB.new(File.read(filename)) File.write(cachefile, eruby.src) else eruby = ERB.new('') #eruby.src = File.read(cachefile) eruby.instance_variable_set("@src", File.read(cachefile)) end output = eruby.result(binding()) print output end return output end ## no cached for klass in %w[Eruby FastEruby TinyEruby ArrayBufferEruby PrintOutEruby StdoutEruby] do s = <<-END def execute_erubis_#{klass.downcase}(filename, context) #eval context2code(context) list = context['list'] output = nil @ntimes.times do eruby = Erubis::#{klass}.new(File.read(filename)) output = eruby.result(binding()) print output end return output end END eval s end ## cached for klass in %w[Eruby FastEruby] do s = <<-END def execute_erubis_#{klass.downcase}_cached(filename, context) #eval context2code(context) list = context['list'] cachefile = filename + '.cache' File.unlink(cachefile) if test(?f, cachefile) output = nil @ntimes.times do eruby = Erubis::#{klass}.load_file(filename) output = eruby.result(binding()) print output end savefile = cachefile.sub(/\\.cache$/, '.#{klass.downcase}.cache') File.rename(cachefile, savefile) return output end END eval s end ## def convert_eruby(filename, context) return unless ERuby #eval context2code(context) list = context['list'] output = nil @ntimes.times do output = ERuby::Compiler.new.compile_string(File.read(filename)) end return output end def convert_erb(filename, context) #eval context2code(context) list = context['list'] output = nil @ntimes.times do eruby = ERB.new(File.read(filename)) output = eruby.src end return output end for klass in %w[Eruby FastEruby TinyEruby] s = <<-END def convert_erubis_#{klass.downcase}(filename, context) #eval context2code(context) list = context['list'] output = nil @ntimes.times do eruby = Erubis::#{klass}.new(File.read(filename)) output = eruby.src end return output end END eval s end end require 'optparse' class MainApplication def parse_argv(argv=ARGV) optparser = OptionParser.new options = {} ['-h', '-n N', '-t erubyfile', '-f contextfile', '-A', '-e', '-x exclude', '-m testmode', '-X', '-p', '-D'].each do |opt| optparser.on(opt) { |val| options[opt[1].chr] = val } end begin targets = optparser.parse!(argv) rescue => ex $stderr.puts "#{@script}: #{ex.to_s}" exit(1) end return options, targets end def execute @script = File.basename($0) ntimes = 1000 targets = BenchmarkApplication::TARGETS.dup testmode = 'execute' contextfile = 'bench_context.yaml' # options, args = parse_argv(ARGV) ntimes = options['n'].to_i if options['n'] targets = args if args && !args.empty? targets = targets - options['x'].split(/,/) if options['x'] testmode = options['m'] if options['m'] contextfile = options['f'] if options['f'] erubyfile = options['t'] if options['t'] # if options['h'] $stderr.puts "Usage: ruby #{@script} [..options..] [..targets..]" $stderr.puts " -h : help" $stderr.puts " -n N : loop N times" $stderr.puts " -f datafile : context data filename (*.yaml)" $stderr.puts " -x exclude : exclude target name" $stdout.puts " -m testmode : 'execute' or 'convert' (default 'execute')" $stderr.puts " -p : print output to file (filename: 'output.TARGETNAME')" return end # #if ! options['t'] for item in %w[eruby erb erubis] fname = "bench_#{item}.rhtml" header = File.read("templates/_header.html") #body = File.read("templates/#{erubyfile}") body = File.read("templates/#{fname}") footer = File.read("templates/_footer.html") content = header + body + footer File.write(fname, content) end # if options['e'] # escape tuples = [ [ 'bench_eruby.rhtml', '<%= CGI.escapeHTML((\1).to_s) %>' ], [ 'bench_erb.rhtml', '<%=h \1 %>' ], [ 'bench_erubis.rhtml', '<%== \1 %>' ], ] for fname, replace in tuples content = File.read(fname).gsub(/<%= ?(.*?) ?%>/, replace) File.write(fname, content) end targets.delete('Erubis::TinyEruby') ## because TinyEruby doesn't support '<%== =>' end # context = YAML.load_file(contextfile) # params = { :printout=>options['p'], :testmode=>testmode, } app = BenchmarkApplication.new(ntimes, context, targets, params) app.perform_benchmark() end end if __FILE__ == $0 ## open /dev/null $stdout = File.open('/dev/null', 'w') at_exit do $stdout.close() end ## start benchmark MainApplication.new().execute() end ruby-erubis-2.7.0/benchmark/bench_context.yaml000066400000000000000000000070521170760342400214410ustar00rootroot00000000000000list: - name: Adobe Systems name2: Adobe Systems Inc. url: http://www.adobe.com symbol: ADBE price: 39.26 change: 0.13 ratio: 0.33 - name: Advanced Micro Devices name2: Advanced Micro Devices Inc. url: http://www.amd.com symbol: AMD price: 16.22 change: 0.17 ratio: 1.06 - name: Amazon.com name2: Amazon.com Inc url: http://www.amazon.com symbol: AMZN price: 36.85 change: -0.23 ratio: -0.62 - name: Apple name2: Apple Inc. url: http://www.apple.com symbol: AAPL price: 85.38 change: -0.87 ratio: -1.01 - name: BEA Systems name2: BEA Systems Inc. url: http://www.bea.com symbol: BEAS price: 12.46 change: 0.09 ratio: 0.73 - name: CA name2: CA, Inc. url: http://www.ca.com symbol: CA price: 24.66 change: 0.38 ratio: 1.57 - name: Cisco Systems name2: Cisco Systems Inc. url: http://www.cisco.com symbol: CSCO price: 26.35 change: 0.13 ratio: 0.5 - name: Dell name2: Dell Corp. url: http://www.dell.com/ symbol: DELL price: 23.73 change: -0.42 ratio: -1.74 - name: eBay name2: eBay Inc. url: http://www.ebay.com symbol: EBAY price: 31.65 change: -0.8 ratio: -2.47 - name: Google name2: Google Inc. url: http://www.google.com symbol: GOOG price: 495.84 change: 7.75 ratio: 1.59 - name: Hewlett-Packard name2: Hewlett-Packard Co. url: http://www.hp.com symbol: HPQ price: 41.69 change: -0.02 ratio: -0.05 - name: IBM name2: International Business Machines Corp. url: http://www.ibm.com symbol: IBM price: 97.45 change: -0.06 ratio: -0.06 - name: Intel name2: Intel Corp. url: http://www.intel.com symbol: INTC price: 20.53 change: -0.07 ratio: -0.34 - name: Juniper Networks name2: Juniper Networks, Inc url: http://www.juniper.net/ symbol: JNPR price: 18.96 change: 0.5 ratio: 2.71 - name: Microsoft name2: Microsoft Corp url: http://www.microsoft.com symbol: MSFT price: 30.6 change: 0.15 ratio: 0.49 - name: Oracle name2: Oracle Corp. url: http://www.oracle.com symbol: ORCL price: 17.15 change: 0.17 ratio: 1.0 - name: SAP name2: SAP AG url: http://www.sap.com symbol: SAP price: 46.2 change: -0.16 ratio: -0.35 - name: Seagate Technology name2: Seagate Technology url: http://www.seagate.com/ symbol: STX price: 27.35 change: -0.36 ratio: -1.3 - name: Sun Microsystems name2: Sun Microsystems Inc. url: http://www.sun.com symbol: SUNW price: 6.33 change: -0.01 ratio: -0.16 - name: Yahoo name2: Yahoo! Inc. url: http://www.yahoo.com symbol: YHOO price: 28.04 change: -0.17 ratio: -0.6 ruby-erubis-2.7.0/benchmark/templates/000077500000000000000000000000001170760342400177245ustar00rootroot00000000000000ruby-erubis-2.7.0/benchmark/templates/_footer.html000066400000000000000000000000351170760342400222450ustar00rootroot00000000000000 ruby-erubis-2.7.0/benchmark/templates/_header.html000066400000000000000000000022071170760342400222020ustar00rootroot00000000000000 Stock Prices

    Stock Prices

    ruby-erubis-2.7.0/benchmark/templates/bench_erb.rhtml000066400000000000000000000012061170760342400227020ustar00rootroot00000000000000 <% n = 0 for item in list n += 1 %> <% if item['change'] < 0.0 %> <% else %> <% end %> <% end %> ruby-erubis-2.7.0/benchmark/templates/bench_erubis.rhtml000066400000000000000000000012061170760342400234230ustar00rootroot00000000000000 <% n = 0 for item in list n += 1 %> <% if item['change'] < 0.0 %> <% else %> <% end %> <% end %> ruby-erubis-2.7.0/benchmark/templates/bench_eruby.rhtml000066400000000000000000000012061170760342400232600ustar00rootroot00000000000000 <% n = 0 for item in list n += 1 %> <% if item['change'] < 0.0 %> <% else %> <% end %> <% end %> ruby-erubis-2.7.0/bin/000077500000000000000000000000001170760342400145445ustar00rootroot00000000000000ruby-erubis-2.7.0/bin/erubis000077500000000000000000000002421170760342400157610ustar00rootroot00000000000000#!/usr/bin/env ruby ### ### $Release: 2.7.0 $ ### copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ### require 'erubis/main' Erubis::Main.main(ARGV) ruby-erubis-2.7.0/contrib/000077500000000000000000000000001170760342400154345ustar00rootroot00000000000000ruby-erubis-2.7.0/contrib/erubis000077500000000000000000002421131170760342400166560ustar00rootroot00000000000000#!/usr/bin/env ruby ### ### $Release: 2.7.0 $ ### copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ### #--begin of require 'erubis/main' ### ### $Release: 2.7.0 $ ### copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ### require 'yaml' #--begin of require 'erubis' ## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## ## ## an implementation of eRuby ## ## ex. ## input = <<'END' ## ## END ## list = ['', 'b&b', '"ccc"'] ## eruby = Erubis::Eruby.new(input) ## puts "--- code ---" ## puts eruby.src ## puts "--- result ---" ## context = Erubis::Context.new() # or new(:list=>list) ## context[:list] = list ## puts eruby.evaluate(context) ## ## result: ## --- source --- ## _buf = ''; _buf << '
      ## '; for item in @list ## _buf << '
    • '; _buf << ( item ).to_s; _buf << ' ## '; _buf << ' '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '
    • ## '; end ## _buf << '
    ## '; ## _buf.to_s ## --- result --- ##
      ##
    • ## <aaa>
    • ##
    • b&b ## b&b
    • ##
    • "ccc" ## "ccc"
    • ##
    ## module Erubis VERSION = ('$Release: 2.7.0 $' =~ /([.\d]+)/) && $1 end #--begin of require 'erubis/engine' ## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## #--begin of require 'erubis/generator' ## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## #--begin of require 'erubis/util' ## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## module Kernel ## ## raise NotImplementedError ## def not_implemented #:doc: backtrace = caller() method_name = (backtrace.shift =~ /`(\w+)'$/) && $1 mesg = "class #{self.class.name} must implement abstract method '#{method_name}()'." #mesg = "#{self.class.name}##{method_name}() is not implemented." err = NotImplementedError.new mesg err.set_backtrace backtrace raise err end private :not_implemented end #--end of require 'erubis/util' module Erubis ## ## code generator, called by Converter module ## module Generator def self.supported_properties() # :nodoc: return [ [:escapefunc, nil, "escape function name"], ] end attr_accessor :escapefunc def init_generator(properties={}) @escapefunc = properties[:escapefunc] end ## (abstract) escape text string ## ## ex. ## def escape_text(text) ## return text.dump ## # or return "'" + text.gsub(/['\\]/, '\\\\\&') + "'" ## end def escape_text(text) not_implemented end ## return escaped expression code (ex. 'h(...)' or 'htmlspecialchars(...)') def escaped_expr(code) code.strip! return "#{@escapefunc}(#{code})" end ## (abstract) add @preamble to src def add_preamble(src) not_implemented end ## (abstract) add text string to src def add_text(src, text) not_implemented end ## (abstract) add statement code to src def add_stmt(src, code) not_implemented end ## (abstract) add expression literal code to src. this is called by add_expr(). def add_expr_literal(src, code) not_implemented end ## (abstract) add escaped expression code to src. this is called by add_expr(). def add_expr_escaped(src, code) not_implemented end ## (abstract) add expression code to src for debug. this is called by add_expr(). def add_expr_debug(src, code) not_implemented end ## (abstract) add @postamble to src def add_postamble(src) not_implemented end end end #--end of require 'erubis/generator' #--begin of require 'erubis/converter' ## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## #--already included require 'erubis/util' module Erubis ## ## convert ## module Converter attr_accessor :preamble, :postamble, :escape def self.supported_properties # :nodoc: return [ [:preamble, nil, "preamble (no preamble when false)"], [:postamble, nil, "postamble (no postamble when false)"], [:escape, nil, "escape expression or not in default"], ] end def init_converter(properties={}) @preamble = properties[:preamble] @postamble = properties[:postamble] @escape = properties[:escape] end ## convert input string into target language def convert(input) codebuf = "" # or [] @preamble.nil? ? add_preamble(codebuf) : (@preamble && (codebuf << @preamble)) convert_input(codebuf, input) @postamble.nil? ? add_postamble(codebuf) : (@postamble && (codebuf << @postamble)) @_proc = nil # clear cached proc object return codebuf # or codebuf.join() end protected ## ## detect spaces at beginning of line ## def detect_spaces_at_bol(text, is_bol) lspace = nil if text.empty? lspace = "" if is_bol elsif text[-1] == ?\n lspace = "" else rindex = text.rindex(?\n) if rindex s = text[rindex+1..-1] if s =~ /\A[ \t]*\z/ lspace = s #text = text[0..rindex] text[rindex+1..-1] = '' end else if is_bol && text =~ /\A[ \t]*\z/ #lspace = text #text = nil lspace = text.dup text[0..-1] = '' end end end return lspace end ## ## (abstract) convert input to code ## def convert_input(codebuf, input) not_implemented end end module Basic end ## ## basic converter which supports '<% ... %>' notation. ## module Basic::Converter include Erubis::Converter def self.supported_properties # :nodoc: return [ [:pattern, '<% %>', "embed pattern"], [:trim, true, "trim spaces around <% ... %>"], ] end attr_accessor :pattern, :trim def init_converter(properties={}) super(properties) @pattern = properties[:pattern] @trim = properties[:trim] != false end protected ## return regexp of pattern to parse eRuby script def pattern_regexp(pattern) @prefix, @postfix = pattern.split() # '<% %>' => '<%', '%>' #return /(.*?)(^[ \t]*)?#{@prefix}(=+|\#)?(.*?)-?#{@postfix}([ \t]*\r?\n)?/m #return /(^[ \t]*)?#{@prefix}(=+|\#)?(.*?)-?#{@postfix}([ \t]*\r?\n)?/m return /#{@prefix}(=+|-|\#|%)?(.*?)([-=])?#{@postfix}([ \t]*\r?\n)?/m end module_function :pattern_regexp #DEFAULT_REGEXP = /(.*?)(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m #DEFAULT_REGEXP = /(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m #DEFAULT_REGEXP = /<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m DEFAULT_REGEXP = pattern_regexp('<% %>') public def convert_input(src, input) pat = @pattern regexp = pat.nil? || pat == '<% %>' ? DEFAULT_REGEXP : pattern_regexp(pat) pos = 0 is_bol = true # is beginning of line input.scan(regexp) do |indicator, code, tailch, rspace| match = Regexp.last_match() len = match.begin(0) - pos text = input[pos, len] pos = match.end(0) ch = indicator ? indicator[0] : nil lspace = ch == ?= ? nil : detect_spaces_at_bol(text, is_bol) is_bol = rspace ? true : false add_text(src, text) if text && !text.empty? ## * when '<%= %>', do nothing ## * when '<% %>' or '<%# %>', delete spaces iff only spaces are around '<% %>' if ch == ?= # <%= %> rspace = nil if tailch && !tailch.empty? add_text(src, lspace) if lspace add_expr(src, code, indicator) add_text(src, rspace) if rspace elsif ch == ?\# # <%# %> n = code.count("\n") + (rspace ? 1 : 0) if @trim && lspace && rspace add_stmt(src, "\n" * n) else add_text(src, lspace) if lspace add_stmt(src, "\n" * n) add_text(src, rspace) if rspace end elsif ch == ?% # <%% %> s = "#{lspace}#{@prefix||='<%'}#{code}#{tailch}#{@postfix||='%>'}#{rspace}" add_text(src, s) else # <% %> if @trim && lspace && rspace add_stmt(src, "#{lspace}#{code}#{rspace}") else add_text(src, lspace) if lspace add_stmt(src, code) add_text(src, rspace) if rspace end end end #rest = $' || input # ruby1.8 rest = pos == 0 ? input : input[pos..-1] # ruby1.9 add_text(src, rest) end ## add expression code to src def add_expr(src, code, indicator) case indicator when '=' @escape ? add_expr_escaped(src, code) : add_expr_literal(src, code) when '==' @escape ? add_expr_literal(src, code) : add_expr_escaped(src, code) when '===' add_expr_debug(src, code) end end end module PI end ## ## Processing Instructions (PI) converter for XML. ## this class converts '' and '${...}' notation. ## module PI::Converter include Erubis::Converter def self.desc # :nodoc: "use processing instructions (PI) instead of '<% %>'" end def self.supported_properties # :nodoc: return [ [:trim, true, "trim spaces around <% ... %>"], [:pi, 'rb', "PI (Processing Instrunctions) name"], [:embchar, '@', "char for embedded expression pattern('@{...}@')"], [:pattern, '<% %>', "embed pattern"], ] end attr_accessor :pi, :prefix def init_converter(properties={}) super(properties) @trim = properties.fetch(:trim, true) @pi = properties[:pi] if properties[:pi] @embchar = properties[:embchar] || '@' @pattern = properties[:pattern] @pattern = '<% %>' if @pattern.nil? #|| @pattern == true end def convert(input) code = super(input) return @header || @footer ? "#{@header}#{code}#{@footer}" : code end protected def convert_input(codebuf, input) unless @regexp @pi ||= 'e' ch = Regexp.escape(@embchar) if @pattern left, right = @pattern.split(' ') @regexp = /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?|#{ch}(!*)?\{(.*?)\}#{ch}|#{left}(=+)(.*?)#{right}/m else @regexp = /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?|#{ch}(!*)?\{(.*?)\}#{ch}/m end end # is_bol = true pos = 0 input.scan(@regexp) do |pi_arg, stmt, rspace, indicator1, expr1, indicator2, expr2| match = Regexp.last_match len = match.begin(0) - pos text = input[pos, len] pos = match.end(0) lspace = stmt ? detect_spaces_at_bol(text, is_bol) : nil is_bol = stmt && rspace ? true : false add_text(codebuf, text) # unless text.empty? # if stmt if @trim && lspace && rspace add_pi_stmt(codebuf, "#{lspace}#{stmt}#{rspace}", pi_arg) else add_text(codebuf, lspace) if lspace add_pi_stmt(codebuf, stmt, pi_arg) add_text(codebuf, rspace) if rspace end else add_pi_expr(codebuf, expr1 || expr2, indicator1 || indicator2) end end #rest = $' || input # ruby1.8 rest = pos == 0 ? input : input[pos..-1] # ruby1.9 add_text(codebuf, rest) end #-- #def convert_input(codebuf, input) # parse_stmts(codebuf, input) # #parse_stmts2(codebuf, input) #end # #def parse_stmts(codebuf, input) # #regexp = pattern_regexp(@pattern) # @pi ||= 'e' # @stmt_pattern ||= /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?/m # is_bol = true # pos = 0 # input.scan(@stmt_pattern) do |pi_arg, code, rspace| # match = Regexp.last_match # len = match.begin(0) - pos # text = input[pos, len] # pos = match.end(0) # lspace = detect_spaces_at_bol(text, is_bol) # is_bol = rspace ? true : false # parse_exprs(codebuf, text) # unless text.empty? # if @trim && lspace && rspace # add_pi_stmt(codebuf, "#{lspace}#{code}#{rspace}", pi_arg) # else # add_text(codebuf, lspace) # add_pi_stmt(codebuf, code, pi_arg) # add_text(codebuf, rspace) # end # end # rest = $' || input # parse_exprs(codebuf, rest) #end # #def parse_exprs(codebuf, input) # unless @expr_pattern # ch = Regexp.escape(@embchar) # if @pattern # left, right = @pattern.split(' ') # @expr_pattern = /#{ch}(!*)?\{(.*?)\}#{ch}|#{left}(=+)(.*?)#{right}/ # else # @expr_pattern = /#{ch}(!*)?\{(.*?)\}#{ch}/ # end # end # pos = 0 # input.scan(@expr_pattern) do |indicator1, code1, indicator2, code2| # indicator = indicator1 || indicator2 # code = code1 || code2 # match = Regexp.last_match # len = match.begin(0) - pos # text = input[pos, len] # pos = match.end(0) # add_text(codebuf, text) # unless text.empty? # add_pi_expr(codebuf, code, indicator) # end # rest = $' || input # add_text(codebuf, rest) #end #++ def add_pi_stmt(codebuf, code, pi_arg) # :nodoc: case pi_arg when nil ; add_stmt(codebuf, code) when 'header' ; @header = code when 'footer' ; @footer = code when 'comment'; add_stmt(codebuf, "\n" * code.count("\n")) when 'value' ; add_expr_literal(codebuf, code) else ; add_stmt(codebuf, code) end end def add_pi_expr(codebuf, code, indicator) # :nodoc: case indicator when nil, '', '==' # @{...}@ or <%== ... %> @escape == false ? add_expr_literal(codebuf, code) : add_expr_escaped(codebuf, code) when '!', '=' # @!{...}@ or <%= ... %> @escape == false ? add_expr_escaped(codebuf, code) : add_expr_literal(codebuf, code) when '!!', '===' # @!!{...}@ or <%=== ... %> add_expr_debug(codebuf, code) else # ignore end end end end #--end of require 'erubis/converter' #--begin of require 'erubis/evaluator' ## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## #--begin of require 'erubis/error' ## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## module Erubis ## ## base error class ## class ErubisError < StandardError end ## ## raised when method or function is not supported ## class NotSupportedError < ErubisError end end #--end of require 'erubis/error' #--begin of require 'erubis/context' ## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## module Erubis ## ## context object for Engine#evaluate ## ## ex. ## template = <<'END' ## Hello <%= @user %>! ## <% for item in @list %> ## - <%= item %> ## <% end %> ## END ## ## context = Erubis::Context.new(:user=>'World', :list=>['a','b','c']) ## # or ## # context = Erubis::Context.new ## # context[:user] = 'World' ## # context[:list] = ['a', 'b', 'c'] ## ## eruby = Erubis::Eruby.new(template) ## print eruby.evaluate(context) ## class Context include Enumerable def initialize(hash=nil) hash.each do |name, value| self[name] = value end if hash end def [](key) return instance_variable_get("@#{key}") end def []=(key, value) return instance_variable_set("@#{key}", value) end def keys return instance_variables.collect { |name| name[1..-1] } end def each instance_variables.each do |name| key = name[1..-1] value = instance_variable_get(name) yield(key, value) end end def to_hash hash = {} self.keys.each { |key| hash[key] = self[key] } return hash end def update(context_or_hash) arg = context_or_hash if arg.is_a?(Hash) arg.each do |key, val| self[key] = val end else arg.instance_variables.each do |varname| key = varname[1..-1] val = arg.instance_variable_get(varname) self[key] = val end end end end end #--end of require 'erubis/context' module Erubis EMPTY_BINDING = binding() ## ## evaluate code ## module Evaluator def self.supported_properties # :nodoc: return [] end attr_accessor :src, :filename def init_evaluator(properties) @filename = properties[:filename] end def result(*args) raise NotSupportedError.new("evaluation of code except Ruby is not supported.") end def evaluate(*args) raise NotSupportedError.new("evaluation of code except Ruby is not supported.") end end ## ## evaluator for Ruby ## module RubyEvaluator include Evaluator def self.supported_properties # :nodoc: list = Evaluator.supported_properties return list end ## eval(@src) with binding object def result(_binding_or_hash=TOPLEVEL_BINDING) _arg = _binding_or_hash if _arg.is_a?(Hash) _b = binding() eval _arg.collect{|k,v| "#{k} = _arg[#{k.inspect}]; "}.join, _b elsif _arg.is_a?(Binding) _b = _arg elsif _arg.nil? _b = binding() else raise ArgumentError.new("#{self.class.name}#result(): argument should be Binding or Hash but passed #{_arg.class.name} object.") end return eval(@src, _b, (@filename || '(erubis')) end ## invoke context.instance_eval(@src) def evaluate(_context=Context.new) _context = Context.new(_context) if _context.is_a?(Hash) #return _context.instance_eval(@src, @filename || '(erubis)') #@_proc ||= eval("proc { #{@src} }", Erubis::EMPTY_BINDING, @filename || '(erubis)') @_proc ||= eval("proc { #{@src} }", binding(), @filename || '(erubis)') return _context.instance_eval(&@_proc) end ## if object is an Class or Module then define instance method to it, ## else define singleton method to it. def def_method(object, method_name, filename=nil) m = object.is_a?(Module) ? :module_eval : :instance_eval object.__send__(m, "def #{method_name}; #{@src}; end", filename || @filename || '(erubis)') end end end #--end of require 'erubis/evaluator' #--already included require 'erubis/context' module Erubis ## ## (abstract) abstract engine class. ## subclass must include evaluator and converter module. ## class Engine #include Evaluator #include Converter #include Generator def initialize(input=nil, properties={}) #@input = input init_generator(properties) init_converter(properties) init_evaluator(properties) @src = convert(input) if input end ## ## convert input string and set it to @src ## def convert!(input) @src = convert(input) end ## ## load file, write cache file, and return engine object. ## this method create code cache file automatically. ## cachefile name can be specified with properties[:cachename], ## or filname + 'cache' is used as default. ## def self.load_file(filename, properties={}) cachename = properties[:cachename] || (filename + '.cache') properties[:filename] = filename timestamp = File.mtime(filename) if test(?f, cachename) && timestamp == File.mtime(cachename) engine = self.new(nil, properties) engine.src = File.read(cachename) else input = File.open(filename, 'rb') {|f| f.read } engine = self.new(input, properties) tmpname = cachename + rand().to_s[1,8] File.open(tmpname, 'wb') {|f| f.write(engine.src) } File.rename(tmpname, cachename) File.utime(timestamp, timestamp, cachename) end engine.src.untaint # ok? return engine end ## ## helper method to convert and evaluate input text with context object. ## context may be Binding, Hash, or Object. ## def process(input, context=nil, filename=nil) code = convert(input) filename ||= '(erubis)' if context.is_a?(Binding) return eval(code, context, filename) else context = Context.new(context) if context.is_a?(Hash) return context.instance_eval(code, filename) end end ## ## helper method evaluate Proc object with contect object. ## context may be Binding, Hash, or Object. ## def process_proc(proc_obj, context=nil, filename=nil) if context.is_a?(Binding) filename ||= '(erubis)' return eval(proc_obj, context, filename) else context = Context.new(context) if context.is_a?(Hash) return context.instance_eval(&proc_obj) end end end # end of class Engine ## ## (abstract) base engine class for Eruby, Eperl, Ejava, and so on. ## subclass must include generator. ## class Basic::Engine < Engine include Evaluator include Basic::Converter include Generator end class PI::Engine < Engine include Evaluator include PI::Converter include Generator end end #--end of require 'erubis/engine' #require 'erubis/generator' #require 'erubis/converter' #require 'erubis/evaluator' #require 'erubis/error' #require 'erubis/context' #requier 'erubis/util' #--begin of require 'erubis/helper' ## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## module Erubis ## ## helper for xml ## module XmlHelper module_function ESCAPE_TABLE = { '&' => '&', '<' => '<', '>' => '>', '"' => '"', "'" => ''', } def escape_xml(value) value.to_s.gsub(/[&<>"]/) { |s| ESCAPE_TABLE[s] } # or /[&<>"']/ #value.to_s.gsub(/[&<>"]/) { ESCAPE_TABLE[$&] } end def escape_xml2(value) return value.to_s.gsub(/\&/,'&').gsub(//,'>').gsub(/"/,'"') end alias h escape_xml alias html_escape escape_xml def url_encode(str) return str.gsub(/[^-_.a-zA-Z0-9]+/) { |s| s.unpack('C*').collect { |i| "%%%02X" % i }.join } end alias u url_encode end end #--end of require 'erubis/helper' #--begin of require 'erubis/enhancer' ## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## module Erubis ## ## switch '<%= ... %>' to escaped and '<%== ... %>' to unescaped ## ## ex. ## class XmlEruby < Eruby ## include EscapeEnhancer ## end ## ## this is language-indenedent. ## module EscapeEnhancer def self.desc # :nodoc: "switch '<%= %>' to escaped and '<%== %>' to unescaped" end #-- #def self.included(klass) # klass.class_eval <<-END # alias _add_expr_literal add_expr_literal # alias _add_expr_escaped add_expr_escaped # alias add_expr_literal _add_expr_escaped # alias add_expr_escaped _add_expr_literal # END #end #++ def add_expr(src, code, indicator) case indicator when '=' @escape ? add_expr_literal(src, code) : add_expr_escaped(src, code) when '==' @escape ? add_expr_escaped(src, code) : add_expr_literal(src, code) when '===' add_expr_debug(src, code) end end end #-- ## (obsolete) #module FastEnhancer #end #++ ## ## use $stdout instead of string ## ## this is only for Eruby. ## module StdoutEnhancer def self.desc # :nodoc: "use $stdout instead of array buffer or string buffer" end def add_preamble(src) src << "#{@bufvar} = $stdout;" end def add_postamble(src) src << "\n''\n" end end ## ## use print statement instead of '_buf << ...' ## ## this is only for Eruby. ## module PrintOutEnhancer def self.desc # :nodoc: "use print statement instead of '_buf << ...'" end def add_preamble(src) end def add_text(src, text) src << " print '#{escape_text(text)}';" unless text.empty? end def add_expr_literal(src, code) src << " print((#{code}).to_s);" end def add_expr_escaped(src, code) src << " print #{escaped_expr(code)};" end def add_postamble(src) src << "\n" unless src[-1] == ?\n end end ## ## enable print function ## ## Notice: use Eruby#evaluate() and don't use Eruby#result() ## to be enable print function. ## ## this is only for Eruby. ## module PrintEnabledEnhancer def self.desc # :nodoc: "enable to use print function in '<% %>'" end def add_preamble(src) src << "@_buf = " super end def print(*args) args.each do |arg| @_buf << arg.to_s end end def evaluate(context=nil) _src = @src if context.is_a?(Hash) context.each do |key, val| instance_variable_set("@#{key}", val) end elsif context context.instance_variables.each do |name| instance_variable_set(name, context.instance_variable_get(name)) end end return instance_eval(_src, (@filename || '(erubis)')) end end ## ## return array instead of string ## ## this is only for Eruby. ## module ArrayEnhancer def self.desc # :nodoc: "return array instead of string" end def add_preamble(src) src << "#{@bufvar} = [];" end def add_postamble(src) src << "\n" unless src[-1] == ?\n src << "#{@bufvar}\n" end end ## ## use an Array object as buffer (included in Eruby by default) ## ## this is only for Eruby. ## module ArrayBufferEnhancer def self.desc # :nodoc: "use an Array object for buffering (included in Eruby class)" end def add_preamble(src) src << "_buf = [];" end def add_postamble(src) src << "\n" unless src[-1] == ?\n src << "_buf.join\n" end end ## ## use String class for buffering ## ## this is only for Eruby. ## module StringBufferEnhancer def self.desc # :nodoc: "use a String object for buffering" end def add_preamble(src) src << "#{@bufvar} = '';" end def add_postamble(src) src << "\n" unless src[-1] == ?\n src << "#{@bufvar}.to_s\n" end end ## ## use StringIO class for buffering ## ## this is only for Eruby. ## module StringIOEnhancer # :nodoc: def self.desc # :nodoc: "use a StringIO object for buffering" end def add_preamble(src) src << "#{@bufvar} = StringIO.new;" end def add_postamble(src) src << "\n" unless src[-1] == ?\n src << "#{@bufvar}.string\n" end end ## ## set buffer variable name to '_erbout' as well as '_buf' ## ## this is only for Eruby. ## module ErboutEnhancer def self.desc # :nodoc: "set '_erbout = _buf = \"\";' to be compatible with ERB." end def add_preamble(src) src << "_erbout = #{@bufvar} = '';" end def add_postamble(src) src << "\n" unless src[-1] == ?\n src << "#{@bufvar}.to_s\n" end end ## ## remove text and leave code, especially useful when debugging. ## ## ex. ## $ erubis -s -E NoText file.eruby | more ## ## this is language independent. ## module NoTextEnhancer def self.desc # :nodoc: "remove text and leave code (useful when debugging)" end def add_text(src, text) src << ("\n" * text.count("\n")) if text[-1] != ?\n text =~ /^(.*?)\z/ src << (' ' * $1.length) end end end ## ## remove code and leave text, especially useful when validating HTML tags. ## ## ex. ## $ erubis -s -E NoCode file.eruby | tidy -errors ## ## this is language independent. ## module NoCodeEnhancer def self.desc # :nodoc: "remove code and leave text (useful when validating HTML)" end def add_preamble(src) end def add_postamble(src) end def add_text(src, text) src << text end def add_expr(src, code, indicator) src << "\n" * code.count("\n") end def add_stmt(src, code) src << "\n" * code.count("\n") end end ## ## get convert faster, but spaces around '<%...%>' are not trimmed. ## ## this is language-independent. ## module SimplifyEnhancer def self.desc # :nodoc: "get convert faster but leave spaces around '<% %>'" end #DEFAULT_REGEXP = /(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m SIMPLE_REGEXP = /<%(=+|\#)?(.*?)-?%>/m def convert(input) src = "" add_preamble(src) #regexp = pattern_regexp(@pattern) pos = 0 input.scan(SIMPLE_REGEXP) do |indicator, code| match = Regexp.last_match index = match.begin(0) text = input[pos, index - pos] pos = match.end(0) add_text(src, text) if !indicator # <% %> add_stmt(src, code) elsif indicator[0] == ?\# # <%# %> n = code.count("\n") add_stmt(src, "\n" * n) else # <%= %> add_expr(src, code, indicator) end end #rest = $' || input # ruby1.8 rest = pos == 0 ? input : input[pos..-1] # ruby1.9 add_text(src, rest) add_postamble(src) return src end end ## ## enable to use other embedded expression pattern (default is '\[= =\]'). ## ## notice! this is an experimental. spec may change in the future. ## ## ex. ## input = < ## <%= item %> : <%== item %> ## [= item =] : [== item =] ## <% end %> ## END ## ## class BiPatternEruby ## include BiPatternEnhancer ## end ## eruby = BiPatternEruby.new(input, :bipattern=>'\[= =\]') ## list = ['', 'b&b', '"c"'] ## print eruby.result(binding()) ## ## ## output ## : <a> ## : <a> ## b&b : b&b ## b&b : b&b ## "c" : "c" ## "c" : "c" ## ## this is language independent. ## module BiPatternEnhancer def self.desc # :nodoc: "another embedded expression pattern (default '\[= =\]')." end def initialize(input, properties={}) self.bipattern = properties[:bipattern] # or '\$\{ \}' super end ## when pat is nil then '\[= =\]' is used def bipattern=(pat) # :nodoc: @bipattern = pat || '\[= =\]' pre, post = @bipattern.split() @bipattern_regexp = /(.*?)#{pre}(=*)(.*?)#{post}/m end def add_text(src, text) return unless text m = nil text.scan(@bipattern_regexp) do |txt, indicator, code| m = Regexp.last_match super(src, txt) add_expr(src, code, '=' + indicator) end #rest = $' || text # ruby1.8 rest = m ? text[m.end(0)..-1] : text # ruby1.9 super(src, rest) end end ## ## regards lines starting with '^[ \t]*%' as program code ## ## in addition you can specify prefix character (default '%') ## ## this is language-independent. ## module PrefixedLineEnhancer def self.desc # :nodoc: "regard lines matched to '^[ \t]*%' as program code" end def init_generator(properties={}) super @prefixchar = properties[:prefixchar] end def add_text(src, text) unless @prefixrexp @prefixchar ||= '%' @prefixrexp = Regexp.compile("^([ \\t]*)\\#{@prefixchar}(.*?\\r?\\n)") end pos = 0 text2 = '' text.scan(@prefixrexp) do space = $1 line = $2 space, line = '', $1 unless $2 match = Regexp.last_match len = match.begin(0) - pos str = text[pos, len] pos = match.end(0) if text2.empty? text2 = str else text2 << str end if line[0, 1] == @prefixchar text2 << space << line else super(src, text2) text2 = '' add_stmt(src, space + line) end end #rest = pos == 0 ? text : $' # ruby1.8 rest = pos == 0 ? text : text[pos..-1] # ruby1.9 unless text2.empty? text2 << rest if rest rest = text2 end super(src, rest) end end ## ## regards lines starting with '%' as program code ## ## this is for compatibility to eruby and ERB. ## ## this is language-independent. ## module PercentLineEnhancer include PrefixedLineEnhancer def self.desc # :nodoc: "regard lines starting with '%' as program code" end #-- #def init_generator(properties={}) # super # @prefixchar = '%' # @prefixrexp = /^\%(.*?\r?\n)/ #end #++ def add_text(src, text) unless @prefixrexp @prefixchar = '%' @prefixrexp = /^\%(.*?\r?\n)/ end super(src, text) end end ## ## [experimental] allow header and footer in eRuby script ## ## ex. ## ==================== ## ## without header and footer ## $ cat ex1.eruby ## <% def list_items(list) %> ## <% for item in list %> ##
  • <%= item %>
  • ## <% end %> ## <% end %> ## ## $ erubis -s ex1.eruby ## _buf = []; def list_items(list) ## ; for item in list ## ; _buf << '
  • '; _buf << ( item ).to_s; _buf << '
  • ## '; end ## ; end ## ; ## _buf.join ## ## ## with header and footer ## $ cat ex2.eruby ## ## <% for item in list %> ##
  • <%= item %>
  • ## <% end %> ## ## ## $ erubis -s -c HeaderFooterEruby ex4.eruby ## ## def list_items(list) ## _buf = []; _buf << ' ## '; for item in list ## ; _buf << '
  • '; _buf << ( item ).to_s; _buf << '
  • ## '; end ## ; _buf << ' ## '; ## _buf.join ## end ## ## ==================== ## ## this is language-independent. ## module HeaderFooterEnhancer def self.desc # :nodoc: "allow header/footer in document (ex. '')" end HEADER_FOOTER_PATTERN = /(.*?)(^[ \t]*)?([ \t]*\r?\n)?/m def add_text(src, text) m = nil text.scan(HEADER_FOOTER_PATTERN) do |txt, lspace, word, content, rspace| m = Regexp.last_match flag_trim = @trim && lspace && rspace super(src, txt) content = "#{lspace}#{content}#{rspace}" if flag_trim super(src, lspace) if !flag_trim && lspace instance_variable_set("@#{word}", content) super(src, rspace) if !flag_trim && rspace end #rest = $' || text # ruby1.8 rest = m ? text[m.end(0)..-1] : text # ruby1.9 super(src, rest) end attr_accessor :header, :footer def convert(input) source = super return @src = "#{@header}#{source}#{@footer}" end end ## ## delete indentation of HTML. ## ## this is language-independent. ## module DeleteIndentEnhancer def self.desc # :nodoc: "delete indentation of HTML." end def convert_input(src, input) input = input.gsub(/^[ \t]+<%=title%>" into "_buf << %Q`

    #{title}

    `" ## ## this is only for Eruby. ## module InterpolationEnhancer def self.desc # :nodoc: "convert '

    <%=text%>

    ' into '_buf << %Q`

    \#{text}

    `'" end def convert_input(src, input) pat = @pattern regexp = pat.nil? || pat == '<% %>' ? Basic::Converter::DEFAULT_REGEXP : pattern_regexp(pat) pos = 0 is_bol = true # is beginning of line str = '' input.scan(regexp) do |indicator, code, tailch, rspace| match = Regexp.last_match() len = match.begin(0) - pos text = input[pos, len] pos = match.end(0) ch = indicator ? indicator[0] : nil lspace = ch == ?= ? nil : detect_spaces_at_bol(text, is_bol) is_bol = rspace ? true : false _add_text_to_str(str, text) ## * when '<%= %>', do nothing ## * when '<% %>' or '<%# %>', delete spaces iff only spaces are around '<% %>' if ch == ?= # <%= %> rspace = nil if tailch && !tailch.empty? str << lspace if lspace add_expr(str, code, indicator) str << rspace if rspace elsif ch == ?\# # <%# %> n = code.count("\n") + (rspace ? 1 : 0) if @trim && lspace && rspace add_text(src, str) str = '' add_stmt(src, "\n" * n) else str << lspace if lspace add_text(src, str) str = '' add_stmt(src, "\n" * n) str << rspace if rspace end else # <% %> if @trim && lspace && rspace add_text(src, str) str = '' add_stmt(src, "#{lspace}#{code}#{rspace}") else str << lspace if lspace add_text(src, str) str = '' add_stmt(src, code) str << rspace if rspace end end end #rest = $' || input # ruby1.8 rest = pos == 0 ? input : input[pos..-1] # ruby1.9 _add_text_to_str(str, rest) add_text(src, str) end def add_text(src, text) return if !text || text.empty? #src << " _buf << %Q`" << text << "`;" if text[-1] == ?\n text[-1] = "\\n" src << " #{@bufvar} << %Q`#{text}`\n" else src << " #{@bufvar} << %Q`#{text}`;" end end def _add_text_to_str(str, text) return if !text || text.empty? str << text.gsub(/[`\#\\]/, '\\\\\&') end def add_expr_escaped(str, code) str << "\#{#{escaped_expr(code)}}" end def add_expr_literal(str, code) str << "\#{#{code}}" end end end #--end of require 'erubis/enhancer' #require 'erubis/tiny' #--begin of require 'erubis/engine/eruby' ## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## #--already included require 'erubis/engine' #--already included require 'erubis/enhancer' module Erubis ## ## code generator for Ruby ## module RubyGenerator include Generator #include ArrayBufferEnhancer include StringBufferEnhancer def init_generator(properties={}) super @escapefunc ||= "Erubis::XmlHelper.escape_xml" @bufvar = properties[:bufvar] || "_buf" end def self.supported_properties() # :nodoc: return [] end def escape_text(text) text.gsub(/['\\]/, '\\\\\&') # "'" => "\\'", '\\' => '\\\\' end def escaped_expr(code) return "#{@escapefunc}(#{code})" end #-- #def add_preamble(src) # src << "#{@bufvar} = [];" #end #++ def add_text(src, text) src << " #{@bufvar} << '" << escape_text(text) << "';" unless text.empty? end def add_stmt(src, code) #src << code << ';' src << code src << ';' unless code[-1] == ?\n end def add_expr_literal(src, code) src << " #{@bufvar} << (" << code << ').to_s;' end def add_expr_escaped(src, code) src << " #{@bufvar} << " << escaped_expr(code) << ';' end def add_expr_debug(src, code) code.strip! s = (code.dump =~ /\A"(.*)"\z/) && $1 src << ' $stderr.puts("*** debug: ' << s << '=#{(' << code << ').inspect}");' end #-- #def add_postamble(src) # src << "\n#{@bufvar}.join\n" #end #++ end ## ## engine for Ruby ## class Eruby < Basic::Engine include RubyEvaluator include RubyGenerator end ## ## fast engine for Ruby ## class FastEruby < Eruby include InterpolationEnhancer end ## ## swtich '<%= %>' to escaped and '<%== %>' to not escaped ## class EscapedEruby < Eruby include EscapeEnhancer end ## ## sanitize expression (<%= ... %>) by default ## ## this is equivalent to EscapedEruby and is prepared only for compatibility. ## class XmlEruby < Eruby include EscapeEnhancer end class PI::Eruby < PI::Engine include RubyEvaluator include RubyGenerator def init_converter(properties={}) @pi = 'rb' super(properties) end end end #--end of require 'erubis/engine/eruby' #require 'erubis/engine/enhanced' # enhanced eruby engines #require 'erubis/engine/optimized' # generates optimized ruby code #require 'erubis/engine/ephp' #require 'erubis/engine/ec' #require 'erubis/engine/ejava' #require 'erubis/engine/escheme' #require 'erubis/engine/eperl' #require 'erubis/engine/ejavascript' #--begin of require 'erubis/local-setting' ## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## ## ## you can add site-local settings here. ## this files is required by erubis.rb ## #--end of require 'erubis/local-setting' #--end of require 'erubis' #--begin of require 'erubis/tiny' ## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## module Erubis ## ## tiny and the simplest implementation of eRuby ## ## ex. ## eruby = TinyEruby.new(File.read('example.rhtml')) ## print eruby.src # print ruby code ## print eruby.result(binding()) # eval ruby code with Binding object ## print eruby.evalute(context) # eval ruby code with context object ## class TinyEruby def initialize(input=nil) @src = convert(input) if input end attr_reader :src EMBEDDED_PATTERN = /<%(=+|\#)?(.*?)-?%>/m def convert(input) src = "_buf = '';" # preamble pos = 0 input.scan(EMBEDDED_PATTERN) do |indicator, code| m = Regexp.last_match text = input[pos...m.begin(0)] pos = m.end(0) #src << " _buf << '" << escape_text(text) << "';" text.gsub!(/['\\]/, '\\\\\&') src << " _buf << '" << text << "';" unless text.empty? if !indicator # <% %> src << code << ";" elsif indicator == '#' # <%# %> src << ("\n" * code.count("\n")) else # <%= %> src << " _buf << (" << code << ").to_s;" end end #rest = $' || input # ruby1.8 rest = pos == 0 ? input : input[pos..-1] # ruby1.9 #src << " _buf << '" << escape_text(rest) << "';" rest.gsub!(/['\\]/, '\\\\\&') src << " _buf << '" << rest << "';" unless rest.empty? src << "\n_buf.to_s\n" # postamble return src end #def escape_text(text) # return text.gsub!(/['\\]/, '\\\\\&') || text #end def result(_binding=TOPLEVEL_BINDING) eval @src, _binding end def evaluate(_context=Object.new) if _context.is_a?(Hash) _obj = Object.new _context.each do |k, v| _obj.instance_variable_set("@#{k}", v) end _context = _obj end _context.instance_eval @src end end module PI end class PI::TinyEruby def initialize(input=nil, options={}) @escape = options[:escape] || 'Erubis::XmlHelper.escape_xml' @src = convert(input) if input end attr_reader :src EMBEDDED_PATTERN = /(^[ \t]*)?<\?rb(\s.*?)\?>([ \t]*\r?\n)?|@(!+)?\{(.*?)\}@/m def convert(input) src = "_buf = '';" # preamble pos = 0 input.scan(EMBEDDED_PATTERN) do |lspace, stmt, rspace, indicator, expr| match = Regexp.last_match len = match.begin(0) - pos text = input[pos, len] pos = match.end(0) #src << " _buf << '" << escape_text(text) << "';" text.gsub!(/['\\]/, '\\\\\&') src << " _buf << '" << text << "';" unless text.empty? if stmt # if lspace && rspace src << "#{lspace}#{stmt}#{rspace}" else src << " _buf << '" << lspace << "';" if lspace src << stmt << ";" src << " _buf << '" << rspace << "';" if rspace end else # ${...}, $!{...} if !indicator src << " _buf << " << @escape << "(" << expr << ");" elsif indicator == '!' src << " _buf << (" << expr << ").to_s;" end end end #rest = $' || input # ruby1.8 rest = pos == 0 ? input : input[pos..-1] # ruby1.9 #src << " _buf << '" << escape_text(rest) << "';" rest.gsub!(/['\\]/, '\\\\\&') src << " _buf << '" << rest << "';" unless rest.empty? src << "\n_buf.to_s\n" # postamble return src end #def escape_text(text) # return text.gsub!(/['\\]/, '\\\\\&') || text #end def result(_binding=TOPLEVEL_BINDING) eval @src, _binding end def evaluate(_context=Object.new) if _context.is_a?(Hash) _obj = Object.new _context.each do |k, v| _obj.instance_variable_set("@#{k}", v) end _context = _obj end _context.instance_eval @src end end end #--end of require 'erubis/tiny' #--begin of require 'erubis/engine/enhanced' ## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## #--already included require 'erubis/enhancer' #--already included require 'erubis/engine/eruby' module Erubis #-- ## moved to engine/ruby.rb #class EscapedEruby < Eruby # include EscapeEnhancer #end #++ #-- ### (obsolete) #class FastEruby < Eruby # include FastEnhancer #end #++ class StdoutEruby < Eruby include StdoutEnhancer end class PrintOutEruby < Eruby include PrintOutEnhancer end class PrintEnabledEruby < Eruby include PrintEnabledEnhancer end class ArrayEruby < Eruby include ArrayEnhancer end class ArrayBufferEruby < Eruby include ArrayBufferEnhancer end class StringBufferEruby < Eruby include StringBufferEnhancer end class StringIOEruby < Eruby include StringIOEnhancer end class ErboutEruby < Eruby include ErboutEnhancer end class NoTextEruby < Eruby include NoTextEnhancer end class NoCodeEruby < Eruby include NoCodeEnhancer end class SimplifiedEruby < Eruby include SimplifyEnhancer end class StdoutSimplifiedEruby < Eruby include StdoutEnhancer include SimplifyEnhancer end class PrintOutSimplifiedEruby < Eruby include PrintOutEnhancer include SimplifyEnhancer end class BiPatternEruby < Eruby include BiPatternEnhancer end class PercentLineEruby < Eruby include PercentLineEnhancer end class PrefixedLineEruby < Eruby include PrefixedLineEnhancer end class HeaderFooterEruby < Eruby include HeaderFooterEnhancer end class DeleteIndentEruby < Eruby include DeleteIndentEnhancer end class InterpolationEruby < Eruby include InterpolationEnhancer end end #--end of require 'erubis/engine/enhanced' #--begin of require 'erubis/engine/optimized' ## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## #--already included require 'erubis/engine/eruby' module Erubis module OptimizedGenerator include Generator def self.supported_properties() # :nodoc: return [] end def init_generator(properties={}) super @escapefunc ||= "Erubis::XmlHelper.escape_xml" @initialized = false @prev_is_expr = false end protected def escape_text(text) text.gsub(/['\\]/, '\\\\\&') # "'" => "\\'", '\\' => '\\\\' end def escaped_expr(code) @escapefunc ||= 'Erubis::XmlHelper.escape_xml' return "#{@escapefunc}(#{code})" end def switch_to_expr(src) return if @prev_is_expr @prev_is_expr = true src << ' _buf' end def switch_to_stmt(src) return unless @prev_is_expr @prev_is_expr = false src << ';' end def add_preamble(src) #@initialized = false #@prev_is_expr = false end def add_text(src, text) return if text.empty? if @initialized switch_to_expr(src) src << " << '" << escape_text(text) << "'" else src << "_buf = '" << escape_text(text) << "';" @initialized = true end end def add_stmt(src, code) switch_to_stmt(src) if @initialized #super src << code src << ';' unless code[-1] == ?\n end def add_expr_literal(src, code) unless @initialized; src << "_buf = ''"; @initialized = true; end switch_to_expr(src) src << " << (" << code << ").to_s" end def add_expr_escaped(src, code) unless @initialized; src << "_buf = ''"; @initialized = true; end switch_to_expr(src) src << " << " << escaped_expr(code) end def add_expr_debug(src, code) code.strip! s = (code.dump =~ /\A"(.*)"\z/) && $1 src << ' $stderr.puts("*** debug: ' << s << '=#{(' << code << ').inspect}");' end def add_postamble(src) #super if @initialized src << "\n_buf\n" if @initialized end end # end of class OptimizedEruby ## ## Eruby class which generates optimized ruby code ## class OptimizedEruby < Basic::Engine # Eruby include RubyEvaluator include OptimizedGenerator def init_converter(properties={}) @pi = 'rb' super(properties) end end ## ## XmlEruby class which generates optimized ruby code ## class OptimizedXmlEruby < OptimizedEruby include EscapeEnhancer def add_expr_debug(src, code) switch_to_stmt(src) if indicator == '===' && !@initialized super end end # end of class OptimizedXmlEruby end #--end of require 'erubis/engine/optimized' #--already included require 'erubis/engine/eruby' #--begin of require 'erubis/engine/ephp' ## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## #--already included require 'erubis/engine' #--already included require 'erubis/enhancer' module Erubis module PhpGenerator include Generator def self.supported_properties() # :nodoc: return [] end def init_generator(properties={}) super @escapefunc ||= 'htmlspecialchars' end def add_preamble(src) # empty end def escape_text(text) return text.gsub!(/<\?xml\b/, '<?xml') || text end def add_text(src, text) src << escape_text(text) end def add_expr_literal(src, code) code.strip! src << "" end def add_expr_escaped(src, code) add_expr_literal(src, escaped_expr(code)) end def add_expr_debug(src, code) code.strip! s = code.gsub(/\'/, "\\'") src << "" end def add_stmt(src, code) src << "\n" else src << code << "?>" end end def add_postamble(src) # empty end end ## ## engine for PHP ## class Ephp < Basic::Engine include PhpGenerator end class EscapedEphp < Ephp include EscapeEnhancer end #class XmlEphp < Ephp # include EscapeEnhancer #end class PI::Ephp < PI::Engine include PhpGenerator def init_converter(properties={}) @pi = 'php' super(properties) end end end #--end of require 'erubis/engine/ephp' #--begin of require 'erubis/engine/ec' ## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## #--already included require 'erubis/engine' #--already included require 'erubis/enhancer' module Erubis module CGenerator include Generator def self.supported_properties() # :nodoc: return [ [:indent, '', "indent spaces (ex. ' ')"], [:out, 'stdout', "output file pointer name"], ] end def init_generator(properties={}) super @escapefunc ||= "escape" @indent = properties[:indent] || '' @out = properties[:out] || 'stdout' end def add_preamble(src) src << "#line 1 \"#{self.filename}\"\n" if self.filename end def escape_text(text) @@table_ ||= { "\r"=>"\\r", "\n"=>"\\n", "\t"=>"\\t", '"'=>'\\"', "\\"=>"\\\\" } text.gsub!(/[\r\n\t"\\]/) { |m| @@table_[m] } return text end def escaped_expr(code) return "#{@escapefunc}(#{code.strip}, #{@out})" end def add_text(src, text) return if text.empty? src << (src.empty? || src[-1] == ?\n ? @indent : ' ') src << "fputs(" i = 0 text.each_line do |line| src << "\n" << @indent << ' ' if i > 0 i += 1 src << '"' << escape_text(line) << '"' end src << ", #{@out});" #<< (text[-1] == ?\n ? "\n" : "") src << "\n" if text[-1] == ?\n end def add_stmt(src, code) src << code end def add_expr_literal(src, code) src << @indent if src.empty? || src[-1] == ?\n src << " fprintf(#{@out}, " << code.strip << ');' end def add_expr_escaped(src, code) src << @indent if src.empty? || src[-1] == ?\n src << ' ' << escaped_expr(code) << ';' end def add_expr_debug(src, code) code.strip! s = nil if code =~ /\A\".*?\"\s*,\s*(.*)/ s = $1.gsub(/[%"]/, '\\\1') + '=' end src << @indent if src.empty? || src[-1] == ?\n src << " fprintf(stderr, \"*** debug: #{s}\" #{code});" end def add_postamble(src) # empty end end ## ## engine for C ## class Ec < Basic::Engine include CGenerator end class EscapedEc < Ec include EscapeEnhancer end #class XmlEc < Ec # include EscapeEnhancer #end class PI::Ec < PI::Engine include CGenerator def init_converter(properties={}) @pi = 'c' super(properties) end end end #--end of require 'erubis/engine/ec' #--begin of require 'erubis/engine/ecpp' ## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## #--already included require 'erubis/engine' #--already included require 'erubis/enhancer' module Erubis module CppGenerator include Generator def self.supported_properties() # :nodoc: return [ [:indent, '', "indent spaces (ex. ' ')"], [:bufvar, '_buf', "buffer variable name"], ] end def init_generator(properties={}) super @escapefunc ||= "escape" @indent = properties[:indent] || '' @bufvar = properties[:bufvar] || '_buf' end def add_preamble(src) src << "#line 1 \"#{self.filename}\"\n" if self.filename end def escape_text(text) @@table_ ||= { "\r"=>"\\r", "\n"=>"\\n", "\t"=>"\\t", '"'=>'\\"', "\\"=>"\\\\" } text.gsub!(/[\r\n\t"\\]/) { |m| @@table_[m] } return text end def escaped_expr(code) return "#{@escapefunc}(#{code.strip})" end def add_text(src, text) return if text.empty? src << (src.empty? || src[-1] == ?\n ? @indent : ' ') src << "_buf << " i = 0 text.each_line do |line| src << "\n" << @indent << " " if i > 0 i += 1 src << '"' << escape_text(line) << '"' end src << ";" #<< (text[-1] == ?\n ? "\n" : "") src << "\n" if text[-1] == ?\n end def add_stmt(src, code) src << code end def add_expr_literal(src, code) src << @indent if src.empty? || src[-1] == ?\n src << " _buf << (" << code.strip << ");" end def add_expr_escaped(src, code) src << @indent if src.empty? || src[-1] == ?\n src << ' ' << escaped_expr(code) << ';' end def add_expr_debug(src, code) code.strip! src << @indent if src.empty? || src[-1] == ?\n src << " std::cerr << \"*** debug: #{code.gsub(/(")/, '\\\&')}=\" << (#{code});" end def add_postamble(src) # empty end end ## ## engine for C ## class Ecpp < Basic::Engine include CppGenerator end class EscapedEcpp < Ecpp include EscapeEnhancer end #class XmlEcpp < Ecpp # include EscapeEnhancer #end class PI::Ecpp < PI::Engine include CppGenerator def init_converter(properties={}) @pi = 'cpp' super(properties) end end end #--end of require 'erubis/engine/ecpp' #--begin of require 'erubis/engine/ejava' ## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## #--already included require 'erubis/engine' #--already included require 'erubis/enhancer' module Erubis module JavaGenerator include Generator def self.supported_properties() # :nodoc: return [ [:indent, '', "indent spaces (ex. ' ')"], [:bufvar, '_buf', "output buffer variable name"], [:bufclass, 'StringBuffer', "output buffer class (ex. 'StringBuilder')"], ] end def init_generator(properties={}) super @escapefunc ||= 'escape' @indent = properties[:indent] || '' @bufvar = properties[:bufvar] || '_buf' @bufclass = properties[:bufclass] || 'StringBuffer' end def add_preamble(src) src << "#{@indent}#{@bufclass} #{@bufvar} = new #{@bufclass}();" end def escape_text(text) @@table_ ||= { "\r"=>"\\r", "\n"=>"\\n", "\t"=>"\\t", '"'=>'\\"', "\\"=>"\\\\" } return text.gsub!(/[\r\n\t"\\]/) { |m| @@table_[m] } || text end def add_text(src, text) return if text.empty? src << (src.empty? || src[-1] == ?\n ? @indent : ' ') src << @bufvar << ".append(" i = 0 text.each_line do |line| src << "\n" << @indent << ' + ' if i > 0 i += 1 src << '"' << escape_text(line) << '"' end src << ");" << (text[-1] == ?\n ? "\n" : "") end def add_stmt(src, code) src << code end def add_expr_literal(src, code) src << @indent if src.empty? || src[-1] == ?\n code.strip! src << " #{@bufvar}.append(#{code});" end def add_expr_escaped(src, code) add_expr_literal(src, escaped_expr(code)) end def add_expr_debug(src, code) code.strip! src << @indent if src.empty? || src[-1] == ?\n src << " System.err.println(\"*** debug: #{code}=\"+(#{code}));" end def add_postamble(src) src << "\n" if src[-1] == ?; src << @indent << "return " << @bufvar << ".toString();\n" #src << @indent << "System.out.print(" << @bufvar << ".toString());\n" end end ## ## engine for Java ## class Ejava < Basic::Engine include JavaGenerator end class EscapedEjava < Ejava include EscapeEnhancer end #class XmlEjava < Ejava # include EscapeEnhancer #end class PI::Ejava < PI::Engine include JavaGenerator def init_converter(properties={}) @pi = 'java' super(properties) end end end #--end of require 'erubis/engine/ejava' #--begin of require 'erubis/engine/escheme' ## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## #--already included require 'erubis/engine' #--already included require 'erubis/enhancer' module Erubis module SchemeGenerator include Generator def self.supported_properties() # :nodoc: return [ [:func, '_add', "function name (ex. 'display')"], ] end def init_generator(properties={}) super @escapefunc ||= 'escape' @func = properties[:func] || '_add' # or 'display' end def add_preamble(src) return unless @func == '_add' src << "(let ((_buf '())) " + \ "(define (_add x) (set! _buf (cons x _buf))) " #src << "(let* ((_buf '())" + \ # " (_add (lambda (x) (set! _buf (cons x _buf))))) " end def escape_text(text) @table_ ||= { '"'=>'\\"', '\\'=>'\\\\' } text.gsub!(/["\\]/) { |m| @table_[m] } return text end def escaped_expr(code) code.strip! return "(#{@escapefunc} #{code})" end def add_text(src, text) return if text.empty? t = escape_text(text) if t[-1] == ?\n t[-1, 1] = '' src << "(#{@func} \"" << t << "\\n\")\n" else src << "(#{@func} \"" << t << '")' end end def add_stmt(src, code) src << code end def add_expr_literal(src, code) code.strip! src << "(#{@func} #{code})" end def add_expr_escaped(src, code) add_expr_literal(src, escaped_expr(code)) end def add_expr_debug(src, code) s = (code.strip! || code).gsub(/\"/, '\\"') src << "(display \"*** debug: #{s}=\")(display #{code.strip})(display \"\\n\")" end def add_postamble(src) return unless @func == '_add' src << "\n" unless src[-1] == ?\n src << " (reverse _buf))\n" end end ## ## engine for Scheme ## class Escheme < Basic::Engine include SchemeGenerator end class EscapedEscheme < Escheme include EscapeEnhancer end #class XmlEscheme < Escheme # include EscapeEnhancer #end class PI::Escheme < PI::Engine include SchemeGenerator def init_converter(properties={}) @pi = 'scheme' super(properties) end end end #--end of require 'erubis/engine/escheme' #--begin of require 'erubis/engine/eperl' ## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## #--already included require 'erubis/engine' #--already included require 'erubis/enhancer' module Erubis module PerlGenerator include Generator def self.supported_properties() # :nodoc: return [ [:func, 'print', "function name"], ] end def init_generator(properties={}) super @escapefunc ||= 'encode_entities' @func = properties[:func] || 'print' end def add_preamble(src) src << "use HTML::Entities; "; end def escape_text(text) return text.gsub!(/['\\]/, '\\\\\&') || text end def add_text(src, text) src << @func << "('" << escape_text(text) << "'); " unless text.empty? end def add_expr_literal(src, code) code.strip! src << @func << "(" << code << "); " end def add_expr_escaped(src, code) add_expr_literal(src, escaped_expr(code)) end def add_expr_debug(src, code) code.strip! s = code.gsub(/\'/, "\\'") src << @func << "('*** debug: #{code}=', #{code}, \"\\n\");" end def add_stmt(src, code) src << code end def add_postamble(src) src << "\n" unless src[-1] == ?\n end end ## ## engine for Perl ## class Eperl < Basic::Engine include PerlGenerator end class EscapedEperl < Eperl include EscapeEnhancer end #class XmlEperl < Eperl # include EscapeEnhancer #end class PI::Eperl < PI::Engine include PerlGenerator def init_converter(properties={}) @pi = 'perl' super(properties) end end end #--end of require 'erubis/engine/eperl' #--begin of require 'erubis/engine/ejavascript' ## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## #--already included require 'erubis/engine' #--already included require 'erubis/enhancer' module Erubis module JavascriptGenerator include Generator def self.supported_properties() # :nodoc: list = [] #list << [:indent, '', "indent spaces (ex. ' ')"] #list << [:bufvar, '_buf', "output buffer variable name"] list << [:docwrite, true, "use 'document.write()' when true"] return list end def init_generator(properties={}) super @escapefunc ||= 'escape' @indent = properties[:indent] || '' @bufvar = properties[:bufvar] || '_buf' @docwrite = properties[:docwrite] != false # '!= false' will be removed in the next release end def add_preamble(src) src << "#{@indent}var #{@bufvar} = [];" end def escape_text(text) @@table_ ||= { "\r"=>"\\r", "\n"=>"\\n\\\n", "\t"=>"\\t", '"'=>'\\"', "\\"=>"\\\\" } return text.gsub!(/[\r\n\t"\\]/) { |m| @@table_[m] } || text end def add_indent(src, indent) src << (src.empty? || src[-1] == ?\n ? indent : ' ') end def add_text(src, text) return if text.empty? add_indent(src, @indent) src << @bufvar << '.push("' s = escape_text(text) if s[-1] == ?\n s[-2, 2] = '' src << s << "\");\n" else src << s << "\");" end end def add_stmt(src, code) src << code end def add_expr_literal(src, code) add_indent(src, @indent) code.strip! src << "#{@bufvar}.push(#{code});" end def add_expr_escaped(src, code) add_expr_literal(src, escaped_expr(code)) end def add_expr_debug(src, code) add_indent(src, @indent) code.strip! src << "alert(\"*** debug: #{code}=\"+(#{code}));" end def add_postamble(src) src << "\n" if src[-1] == ?; if @docwrite src << @indent << 'document.write(' << @bufvar << ".join(\"\"));\n" else src << @indent << @bufvar << ".join(\"\");\n" end end end ## ## engine for JavaScript ## class Ejavascript < Basic::Engine include JavascriptGenerator end class EscapedEjavascript < Ejavascript include EscapeEnhancer end #class XmlEjavascript < Ejavascript # include EscapeEnhancer #end class PI::Ejavascript < PI::Engine include JavascriptGenerator def init_converter(properties={}) @pi = 'js' super(properties) end end end #--end of require 'erubis/engine/ejavascript' module Erubis Ejs = Ejavascript EscapedEjs = EscapedEjavascript class CommandOptionError < ErubisError end ## ## main class of command ## ## ex. ## Main.main(ARGV) ## class Main def self.main(argv=ARGV) status = 0 begin Main.new.execute(ARGV) rescue CommandOptionError => ex $stderr.puts ex.message status = 1 end exit(status) end def initialize @single_options = "hvxztTSbeBXNUC" @arg_options = "pcrfKIlaE" #C @option_names = { 'h' => :help, 'v' => :version, 'x' => :source, 'z' => :syntax, 'T' => :unexpand, 't' => :untabify, # obsolete 'S' => :intern, 'b' => :bodyonly, 'B' => :binding, 'p' => :pattern, 'c' => :context, #'C' => :class, 'e' => :escape, 'r' => :requires, 'f' => :datafiles, 'K' => :kanji, 'I' => :includes, 'l' => :lang, 'a' => :action, 'E' => :enhancers, 'X' => :notext, 'N' => :linenum, 'U' => :unique, 'C' => :compact, } assert unless @single_options.length + @arg_options.length == @option_names.length (@single_options + @arg_options).each_byte do |ch| assert unless @option_names.key?(ch.chr) end end def execute(argv=ARGV) ## parse command-line options options, properties = parse_argv(argv, @single_options, @arg_options) filenames = argv options['h'] = true if properties[:help] opts = Object.new arr = @option_names.collect {|ch, name| "def #{name}; @#{name}; end\n" } opts.instance_eval arr.join options.each do |ch, val| name = @option_names[ch] opts.instance_variable_set("@#{name}", val) end ## help, version, enhancer list if opts.help || opts.version puts version() if opts.version puts usage() if opts.help puts show_properties() if opts.help puts show_enhancers() if opts.help return end ## include path opts.includes.split(/,/).each do |path| $: << path end if opts.includes ## require library opts.requires.split(/,/).each do |library| require library end if opts.requires ## action action = opts.action action ||= 'syntax' if opts.syntax action ||= 'convert' if opts.source || opts.notext ## lang lang = opts.lang || 'ruby' action ||= 'convert' if opts.lang ## class name of Eruby #classname = opts.class classname = nil klass = get_classobj(classname, lang, properties[:pi]) ## kanji code $KCODE = opts.kanji if opts.kanji ## read context values from yaml file datafiles = opts.datafiles context = load_datafiles(datafiles, opts) ## parse context data if opts.context context = parse_context_data(opts.context, opts) end ## properties for engine properties[:escape] = true if opts.escape && !properties.key?(:escape) properties[:pattern] = opts.pattern if opts.pattern #properties[:trim] = false if opts.notrim properties[:preamble] = properties[:postamble] = false if opts.bodyonly properties[:pi] = nil if properties[:pi] == true ## create engine and extend enhancers engine = klass.new(nil, properties) enhancers = get_enhancers(opts.enhancers) #enhancers.push(Erubis::EscapeEnhancer) if opts.escape enhancers.each do |enhancer| engine.extend(enhancer) engine.bipattern = properties[:bipattern] if enhancer == Erubis::BiPatternEnhancer end ## no-text engine.extend(Erubis::NoTextEnhancer) if opts.notext ## convert and execute val = nil msg = "Syntax OK\n" if filenames && !filenames.empty? filenames.each do |filename| File.file?(filename) or raise CommandOptionError.new("#{filename}: file not found.") engine.filename = filename engine.convert!(File.read(filename)) val = do_action(action, engine, context, filename, opts) msg = nil if val end else engine.filename = filename = '(stdin)' engine.convert!($stdin.read()) val = do_action(action, engine, context, filename, opts) msg = nil if val end print msg if action == 'syntax' && msg end private def do_action(action, engine, context, filename, opts) case action when 'convert' s = manipulate_src(engine.src, opts) when nil, 'exec', 'execute' s = opts.binding ? engine.result(context.to_hash) : engine.evaluate(context) when 'syntax' s = check_syntax(filename, engine.src) else raise "*** internal error" end print s if s return s end def manipulate_src(source, opts) flag_linenum = opts.linenum flag_unique = opts.unique flag_compact = opts.compact if flag_linenum n = 0 source.gsub!(/^/) { n += 1; "%5d: " % n } source.gsub!(/^ *\d+:\s+?\n/, '') if flag_compact source.gsub!(/(^ *\d+:\s+?\n)+/, "\n") if flag_unique else source.gsub!(/^\s*?\n/, '') if flag_compact source.gsub!(/(^\s*?\n)+/, "\n") if flag_unique end return source end def usage(command=nil) command ||= File.basename($0) buf = [] buf << "erubis - embedded program converter for multi-language" buf << "Usage: #{command} [..options..] [file ...]" buf << " -h, --help : help" buf << " -v : version" buf << " -x : show converted code" buf << " -X : show converted code, only ruby code and no text part" buf << " -N : numbering: add line numbers (for '-x/-X')" buf << " -U : unique: compress empty lines to a line (for '-x/-X')" buf << " -C : compact: remove empty lines (for '-x/-X')" buf << " -b : body only: no preamble nor postamble (for '-x/-X')" buf << " -z : syntax checking" buf << " -e : escape (equal to '--E Escape')" buf << " -p pattern : embedded pattern (default '<% %>')" buf << " -l lang : convert but no execute (ruby/php/c/cpp/java/scheme/perl/js)" buf << " -E e1,e2,... : enhancer names (Escape, PercentLine, BiPattern, ...)" buf << " -I path : library include path" buf << " -K kanji : kanji code (euc/sjis/utf8) (default none)" buf << " -c context : context data string (yaml inline style or ruby code)" buf << " -f datafile : context data file ('*.yaml', '*.yml', or '*.rb')" #buf << " -t : expand tab characters in YAML file" buf << " -T : don't expand tab characters in YAML file" buf << " -S : convert mapping key from string to symbol in YAML file" buf << " -B : invoke 'result(binding)' instead of 'evaluate(context)'" buf << " --pi=name : parse '' instead of '<% ... %>'" #' # -T : don't trim spaces around '<% %>' # -c class : class name (XmlEruby/PercentLineEruby/...) (default Eruby) # -r library : require library # -a : action (convert/execute) return buf.join("\n") end def collect_supported_properties(erubis_klass) list = [] erubis_klass.ancestors.each do |klass| if klass.respond_to?(:supported_properties) list.concat(klass.supported_properties) end end return list end def show_properties s = "supported properties:\n" basic_props = collect_supported_properties(Erubis::Basic::Engine) pi_props = collect_supported_properties(Erubis::PI::Engine) list = [] common_props = basic_props & pi_props list << ['(common)', common_props] list << ['(basic)', basic_props - common_props] list << ['(pi)', pi_props - common_props] %w[ruby php c cpp java scheme perl javascript].each do |lang| klass = Erubis.const_get("E#{lang}") list << [lang, collect_supported_properties(klass) - basic_props] end list.each do |lang, props| s << " * #{lang}\n" props.each do |name, default_val, desc| s << (" --%-23s : %s\n" % ["#{name}=#{default_val.inspect}", desc]) end end s << "\n" return s end def show_enhancers dict = {} ObjectSpace.each_object(Module) do |mod| dict[$1] = mod if mod.name =~ /\AErubis::(.*)Enhancer\z/ end s = "enhancers:\n" dict.sort_by {|name, mod| name }.each do |name, mod| s << (" %-13s : %s\n" % [name, mod.desc]) end return s end def version return Erubis::VERSION end def parse_argv(argv, arg_none='', arg_required='', arg_optional='') options = {} context = {} while argv[0] && argv[0][0] == ?- optstr = argv.shift optstr = optstr[1, optstr.length-1] # if optstr[0] == ?- # context optstr =~ /\A\-([-\w]+)(?:=(.*))?/ or raise CommandOptionError.new("-#{optstr}: invalid context value.") name, value = $1, $2 name = name.gsub(/-/, '_').intern #value = value.nil? ? true : YAML.load(value) # error, why? value = value.nil? ? true : YAML.load("---\n#{value}\n") context[name] = value # else # options while optstr && !optstr.empty? optchar = optstr[0].chr optstr = optstr[1..-1] if arg_none.include?(optchar) options[optchar] = true elsif arg_required.include?(optchar) arg = optstr.empty? ? argv.shift : optstr or raise CommandOptionError.new("-#{optchar}: #{@option_names[optchar]} required.") options[optchar] = arg optstr = nil elsif arg_optional.include?(optchar) arg = optstr.empty? ? true : optstr options[optchar] = arg optstr = nil else raise CommandOptionError.new("-#{optchar}: unknown option.") end end end # end # end of while return options, context end def untabify(str, width=8) list = str.split(/\t/) last = list.pop sb = '' list.each do |s| column = (n = s.rindex(?\n)) ? s.length - n - 1 : s.length n = width - (column % width) sb << s << (' ' * n) end sb << last return sb end #-- #def untabify(str, width=8) # sb = '' # str.scan(/(.*?)\t/m) do |s, | # len = (n = s.rindex(?\n)) ? s.length - n - 1 : s.length # sb << s << (" " * (width - len % width)) # end # return $' ? (sb << $') : str #end #++ def get_classobj(classname, lang, pi) classname ||= "E#{lang}" base_module = pi ? Erubis::PI : Erubis begin klass = base_module.const_get(classname) rescue NameError klass = nil end unless klass if lang msg = "-l #{lang}: invalid language name (class #{base_module.name}::#{classname} not found)." else msg = "-c #{classname}: invalid class name." end raise CommandOptionError.new(msg) end return klass end def get_enhancers(enhancer_names) return [] unless enhancer_names enhancers = [] shortname = nil begin enhancer_names.split(/,/).each do |name| shortname = name enhancers << Erubis.const_get("#{shortname}Enhancer") end rescue NameError raise CommandOptionError.new("#{shortname}: no such Enhancer (try '-h' to show all enhancers).") end return enhancers end def load_datafiles(filenames, opts) context = Erubis::Context.new return context unless filenames filenames.split(/,/).each do |filename| filename.strip! test(?f, filename) or raise CommandOptionError.new("#{filename}: file not found.") if filename =~ /\.ya?ml$/ if opts.unexpand ydoc = YAML.load_file(filename) else ydoc = YAML.load(untabify(File.read(filename))) end ydoc.is_a?(Hash) or raise CommandOptionError.new("#{filename}: root object is not a mapping.") intern_hash_keys(ydoc) if opts.intern context.update(ydoc) elsif filename =~ /\.rb$/ str = File.read(filename) context2 = Erubis::Context.new _instance_eval(context2, str) context.update(context2) else CommandOptionError.new("#{filename}: '*.yaml', '*.yml', or '*.rb' required.") end end return context end def _instance_eval(_context, _str) _context.instance_eval(_str) end def parse_context_data(context_str, opts) if context_str[0] == ?{ require 'yaml' ydoc = YAML.load(context_str) unless ydoc.is_a?(Hash) raise CommandOptionError.new("-c: root object is not a mapping.") end intern_hash_keys(ydoc) if opts.intern return ydoc else context = Erubis::Context.new context.instance_eval(context_str, '-c') return context end end def intern_hash_keys(obj, done={}) return if done.key?(obj.__id__) case obj when Hash done[obj.__id__] = obj obj.keys.each do |key| obj[key.intern] = obj.delete(key) if key.is_a?(String) end obj.values.each do |val| intern_hash_keys(val, done) if val.is_a?(Hash) || val.is_a?(Array) end when Array done[obj.__id__] = obj obj.each do |val| intern_hash_keys(val, done) if val.is_a?(Hash) || val.is_a?(Array) end end end def check_syntax(filename, src) require 'open3' #command = (ENV['_'] || 'ruby') + ' -wc' # ENV['_'] stores command name bin = ENV['_'] && File.basename(ENV['_']) =~ /^ruby/ ? ENV['_'] : 'ruby' command = bin + ' -wc' stdin, stdout, stderr = Open3.popen3(command) stdin.write(src) stdin.close result = stdout.read() stdout.close() errmsg = stderr.read() stderr.close() return nil unless errmsg && !errmsg.empty? errmsg =~ /\A-:(\d+): / linenum, message = $1, $' return "#{filename}:#{linenum}: #{message}" end if defined?(RUBY_ENGINE) && RUBY_ENGINE == "rbx" def check_syntax(filename, src) require 'compiler' verbose = $VERBOSE msg = nil begin $VERBOSE = true Rubinius::Compiler.compile_string(src, filename) rescue SyntaxError => ex ex_linenum = ex.line linenum = 0 srcline = src.each_line do |line| linenum += 1 break line if linenum == ex_linenum end msg = "#{ex.message}\n" msg << srcline msg << "\n" unless srcline =~ /\n\z/ msg << (" " * (ex.column-1)) << "^\n" ensure $VERBOSE = verbose end return msg end end end end #--end of require 'erubis/main' Erubis::Main.main(ARGV) ruby-erubis-2.7.0/contrib/erubis-run.rb000066400000000000000000000064561170760342400200670ustar00rootroot00000000000000=begin = apache/erubis-run.rb Copyright (C) 2007 Andrew R Jackson Built from original by Shugo Maeda: Copyright (C) 2001 Shugo Maeda All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WAreqANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WAreqANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTEreqUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. == Overview Apache::ErubisRun handles eRuby files with erubis == Example of httpd.conf RubyRequire apache/erubis-run SetHandler ruby-object RubyHandler Apache::ErubisRun.instance =end require "singleton" require "tempfile" require "eruby" # Still needed to bring in a couple useful helper methods require "erubis" module Erubis @@cgi = nil def self.cgi return @@cgi end def self.cgi=(cgi) @@cgi = cgi end end module Apache class ErubisRun include Singleton def handler(req) status = check_request(req) return status if(status != OK) filename = req.filename.dup filename.untaint erubis = compile(filename) prerun(req) begin run(erubis, filename) ensure postrun(req) end return OK end private def initialize @compiler = nil end def check_request(req) if(req.method_number == M_OPTIONS) req.allowed |= (1 << M_GET) req.allowed |= (1 << M_POST) return DECLINED end if(req.finfo.mode == 0) return NOT_FOUND end return OK end def compile(filename) @compiler = Erubis::Eruby.load_file(filename) # use caching version as much as possible return @compiler end def prerun(req) Erubis.cgi = nil req.setup_cgi_env Apache.chdir_file(req.filename) end def run(erubis, filename) binding = eval_string_wrap("binding") puts erubis.result(binding) # eval the code in the context of the same binding ERuby uses end def postrun(req) if(cgi = Erubis.cgi) # TODO: pull the content type header from the cgi object, if set there? elsif(req.sync_output or req.sync_header) # Do nothing: header has already been sent else unless(req.content_type) req.content_type = format("text/html;") end req.send_http_header end end end end ruby-erubis-2.7.0/contrib/inline-require000077500000000000000000000130231170760342400203110ustar00rootroot00000000000000#!/usr/bin/env ruby ### ### inline-require - expand 'require "foo"' into inline code ### ### usage: inline-require [-h] [-I path[,path2,..]] script ### ### copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ### 2.7.0 ### $Rev: 10 $ ### class InlineRequire def initialize(opts={}) @opts = opts.dup end attr_accessor :opts def expand(filename) sbuf = '' inlined = [] level = 0 expand_require(filename, sbuf, inlined, level) return sbuf end private def expand_require(filename, sbuf, inlined, level) raise "*** assertion error" if inlined.include?(filename) remove_comment = @opts[:remove_comment] expand_indented = @opts[:expand_indented] keep_filename = @opts[:keep_filename] loaded_features = @opts[:loaded_features] inlined << filename prog = File.read(filename) n = 0 flag_if_file = false prog.each_line do |line| n += 1 ## comment out from 'if __FILE__ == $0' to 'end' if level > 0 if flag_if_file sbuf << "#" << line flag_if_file = false if line =~ /^end$/ next end if line =~ /^if\s+__FILE__\s*==\s*\$0(\s+then)?$/ || line =~ /^if\s+\$0\s*==\s*__FILE__(\s+then)?$/ flag_if_file = true sbuf << "#" << line next end end ## find 'require "foo"' and expand it to inline code flag_inline = false pattern = expand_indented ? /^[ \t]*require ['"](.*)["']\s*$/ \ : /^require ['"](.*)["']\s*$/ if line =~ pattern libname = $1 libpath = find_library(libname) $stderr.puts "*** debug: libpath=#{libpath.inspect}" if $debug_mode unless libpath #raise "file '#{filename}'(line #{n}): library '#{libname}' not found." warn "file '#{filename}'(line #{n}): library '#{libname}' not found." else flag_inline = true if libpath =~ /\.rb$/ && local_library?(libpath) end end if !flag_inline sbuf << line unless remove_comment && line =~ /^[ \t]*\#/ elsif inlined.include?(libpath) sbuf << "#--already included #{line}" unless remove_comment else if keep_filename @n ||= 0; @n += 1; n = @n end sbuf << "#--begin of #{line}" unless remove_comment sbuf << "$LOADED_FEATURES << '#{libname}.rb'\n" if loaded_features sbuf << "eval <<'END_OF_SCRIPT__#{n}', TOPLEVEL_BINDING, '#{libpath}', 1\n" if keep_filename expand_require(libpath, sbuf, inlined, level+1) sbuf << "END_OF_SCRIPT__#{n}\n" if keep_filename sbuf << "#--end of #{line}" unless remove_comment end end #sbuf << "\n" if sbuf[-1] != ?\n end def local_library?(libpath) return libpath !~ /^\// end def find_library(libname) if libname =~ /^\.rb$/ libname_rb = libname libname_so = nil elsif libname =~ /^\.so$/ libname_rb = nil libname_so = libname else libname_rb = libname + ".rb" libname_so = libname + ".so" end $LOAD_PATH.each do |path| if libname_rb libpath = path + "/" + libname_rb return libpath if test(?f, libpath) end if libname_so libpath = path + "/" + libname_so return libpath if test(?f, libpath) end end return nil end end if __FILE__ == $0 begin require "optparse" op = OptionParser.new options = {} op.on("-h", "--help") {|v| options[:help] = v } op.on("-I libpath") {|v| options[:libpath] = v } op.on("-i") {|v| options[:expand_indented] = v } op.on("-c") {|v| options[:remove_comment] = v } op.on("-k") {|v| options[:keep_filename] = v } op.on("-l") {|v| options[:loaded_features] = v } op.on("-D") {|v| options[:debug] = v } op.parse!() $debug_mode = options[:debug] if options[:help] command = File.basename($0) puts "Usage: #{command} [-h] [-I path[,path2,..]] script" puts " -h : help" puts " -i : expand indented require(), too" puts " -c : remove comment lines start with '#'" puts " -k : keep filename (for debugging)" puts " -l : append libs to $LOADED_FEATURES" puts " -I path[,path2,...] : ruby library path" exit(0) end if options[:libpath] rubylib_paths = options[:libpath].split(/,/) else rubylib_paths = [] end $stderr.puts "*** debug: rubylib_paths=#{rubylib_paths.inspect}" if $debug_mode $LOAD_PATH.concat(rubylib_paths) filenames = ARGV opts = { :expand_indented => options[:expand_indented], :remove_comment => options[:remove_comment], :keep_filename => options[:keep_filename], :loaded_features => options[:loaded_features] } inline_require = InlineRequire.new(opts) filenames.each do |filename| print inline_require.expand(filename) end rescue => ex if $debug_mode raise ex else $stderr.puts ex.message end end end ruby-erubis-2.7.0/doc-api/000077500000000000000000000000001170760342400153105ustar00rootroot00000000000000ruby-erubis-2.7.0/doc-api/classes/000077500000000000000000000000001170760342400167455ustar00rootroot00000000000000ruby-erubis-2.7.0/doc-api/classes/ActionView.html000066400000000000000000000041661170760342400217120ustar00rootroot00000000000000 Module: ActionView
    #symbolnamepricechangeratio
    <%= n %> <%= item['symbol'] %> <%= item['name'] %> <%= item['price'] %> <%= item['change'] %> <%= item['ratio'] %><%= item['change'] %> <%= item['ratio'] %>
    <%= n %> <%= item['symbol'] %> <%= item['name'] %> <%= item['price'] %> <%= item['change'] %> <%= item['ratio'] %><%= item['change'] %> <%= item['ratio'] %>
    <%= n %> <%= item['symbol'] %> <%= item['name'] %> <%= item['price'] %> <%= item['change'] %> <%= item['ratio'] %><%= item['change'] %> <%= item['ratio'] %>
    Module ActionView
    In: erubis/helpers/rails_helper.rb
    ruby-erubis-2.7.0/doc-api/classes/ActionView/000077500000000000000000000000001170760342400210155ustar00rootroot00000000000000ruby-erubis-2.7.0/doc-api/classes/ActionView/TemplateHandlers/000077500000000000000000000000001170760342400242515ustar00rootroot00000000000000ruby-erubis-2.7.0/doc-api/classes/ActionView/TemplateHandlers/ErubisHandler.html000066400000000000000000000163411170760342400276730ustar00rootroot00000000000000 Class: ActionView::TemplateHandlers::ErubisHandler
    Class ActionView::TemplateHandlers::ErubisHandler
    In: erubis/helpers/rails_helper.rb
    Parent: TemplateHandler

    Methods

    compile   compile   compile  

    Public Instance methods

    [Source]

    # File erubis/helpers/rails_helper.rb, line 153
              def compile(template)
                #src = ::ERB.new("<% __in_erb_template=true %>#{template.source}", nil, erb_trim_mode, '@output_buffer').src
                return _convert_template("<% __in_erb_template=true %>#{template.source}")
              end
    

    [Source]

    # File erubis/helpers/rails_helper.rb, line 179
              def compile(template)
                return _convert_template(template.source)   # template.is_a?(ActionView::Template)
              end
    

    [Source]

    # File erubis/helpers/rails_helper.rb, line 209
              def compile(template)
                return _convert_template(template)     # template.is_a?(String)
              end
    
    ruby-erubis-2.7.0/doc-api/classes/ERB.html000066400000000000000000000037151170760342400202510ustar00rootroot00000000000000 Module: ERB
    Module ERB
    In:
    ruby-erubis-2.7.0/doc-api/classes/Erubis.html000066400000000000000000000346101170760342400210700ustar00rootroot00000000000000 Module: Erubis

    an implementation of eRuby

    ex.

      input = <<'END'
       <ul>
        <% for item in @list %>
         <li><%= item %>
             <%== item %></li>
        <% end %>
       </ul>
      END
      list = ['<aaa>', 'b&b', '"ccc"']
      eruby = Erubis::Eruby.new(input)
      puts "--- code ---"
      puts eruby.src
      puts "--- result ---"
      context = Erubis::Context.new()   # or new(:list=>list)
      context[:list] = list
      puts eruby.evaluate(context)
    

    result:

      --- source ---
      _buf = ''; _buf << '<ul>
      ';  for item in @list
       _buf << '  <li>'; _buf << ( item ).to_s; _buf << '
      '; _buf << '      '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</li>
      ';  end
       _buf << '</ul>
      ';
      _buf.to_s
      --- result ---
       <ul>
         <li><aaa>
             &lt;aaa&gt;</li>
         <li>b&b
             b&amp;b</li>
         <li>"ccc"
             &quot;ccc&quot;</li>
       </ul>
    

    Classes and Modules

    Module Erubis::ArrayBufferEnhancer
    Module Erubis::ArrayEnhancer
    Module Erubis::Basic
    Module Erubis::BiPatternEnhancer
    Module Erubis::CGenerator
    Module Erubis::Converter
    Module Erubis::CppGenerator
    Module Erubis::DeleteIndentEnhancer
    Module Erubis::ErboutEnhancer
    Module Erubis::EscapeEnhancer
    Module Erubis::Evaluator
    Module Erubis::Generator
    Module Erubis::HeaderFooterEnhancer
    Module Erubis::Helpers
    Module Erubis::InterpolationEnhancer
    Module Erubis::JavaGenerator
    Module Erubis::JavascriptGenerator
    Module Erubis::NoCodeEnhancer
    Module Erubis::NoTextEnhancer
    Module Erubis::OptimizedGenerator
    Module Erubis::PI
    Module Erubis::PercentLineEnhancer
    Module Erubis::PerlGenerator
    Module Erubis::PhpGenerator
    Module Erubis::PrefixedLineEnhancer
    Module Erubis::PreprocessingHelper
    Module Erubis::PrintEnabledEnhancer
    Module Erubis::PrintOutEnhancer
    Module Erubis::RubyEvaluator
    Module Erubis::RubyGenerator
    Module Erubis::SchemeGenerator
    Module Erubis::SimplifyEnhancer
    Module Erubis::StdoutEnhancer
    Module Erubis::StringBufferEnhancer
    Module Erubis::XmlHelper
    Class Erubis::ArrayBufferEruby
    Class Erubis::ArrayEruby
    Class Erubis::BiPatternEruby
    Class Erubis::CommandOptionError
    Class Erubis::Context
    Class Erubis::DeleteIndentEruby
    Class Erubis::Ec
    Class Erubis::Ecpp
    Class Erubis::Ejava
    Class Erubis::Ejavascript
    Class Erubis::Engine
    Class Erubis::Eperl
    Class Erubis::Ephp
    Class Erubis::ErboutEruby
    Class Erubis::ErubisError
    Class Erubis::Eruby
    Class Erubis::EscapedEc
    Class Erubis::EscapedEcpp
    Class Erubis::EscapedEjava
    Class Erubis::EscapedEjavascript
    Class Erubis::EscapedEperl
    Class Erubis::EscapedEphp
    Class Erubis::EscapedEruby
    Class Erubis::EscapedEscheme
    Class Erubis::Escheme
    Class Erubis::FastEruby
    Class Erubis::HeaderFooterEruby
    Class Erubis::InterpolationEruby
    Class Erubis::Main
    Class Erubis::NoCodeEruby
    Class Erubis::NoTextEruby
    Class Erubis::NotSupportedError
    Class Erubis::OptimizedEruby
    Class Erubis::OptimizedXmlEruby
    Class Erubis::PercentLineEruby
    Class Erubis::PrefixedLineEruby
    Class Erubis::PreprocessingEruby
    Class Erubis::PrintEnabledEruby
    Class Erubis::PrintOutEruby
    Class Erubis::PrintOutSimplifiedEruby
    Class Erubis::SimplifiedEruby
    Class Erubis::StdoutEruby
    Class Erubis::StdoutSimplifiedEruby
    Class Erubis::StringBufferEruby
    Class Erubis::StringIOEruby
    Class Erubis::TinyEruby
    Class Erubis::XmlEruby

    Constants

    EMPTY_BINDING = binding()
    Ejs = Ejavascript
    EscapedEjs = EscapedEjavascript
    VERSION = ('$Release: 2.7.0 $' =~ /([.\d]+)/) && $1
    ruby-erubis-2.7.0/doc-api/classes/Erubis/000077500000000000000000000000001170760342400201765ustar00rootroot00000000000000ruby-erubis-2.7.0/doc-api/classes/Erubis/ArrayBufferEnhancer.html000066400000000000000000000117071170760342400247460ustar00rootroot00000000000000 Module: Erubis::ArrayBufferEnhancer
    Module Erubis::ArrayBufferEnhancer
    In: erubis/enhancer.rb

    use an Array object as buffer (included in Eruby by default)

    this is only for Eruby.

    Methods

    Public Instance methods

    [Source]

    # File erubis/enhancer.rb, line 191
        def add_postamble(src)
          src << "\n" unless src[-1] == ?\n
          src << "_buf.join\n"
        end
    

    [Source]

    # File erubis/enhancer.rb, line 187
        def add_preamble(src)
          src << "_buf = [];"
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/ArrayBufferEruby.html000066400000000000000000000051111170760342400243010ustar00rootroot00000000000000 Class: Erubis::ArrayBufferEruby
    Class Erubis::ArrayBufferEruby
    In: erubis/engine/enhanced.rb
    Parent: Eruby

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/ArrayEnhancer.html000066400000000000000000000116011170760342400236050ustar00rootroot00000000000000 Module: Erubis::ArrayEnhancer
    Module Erubis::ArrayEnhancer
    In: erubis/enhancer.rb

    return array instead of string

    this is only for Eruby.

    Methods

    Public Instance methods

    [Source]

    # File erubis/enhancer.rb, line 168
        def add_postamble(src)
          src << "\n" unless src[-1] == ?\n
          src << "#{@bufvar}\n"
        end
    

    [Source]

    # File erubis/enhancer.rb, line 164
        def add_preamble(src)
          src << "#{@bufvar} = [];"
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/ArrayEruby.html000066400000000000000000000050611170760342400231530ustar00rootroot00000000000000 Class: Erubis::ArrayEruby
    Class Erubis::ArrayEruby
    In: erubis/engine/enhanced.rb
    Parent: Eruby

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/Basic.html000066400000000000000000000045651170760342400221170ustar00rootroot00000000000000 Module: Erubis::Basic
    Module Erubis::Basic
    In: erubis/converter.rb

    Classes and Modules

    Module Erubis::Basic::Converter
    Class Erubis::Basic::Engine
    ruby-erubis-2.7.0/doc-api/classes/Erubis/Basic/000077500000000000000000000000001170760342400212175ustar00rootroot00000000000000ruby-erubis-2.7.0/doc-api/classes/Erubis/Basic/Converter.html000066400000000000000000000467401170760342400240670ustar00rootroot00000000000000 Module: Erubis::Basic::Converter
    Module Erubis::Basic::Converter
    In: erubis/converter.rb

    basic converter which supports ’<% … %>’ notation.

    Included Modules

    Constants

    DEFAULT_REGEXP = pattern_regexp('<% %>')   DEFAULT_REGEXP = /(.*?)(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m DEFAULT_REGEXP = /(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m DEFAULT_REGEXP = /<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m

    Attributes

    pattern  [RW] 
    trim  [RW] 

    Public Instance methods

    add expression code to src

    [Source]

    # File erubis/converter.rb, line 176
        def add_expr(src, code, indicator)
          case indicator
          when '='
            @escape ? add_expr_escaped(src, code) : add_expr_literal(src, code)
          when '=='
            @escape ? add_expr_literal(src, code) : add_expr_escaped(src, code)
          when '==='
            add_expr_debug(src, code)
          end
        end
    

    [Source]

    # File erubis/converter.rb, line 127
        def convert_input(src, input)
          pat = @pattern
          regexp = pat.nil? || pat == '<% %>' ? DEFAULT_REGEXP : pattern_regexp(pat)
          pos = 0
          is_bol = true     # is beginning of line
          input.scan(regexp) do |indicator, code, tailch, rspace|
            match = Regexp.last_match()
            len  = match.begin(0) - pos
            text = input[pos, len]
            pos  = match.end(0)
            ch   = indicator ? indicator[0] : nil
            lspace = ch == ?= ? nil : detect_spaces_at_bol(text, is_bol)
            is_bol = rspace ? true : false
            add_text(src, text) if text && !text.empty?
            ## * when '<%= %>', do nothing
            ## * when '<% %>' or '<%# %>', delete spaces iff only spaces are around '<% %>'
            if ch == ?=              # <%= %>
              rspace = nil if tailch && !tailch.empty?
              add_text(src, lspace) if lspace
              add_expr(src, code, indicator)
              add_text(src, rspace) if rspace
            elsif ch == ?\#          # <%# %>
              n = code.count("\n") + (rspace ? 1 : 0)
              if @trim && lspace && rspace
                add_stmt(src, "\n" * n)
              else
                add_text(src, lspace) if lspace
                add_stmt(src, "\n" * n)
                add_text(src, rspace) if rspace
              end
            elsif ch == ?%           # <%% %>
              s = "#{lspace}#{@prefix||='<%'}#{code}#{tailch}#{@postfix||='%>'}#{rspace}"
              add_text(src, s)
            else                     # <% %>
              if @trim && lspace && rspace
                add_stmt(src, "#{lspace}#{code}#{rspace}")
              else
                add_text(src, lspace) if lspace
                add_stmt(src, code)
                add_text(src, rspace) if rspace
              end
            end
          end
          #rest = $' || input                        # ruby1.8
          rest = pos == 0 ? input : input[pos..-1]   # ruby1.9
          add_text(src, rest)
        end
    

    [Source]

    # File erubis/converter.rb, line 103
        def init_converter(properties={})
          super(properties)
          @pattern = properties[:pattern]
          @trim    = properties[:trim] != false
        end
    

    Protected Instance methods

    return regexp of pattern to parse eRuby script

    [Source]

    # File erubis/converter.rb, line 112
        def pattern_regexp(pattern)
          @prefix, @postfix = pattern.split()   # '<% %>' => '<%', '%>'
          #return /(.*?)(^[ \t]*)?#{@prefix}(=+|\#)?(.*?)-?#{@postfix}([ \t]*\r?\n)?/m
          #return /(^[ \t]*)?#{@prefix}(=+|\#)?(.*?)-?#{@postfix}([ \t]*\r?\n)?/m
          return /#{@prefix}(=+|-|\#|%)?(.*?)([-=])?#{@postfix}([ \t]*\r?\n)?/m
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/Basic/Engine.html000066400000000000000000000057001170760342400233140ustar00rootroot00000000000000 Class: Erubis::Basic::Engine
    Class Erubis::Basic::Engine
    In: erubis/engine.rb
    Parent: Engine

    (abstract) base engine class for Eruby, Eperl, Ejava, and so on. subclass must include generator.

    ruby-erubis-2.7.0/doc-api/classes/Erubis/BiPatternEnhancer.html000066400000000000000000000163621170760342400244300ustar00rootroot00000000000000 Module: Erubis::BiPatternEnhancer
    Module Erubis::BiPatternEnhancer
    In: erubis/enhancer.rb

    enable to use other embedded expression pattern (default is ’\[= =\]’).

    notice! this is an experimental. spec may change in the future.

    ex.

      input = <<END
      <% for item in list %>
        <%= item %> : <%== item %>
        [= item =] : [== item =]
      <% end %>
      END
    
      class BiPatternEruby
        include BiPatternEnhancer
      end
      eruby = BiPatternEruby.new(input, :bipattern=>'\[= =\]')
      list = ['<a>', 'b&b', '"c"']
      print eruby.result(binding())
    
      ## output
        <a> : &lt;a&gt;
        <a> : &lt;a&gt;
        b&b : b&amp;b
        b&b : b&amp;b
        "c" : &quot;c&quot;
        "c" : &quot;c&quot;
    

    this is language independent.

    Methods

    add_text   new  

    Public Class methods

    [Source]

    # File erubis/enhancer.rb, line 408
        def initialize(input, properties={})
          self.bipattern = properties[:bipattern]    # or '\$\{ \}'
          super
        end
    

    Public Instance methods

    [Source]

    # File erubis/enhancer.rb, line 420
        def add_text(src, text)
          return unless text
          m = nil
          text.scan(@bipattern_regexp) do |txt, indicator, code|
            m = Regexp.last_match
            super(src, txt)
            add_expr(src, code, '=' + indicator)
          end
          #rest = $' || text                    # ruby1.8
          rest = m ? text[m.end(0)..-1] : text  # ruby1.9
          super(src, rest)
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/BiPatternEruby.html000066400000000000000000000051011170760342400237600ustar00rootroot00000000000000 Class: Erubis::BiPatternEruby
    Class Erubis::BiPatternEruby
    In: erubis/engine/enhanced.rb
    Parent: Eruby

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/CGenerator.html000066400000000000000000000473241170760342400231270ustar00rootroot00000000000000 Module: Erubis::CGenerator
    Module Erubis::CGenerator
    In: erubis/engine/ec.rb

    Included Modules

    Public Instance methods

    [Source]

    # File erubis/engine/ec.rb, line 72
        def add_expr_debug(src, code)
          code.strip!
          s = nil
          if code =~ /\A\".*?\"\s*,\s*(.*)/
            s = $1.gsub(/[%"]/, '\\\1') + '='
          end
          src << @indent if src.empty? || src[-1] == ?\n
          src << " fprintf(stderr, \"*** debug: #{s}\" #{code});"
        end
    

    [Source]

    # File erubis/engine/ec.rb, line 67
        def add_expr_escaped(src, code)
          src << @indent if src.empty? || src[-1] == ?\n
          src << ' ' << escaped_expr(code) << ';'
        end
    

    [Source]

    # File erubis/engine/ec.rb, line 62
        def add_expr_literal(src, code)
          src << @indent if src.empty? || src[-1] == ?\n
          src << " fprintf(#{@out}, " << code.strip << ');'
        end
    

    [Source]

    # File erubis/engine/ec.rb, line 82
        def add_postamble(src)
          # empty
        end
    

    [Source]

    # File erubis/engine/ec.rb, line 30
        def add_preamble(src)
          src << "#line 1 \"#{self.filename}\"\n" if self.filename
        end
    

    [Source]

    # File erubis/engine/ec.rb, line 58
        def add_stmt(src, code)
          src << code
        end
    

    [Source]

    # File erubis/engine/ec.rb, line 44
        def add_text(src, text)
          return if text.empty?
          src << (src.empty? || src[-1] == ?\n ? @indent : ' ')
          src << "fputs("
          i = 0
          text.each_line do |line|
            src << "\n" << @indent << '      ' if i > 0
            i += 1
            src << '"' << escape_text(line) << '"'
          end
          src << ", #{@out});"   #<< (text[-1] == ?\n ? "\n" : "")
          src << "\n" if text[-1] == ?\n
        end
    

    [Source]

    # File erubis/engine/ec.rb, line 34
        def escape_text(text)
          @@table_ ||= { "\r"=>"\\r", "\n"=>"\\n", "\t"=>"\\t", '"'=>'\\"', "\\"=>"\\\\" }
          text.gsub!(/[\r\n\t"\\]/) { |m| @@table_[m] }
          return text
        end
    

    [Source]

    # File erubis/engine/ec.rb, line 40
        def escaped_expr(code)
          return "#{@escapefunc}(#{code.strip}, #{@out})"
        end
    

    [Source]

    # File erubis/engine/ec.rb, line 23
        def init_generator(properties={})
          super
          @escapefunc ||= "escape"
          @indent = properties[:indent] || ''
          @out = properties[:out] || 'stdout'
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/CommandOptionError.html000066400000000000000000000045321170760342400246510ustar00rootroot00000000000000 Class: Erubis::CommandOptionError
    Class Erubis::CommandOptionError
    In: erubis/main.rb
    Parent: ErubisError
    ruby-erubis-2.7.0/doc-api/classes/Erubis/Context.html000066400000000000000000000331311170760342400225110ustar00rootroot00000000000000 Class: Erubis::Context
    Class Erubis::Context
    In: erubis/context.rb
    Parent: Object

    context object for Engine#evaluate

    ex.

      template = <<'END'
      Hello <%= @user %>!
      <% for item in @list %>
       - <%= item %>
      <% end %>
      END
    
      context = Erubis::Context.new(:user=>'World', :list=>['a','b','c'])
      # or
      # context = Erubis::Context.new
      # context[:user] = 'World'
      # context[:list] = ['a', 'b', 'c']
    
      eruby = Erubis::Eruby.new(template)
      print eruby.evaluate(context)
    

    Methods

    []   []=   each   keys   new   to_hash   update  

    Included Modules

    Enumerable

    Public Class methods

    [Source]

    # File erubis/context.rb, line 33
        def initialize(hash=nil)
          hash.each do |name, value|
            self[name] = value
          end if hash
        end
    

    Public Instance methods

    [Source]

    # File erubis/context.rb, line 39
        def [](key)
          return instance_variable_get("@#{key}")
        end
    

    [Source]

    # File erubis/context.rb, line 43
        def []=(key, value)
          return instance_variable_set("@#{key}", value)
        end
    

    [Source]

    # File erubis/context.rb, line 51
        def each
          instance_variables.each do |name|
            key = name[1..-1]
            value = instance_variable_get(name)
            yield(key, value)
          end
        end
    

    [Source]

    # File erubis/context.rb, line 47
        def keys
          return instance_variables.collect { |name| name[1..-1] }
        end
    

    [Source]

    # File erubis/context.rb, line 59
        def to_hash
          hash = {}
          self.keys.each { |key| hash[key] = self[key] }
          return hash
        end
    

    [Source]

    # File erubis/context.rb, line 65
        def update(context_or_hash)
          arg = context_or_hash
          if arg.is_a?(Hash)
            arg.each do |key, val|
              self[key] = val
            end
          else
            arg.instance_variables.each do |varname|
              key = varname[1..-1]
              val = arg.instance_variable_get(varname)
              self[key] = val
            end
          end
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/Converter.html000066400000000000000000000303331170760342400230350ustar00rootroot00000000000000 Module: Erubis::Converter
    Module Erubis::Converter
    In: erubis/converter.rb

    Attributes

    escape  [RW] 
    postamble  [RW] 
    preamble  [RW] 

    Public Instance methods

    convert input string into target language

    [Source]

    # File erubis/converter.rb, line 33
        def convert(input)
          codebuf = ""    # or []
          @preamble.nil? ? add_preamble(codebuf) : (@preamble && (codebuf << @preamble))
          convert_input(codebuf, input)
          @postamble.nil? ? add_postamble(codebuf) : (@postamble && (codebuf << @postamble))
          @_proc = nil    # clear cached proc object
          return codebuf  # or codebuf.join()
        end
    

    [Source]

    # File erubis/converter.rb, line 26
        def init_converter(properties={})
          @preamble  = properties[:preamble]
          @postamble = properties[:postamble]
          @escape    = properties[:escape]
        end
    

    Protected Instance methods

    (abstract) convert input to code

    [Source]

    # File erubis/converter.rb, line 77
        def convert_input(codebuf, input)
          not_implemented
        end
    

    detect spaces at beginning of line

    [Source]

    # File erubis/converter.rb, line 47
        def detect_spaces_at_bol(text, is_bol)
          lspace = nil
          if text.empty?
            lspace = "" if is_bol
          elsif text[-1] == ?\n
            lspace = ""
          else
            rindex = text.rindex(?\n)
            if rindex
              s = text[rindex+1..-1]
              if s =~ /\A[ \t]*\z/
                lspace = s
                #text = text[0..rindex]
                text[rindex+1..-1] = ''
              end
            else
              if is_bol && text =~ /\A[ \t]*\z/
                #lspace = text
                #text = nil
                lspace = text.dup
                text[0..-1] = ''
              end
            end
          end
          return lspace
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/CppGenerator.html000066400000000000000000000462761170760342400234740ustar00rootroot00000000000000 Module: Erubis::CppGenerator
    Module Erubis::CppGenerator
    In: erubis/engine/ecpp.rb

    Included Modules

    Public Instance methods

    [Source]

    # File erubis/engine/ecpp.rb, line 72
        def add_expr_debug(src, code)
          code.strip!
          src << @indent if src.empty? || src[-1] == ?\n
          src << " std::cerr << \"*** debug: #{code.gsub(/(")/, '\\\&')}=\" << (#{code});"
        end
    

    [Source]

    # File erubis/engine/ecpp.rb, line 67
        def add_expr_escaped(src, code)
          src << @indent if src.empty? || src[-1] == ?\n
          src << ' ' << escaped_expr(code) << ';'
        end
    

    [Source]

    # File erubis/engine/ecpp.rb, line 62
        def add_expr_literal(src, code)
          src << @indent if src.empty? || src[-1] == ?\n
          src << " _buf << (" << code.strip << ");"
        end
    

    [Source]

    # File erubis/engine/ecpp.rb, line 78
        def add_postamble(src)
          # empty
        end
    

    [Source]

    # File erubis/engine/ecpp.rb, line 30
        def add_preamble(src)
          src << "#line 1 \"#{self.filename}\"\n" if self.filename
        end
    

    [Source]

    # File erubis/engine/ecpp.rb, line 58
        def add_stmt(src, code)
          src << code
        end
    

    [Source]

    # File erubis/engine/ecpp.rb, line 44
        def add_text(src, text)
          return if text.empty?
          src << (src.empty? || src[-1] == ?\n ? @indent : ' ')
          src << "_buf << "
          i = 0
          text.each_line do |line|
            src << "\n" << @indent << "        " if i > 0
            i += 1
            src << '"' << escape_text(line) << '"'
          end
          src << ";"   #<< (text[-1] == ?\n ? "\n" : "")
          src << "\n" if text[-1] == ?\n
        end
    

    [Source]

    # File erubis/engine/ecpp.rb, line 34
        def escape_text(text)
          @@table_ ||= { "\r"=>"\\r", "\n"=>"\\n", "\t"=>"\\t", '"'=>'\\"', "\\"=>"\\\\" }
          text.gsub!(/[\r\n\t"\\]/) { |m| @@table_[m] }
          return text
        end
    

    [Source]

    # File erubis/engine/ecpp.rb, line 40
        def escaped_expr(code)
          return "#{@escapefunc}(#{code.strip})"
        end
    

    [Source]

    # File erubis/engine/ecpp.rb, line 23
        def init_generator(properties={})
          super
          @escapefunc ||= "escape"
          @indent = properties[:indent] || ''
          @bufvar = properties[:bufvar] || '_buf'
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/DeleteIndentEnhancer.html000066400000000000000000000074201170760342400250770ustar00rootroot00000000000000 Module: Erubis::DeleteIndentEnhancer
    Module Erubis::DeleteIndentEnhancer
    In: erubis/enhancer.rb

    delete indentation of HTML.

    this is language-independent.

    Methods

    Public Instance methods

    [Source]

    # File erubis/enhancer.rb, line 622
        def convert_input(src, input)
          input = input.gsub(/^[ \t]+</, '<')
          super(src, input)
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/DeleteIndentEruby.html000066400000000000000000000051151170760342400244410ustar00rootroot00000000000000 Class: Erubis::DeleteIndentEruby
    Class Erubis::DeleteIndentEruby
    In: erubis/engine/enhanced.rb
    Parent: Eruby

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/Ec.html000066400000000000000000000051411170760342400214140ustar00rootroot00000000000000 Class: Erubis::Ec
    Class Erubis::Ec
    In: erubis/engine/ec.rb
    Parent: Basic::Engine

    engine for C

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/Ecpp.html000066400000000000000000000051551170760342400217610ustar00rootroot00000000000000 Class: Erubis::Ecpp
    Class Erubis::Ecpp
    In: erubis/engine/ecpp.rb
    Parent: Basic::Engine

    engine for C

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/Ejava.html000066400000000000000000000051661170760342400221220ustar00rootroot00000000000000 Class: Erubis::Ejava
    Class Erubis::Ejava
    In: erubis/engine/ejava.rb
    Parent: Basic::Engine

    engine for Java

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/Ejavascript.html000066400000000000000000000052401170760342400233400ustar00rootroot00000000000000 Class: Erubis::Ejavascript
    Class Erubis::Ejavascript
    In: erubis/engine/ejavascript.rb
    Parent: Basic::Engine

    engine for JavaScript

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/Engine.html000066400000000000000000000364361170760342400223050ustar00rootroot00000000000000 Class: Erubis::Engine
    Class Erubis::Engine
    In: erubis/engine.rb
    Parent: Object

    (abstract) abstract engine class. subclass must include evaluator and converter module.

    Methods

    convert!   load_file   new   process   process_proc  

    Public Class methods

    load file, write cache file, and return engine object. this method create code cache file automatically. cachefile name can be specified with properties[:cachename], or filname + ‘cache’ is used as default.

    [Source]

    # File erubis/engine.rb, line 48
        def self.load_file(filename, properties={})
          cachename = properties[:cachename] || (filename + '.cache')
          properties[:filename] = filename
          timestamp = File.mtime(filename)
          if test(?f, cachename) && timestamp == File.mtime(cachename)
            engine = self.new(nil, properties)
            engine.src = File.read(cachename)
          else
            input = File.open(filename, 'rb') {|f| f.read }
            engine = self.new(input, properties)
            tmpname = cachename + rand().to_s[1,8]
            File.open(tmpname, 'wb') {|f| f.write(engine.src) }
            File.rename(tmpname, cachename)
            File.utime(timestamp, timestamp, cachename)
          end
          engine.src.untaint   # ok?
          return engine
        end
    

    include Evaluator include Converter include Generator

    [Source]

    # File erubis/engine.rb, line 25
        def initialize(input=nil, properties={})
          #@input = input
          init_generator(properties)
          init_converter(properties)
          init_evaluator(properties)
          @src    = convert(input) if input
        end
    

    Public Instance methods

    convert input string and set it to @src

    [Source]

    # File erubis/engine.rb, line 37
        def convert!(input)
          @src = convert(input)
        end
    

    helper method to convert and evaluate input text with context object. context may be Binding, Hash, or Object.

    [Source]

    # File erubis/engine.rb, line 72
        def process(input, context=nil, filename=nil)
          code = convert(input)
          filename ||= '(erubis)'
          if context.is_a?(Binding)
            return eval(code, context, filename)
          else
            context = Context.new(context) if context.is_a?(Hash)
            return context.instance_eval(code, filename)
          end
        end
    

    helper method evaluate Proc object with contect object. context may be Binding, Hash, or Object.

    [Source]

    # File erubis/engine.rb, line 88
        def process_proc(proc_obj, context=nil, filename=nil)
          if context.is_a?(Binding)
            filename ||= '(erubis)'
            return eval(proc_obj, context, filename)
          else
            context = Context.new(context) if context.is_a?(Hash)
            return context.instance_eval(&proc_obj)
          end
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/Eperl.html000066400000000000000000000051661170760342400221430ustar00rootroot00000000000000 Class: Erubis::Eperl
    Class Erubis::Eperl
    In: erubis/engine/eperl.rb
    Parent: Basic::Engine

    engine for Perl

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/Ephp.html000066400000000000000000000051571170760342400217700ustar00rootroot00000000000000 Class: Erubis::Ephp
    Class Erubis::Ephp
    In: erubis/engine/ephp.rb
    Parent: Basic::Engine

    engine for PHP

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/ErboutEnhancer.html000066400000000000000000000117031170760342400237720ustar00rootroot00000000000000 Module: Erubis::ErboutEnhancer
    Module Erubis::ErboutEnhancer
    In: erubis/enhancer.rb

    set buffer variable name to ‘_erbout’ as well as ‘_buf‘

    this is only for Eruby.

    Methods

    Public Instance methods

    [Source]

    # File erubis/enhancer.rb, line 260
        def add_postamble(src)
          src << "\n" unless src[-1] == ?\n
          src << "#{@bufvar}.to_s\n"
        end
    

    [Source]

    # File erubis/enhancer.rb, line 256
        def add_preamble(src)
          src << "_erbout = #{@bufvar} = '';"
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/ErboutEruby.html000066400000000000000000000050651170760342400233410ustar00rootroot00000000000000 Class: Erubis::ErboutEruby
    Class Erubis::ErboutEruby
    In: erubis/engine/enhanced.rb
    Parent: Eruby

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/ErubisError.html000066400000000000000000000045271170760342400233370ustar00rootroot00000000000000 Class: Erubis::ErubisError
    Class Erubis::ErubisError
    In: erubis/error.rb
    Parent: StandardError

    base error class

    ruby-erubis-2.7.0/doc-api/classes/Erubis/Eruby.html000066400000000000000000000057101170760342400221550ustar00rootroot00000000000000 Class: Erubis::Eruby

    engine for Ruby

    ruby-erubis-2.7.0/doc-api/classes/Erubis/EscapeEnhancer.html000066400000000000000000000116531170760342400237360ustar00rootroot00000000000000 Module: Erubis::EscapeEnhancer
    Module Erubis::EscapeEnhancer
    In: erubis/enhancer.rb

    switch ’<%= … %>’ to escaped and ’<%== … %>’ to unescaped

    ex.

      class XmlEruby < Eruby
        include EscapeEnhancer
      end
    

    this is language-indenedent.

    Methods

    add_expr  

    Public Instance methods

    [Source]

    # File erubis/enhancer.rb, line 37
        def add_expr(src, code, indicator)
          case indicator
          when '='
            @escape ? add_expr_literal(src, code) : add_expr_escaped(src, code)
          when '=='
            @escape ? add_expr_escaped(src, code) : add_expr_literal(src, code)
          when '==='
            add_expr_debug(src, code)
          end
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/EscapedEc.html000066400000000000000000000050371170760342400227050ustar00rootroot00000000000000 Class: Erubis::EscapedEc
    Class Erubis::EscapedEc
    In: erubis/engine/ec.rb
    Parent: Ec

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/EscapedEcpp.html000066400000000000000000000050531170760342400232430ustar00rootroot00000000000000 Class: Erubis::EscapedEcpp
    Class Erubis::EscapedEcpp
    In: erubis/engine/ecpp.rb
    Parent: Ecpp

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/EscapedEjava.html000066400000000000000000000050611170760342400234010ustar00rootroot00000000000000 Class: Erubis::EscapedEjava
    Class Erubis::EscapedEjava
    In: erubis/engine/ejava.rb
    Parent: Ejava

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/EscapedEjavascript.html000066400000000000000000000051251170760342400246270ustar00rootroot00000000000000 Class: Erubis::EscapedEjavascript
    Class Erubis::EscapedEjavascript
    In: erubis/engine/ejavascript.rb
    Parent: Ejavascript

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/EscapedEperl.html000066400000000000000000000050611170760342400234220ustar00rootroot00000000000000 Class: Erubis::EscapedEperl
    Class Erubis::EscapedEperl
    In: erubis/engine/eperl.rb
    Parent: Eperl

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/EscapedEphp.html000066400000000000000000000050531170760342400232500ustar00rootroot00000000000000 Class: Erubis::EscapedEphp
    Class Erubis::EscapedEphp
    In: erubis/engine/ephp.rb
    Parent: Ephp

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/EscapedEruby.html000066400000000000000000000053031170760342400234400ustar00rootroot00000000000000 Class: Erubis::EscapedEruby
    Class Erubis::EscapedEruby
    In: erubis/engine/eruby.rb
    Parent: Eruby

    swtich ’<%= %>’ to escaped and ’<%== %>’ to not escaped

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/EscapedEscheme.html000066400000000000000000000050751170760342400237310ustar00rootroot00000000000000 Class: Erubis::EscapedEscheme
    Class Erubis::EscapedEscheme
    In: erubis/engine/escheme.rb
    Parent: Escheme

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/Escheme.html000066400000000000000000000052041170760342400224360ustar00rootroot00000000000000 Class: Erubis::Escheme
    Class Erubis::Escheme
    In: erubis/engine/escheme.rb
    Parent: Basic::Engine

    engine for Scheme

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/Evaluator.html000066400000000000000000000146001170760342400230270ustar00rootroot00000000000000 Module: Erubis::Evaluator
    Module Erubis::Evaluator
    In: erubis/evaluator.rb

    evaluate code

    Methods

    Attributes

    filename  [RW] 
    src  [RW] 

    Public Instance methods

    [Source]

    # File erubis/evaluator.rb, line 34
        def evaluate(*args)
          raise NotSupportedError.new("evaluation of code except Ruby is not supported.")
        end
    

    [Source]

    # File erubis/evaluator.rb, line 26
        def init_evaluator(properties)
          @filename = properties[:filename]
        end
    

    [Source]

    # File erubis/evaluator.rb, line 30
        def result(*args)
          raise NotSupportedError.new("evaluation of code except Ruby is not supported.")
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/FastEruby.html000066400000000000000000000055751170760342400230040ustar00rootroot00000000000000 Class: Erubis::FastEruby

    fast engine for Ruby

    ruby-erubis-2.7.0/doc-api/classes/Erubis/Generator.html000066400000000000000000000332041170760342400230140ustar00rootroot00000000000000 Module: Erubis::Generator
    Module Erubis::Generator
    In: erubis/generator.rb

    code generator, called by Converter module

    Attributes

    escapefunc  [RW] 

    Public Instance methods

    (abstract) add expression code to src for debug. this is called by add_expr().

    [Source]

    # File erubis/generator.rb, line 72
        def add_expr_debug(src, code)
          not_implemented
        end
    

    (abstract) add escaped expression code to src. this is called by add_expr().

    [Source]

    # File erubis/generator.rb, line 67
        def add_expr_escaped(src, code)
          not_implemented
        end
    

    (abstract) add expression literal code to src. this is called by add_expr().

    [Source]

    # File erubis/generator.rb, line 62
        def add_expr_literal(src, code)
          not_implemented
        end
    

    (abstract) add @postamble to src

    [Source]

    # File erubis/generator.rb, line 77
        def add_postamble(src)
          not_implemented
        end
    

    (abstract) add @preamble to src

    [Source]

    # File erubis/generator.rb, line 47
        def add_preamble(src)
          not_implemented
        end
    

    (abstract) add statement code to src

    [Source]

    # File erubis/generator.rb, line 57
        def add_stmt(src, code)
          not_implemented
        end
    

    (abstract) add text string to src

    [Source]

    # File erubis/generator.rb, line 52
        def add_text(src, text)
          not_implemented
        end
    

    (abstract) escape text string

    ex.

      def escape_text(text)
        return text.dump
        # or return "'" + text.gsub(/['\\]/, '\\\\\&') + "'"
      end
    

    [Source]

    # File erubis/generator.rb, line 36
        def escape_text(text)
          not_implemented
        end
    

    return escaped expression code (ex. ‘h(…)’ or ‘htmlspecialchars(…)’)

    [Source]

    # File erubis/generator.rb, line 41
        def escaped_expr(code)
          code.strip!
          return "#{@escapefunc}(#{code})"
        end
    

    [Source]

    # File erubis/generator.rb, line 24
        def init_generator(properties={})
          @escapefunc = properties[:escapefunc]
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/HeaderFooterEnhancer.html000066400000000000000000000226531170760342400251070ustar00rootroot00000000000000 Module: Erubis::HeaderFooterEnhancer
    Module Erubis::HeaderFooterEnhancer
    In: erubis/enhancer.rb
    experimental
    allow header and footer in eRuby script

    ex.

      ====================
      ## without header and footer
      $ cat ex1.eruby
      <% def list_items(list) %>
      <%   for item in list %>
      <li><%= item %></li>
      <%   end %>
      <% end %>
    
      $ erubis -s ex1.eruby
      _buf = []; def list_items(list)
      ;   for item in list
      ; _buf << '<li>'; _buf << ( item ).to_s; _buf << '</li>
      ';   end
      ; end
      ;
      _buf.join
    
      ## with header and footer
      $ cat ex2.eruby
      <!--#header:
      def list_items(list)
       #-->
      <%  for item in list %>
      <li><%= item %></li>
      <%  end %>
      <!--#footer:
      end
       #-->
    
      $ erubis -s -c HeaderFooterEruby ex4.eruby
    
      def list_items(list)
       _buf = []; _buf << '
      ';  for item in list
      ; _buf << '<li>'; _buf << ( item ).to_s; _buf << '</li>
      ';  end
      ; _buf << '
      ';
      _buf.join
      end
    
      ====================
    

    this is language-independent.

    Methods

    add_text   convert  

    Constants

    HEADER_FOOTER_PATTERN = /(.*?)(^[ \t]*)?<!--\#(\w+):(.*?)\#-->([ \t]*\r?\n)?/m

    Attributes

    footer  [RW] 
    header  [RW] 

    Public Instance methods

    [Source]

    # File erubis/enhancer.rb, line 585
        def add_text(src, text)
          m = nil
          text.scan(HEADER_FOOTER_PATTERN) do |txt, lspace, word, content, rspace|
            m = Regexp.last_match
            flag_trim = @trim && lspace && rspace
            super(src, txt)
            content = "#{lspace}#{content}#{rspace}" if flag_trim
            super(src, lspace) if !flag_trim && lspace
            instance_variable_set("@#{word}", content)
            super(src, rspace) if !flag_trim && rspace
          end
          #rest = $' || text                    # ruby1.8
          rest = m ? text[m.end(0)..-1] : text  # ruby1.9
          super(src, rest)
        end
    

    [Source]

    # File erubis/enhancer.rb, line 603
        def convert(input)
          source = super
          return @src = "#{@header}#{source}#{@footer}"
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/HeaderFooterEruby.html000066400000000000000000000051151170760342400244440ustar00rootroot00000000000000 Class: Erubis::HeaderFooterEruby
    Class Erubis::HeaderFooterEruby
    In: erubis/engine/enhanced.rb
    Parent: Eruby

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/Helpers.html000066400000000000000000000051261170760342400224720ustar00rootroot00000000000000 Module: Erubis::Helpers
    ruby-erubis-2.7.0/doc-api/classes/Erubis/Helpers/000077500000000000000000000000001170760342400216005ustar00rootroot00000000000000ruby-erubis-2.7.0/doc-api/classes/Erubis/Helpers/RailsFormHelper.html000066400000000000000000001417561170760342400255420ustar00rootroot00000000000000 Module: Erubis::Helpers::RailsFormHelper
    Module Erubis::Helpers::RailsFormHelper
    In: erubis/helpers/rails_form_helper.rb

    Public Instance methods

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 106
      def _pp_check_box_checked?(value, checked_value)
        return ActionView::Helpers::InstanceTag::check_box_checked?(value, checked_value)
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 46
      def _pp_error_tags(value)
        return value ? ['<div class="fieldWithErrors">', '</div>'] : ['', '']
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 117
      def _pp_radio_button_checked?(value, tag_value)
        return ActionView::Helpers::InstanceTag::radio_button_checked?(value, tag_value)
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 50
      def _pp_remove_error_div(s)
        s.sub!(/\A<div class="fieldWithErrors">(.*)<\/div>\z/, '\1')
        return s
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 121
      def _pp_select(object, method, collection, priority_collection, options={}, html_options={})
        return pp_error_on(object, method) do
          s = ""
          ## start tag
          s << "<select id=\"#{object}_#{method}\" name=\"#{object}[#{method}]\""
          for key, val in html_options:
              s << " #{key}=\"#{val}\""
          end
          s << ">\n"
          ## selected table
          key = options.key?(:value) ? :value : (options.key?('value') ? 'value' : nil)
          if    key.nil?                ;  selected = "@#{object}.#{method}"
          elsif (val=options[key]).nil? ;  selected = nil
          elsif val =~ /\A<%=(.*)%>\z/  ;  selected = $1
          else                          ;  selected = val.inspect
          end
          s << "<% _table = {#{selected}=>' selected=\"selected\"'} %>\n" if selected
          ## <option> tags
          if options[:include_blank] || options['include_blank']
            s << "<option value=\"\"></option>\n"
          end
          unless priority_collection.blank?
            _pp_select_options(s, priority_collection, selected, 'delete')
            s << "<option value=\"\">-------------</option>\n"
          end
          _pp_select_options(s, collection, selected, '[]')
          ## end tag
          s << "</select>"
          s
        end
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 153
      def _pp_select_options(s, collection, selected, operator)
        for item in collection
          value, text = item.is_a?(Array) ? item : [item, item]
          if !selected
            t = ''
          elsif operator == 'delete'
            t = "<%= _table.delete(#{value.inspect}) %>"
          else
            t = "<%= _table[#{value.inspect}] %>"
          end
          s << "<option value=\"#{h value}\"#{t}>#{h text}</option>\n"
        end
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 99
      def pp_check_box(object_name, method, options={}, checked_value="1", unchecked_value="0")
        s = check_box(object_name, method, options, checked_value, unchecked_value)
        s.sub!(/\schecked=\"checked\"/, '')
        s.sub!(/type="checkbox"/, "\\&<%= _pp_check_box_checked?(@#{object_name}.#{method}, #{checked_value.inspect}) ? ' checked=\"checked\"' : '' %>")
        return pp_error_on(object_name, method) { _pp_remove_error_div(s) }
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 171
      def pp_collection_select(object, method, collection, value_method, text_method, options={}, html_options={})
        collection2 = collection.collect { |e|
          [e.__send__(value_method), e.__send__(text_method)]
        }
        return _pp_select(object, method, collection2, nil, options, html_options)
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 178
      def pp_country_select(object, method, priority_countries=nil, options={}, html_options={})
        collection = ActionView::Helpers::FormOptionsHelper::COUNTRIES
        return _pp_select(object, method, collection, priority_countries, options, html_options)
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 37
      def pp_error_on(object_name, method)
        s = ''
        s << "<% _stag, _etag = _pp_error_tags(@#{object_name}.errors.on('#{method}')) %>"
        s << "<%= _stag %>"
        s << yield(object_name, method)
        s << "<%= _etag %>"
        return s
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 91
      def pp_file_field(object_name, method, options={})
        return pp_tag_helper(:file_field, object_name, method, options)
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 69
      def pp_form_tag(url_for_options={}, options={}, *parameters_for_url, &block)
        return form_tag(url_for_options, options, *parameters_for_url, &block)
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 87
      def pp_hidden_field(object_name, method, options={})
        return pp_tag_helper(:hidden_field, object_name, method, options)
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 193
      def pp_image_submit_tag(source, options={})
        return image_submit_tag(source, options)
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 83
      def pp_password_field(object_name, method, options={})
        return pp_tag_helper(:password_field, object_name, method, options)
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 110
      def pp_radio_button(object_name, method, tag_value, options={})
        s = radio_button(object_name, method, tag_value, options)
        s.sub!(/\schecked=\"checked\"/, '')
        s.sub!(/type="radio"/, "\\&<%= _pp_radio_button_checked?(@#{object_name}.#{method}, #{tag_value.inspect}) ? ' checked=\"checked\"' : '' %>")
        return pp_error_on(object_name, method) { _pp_remove_error_div(s) }
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 30
      def pp_render_partial(basename)
        basename = "_#{basename}" unless basename[0] == ?_
        filename = pp_template_filename(basename)
        preprocessor = _create_preprocessor(File.read(filename))
        return preprocessor.evaluate(_preprocessing_context_object())
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 167
      def pp_select(object, method, collection, options={}, html_options={})
        return _pp_select(object, method, collection, nil, options, html_options)
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 189
      def pp_submit_tag(value="Save changes", options={})
        return submit_tag(value, options)
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 55
      def pp_tag_helper(helper, object_name, method, options={})
        if object_name.is_a?(ActionView::Helpers::FormHelper)
          object_name = object_name.object_name
        end
        unless options.key?(:value) || options.key?('value')
          options['value'] = _?("h @#{object_name}.#{method}")
        end
        #$stderr.puts "*** debug: pp_tag_helper(): options=#{options.inspect}"
        return pp_error_on(object_name, method) {
          s = __send__(helper, object_name, method, options)
          _pp_remove_error_div(s)
        }
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 23
      def pp_template_filename(basename)
        fname = "#{RAILS_ROOT}/app/views/#{controller.controller_name}/#{basename}.html.erb"
        return fname if test(?f, fname)
        return  "#{RAILS_ROOT}/app/views/#{controller.controller_name}/#{basename}.rhtml"
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 19
      def pp_template_filename(basename)
        return "#{RAILS_ROOT}/app/views/#{controller.controller_name}/#{basename}.rhtml"
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 95
      def pp_text_area(object_name, method, options={})
        return pp_tag_helper(:text_area, object_name, method, options)
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 79
      def pp_text_field(object_name, method, options={})
        return pp_tag_helper(:text_field, object_name, method, options)
      end
    

    [Source]

    # File erubis/helpers/rails_form_helper.rb, line 183
      def pp_time_zone_select(object, method, priority_zones=nil, options={}, html_options={})
        model = options[:model] || options['model'] || TimeZone
        collection = model.all.collect { |e| [e.name, e.to_s] }
        return _pp_select(object, method, collection, priority_zones, options, html_options)
      end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/Helpers/RailsHelper.html000066400000000000000000000271701170760342400247070ustar00rootroot00000000000000 Module: Erubis::Helpers::RailsHelper
    Module Erubis::Helpers::RailsHelper
    In: erubis/helpers/rails_helper.rb

    helper module for Ruby on Rails

    howto:

    1. add the folliwng code in your ‘config/environment.rb‘
        require 'erubis/helpers/rails_helper'
        #Erubis::Helpers::RailsHelper.engine_class = Erubis::Eruby # or Erubis::FastEruby
        #Erubis::Helpers::RailsHelper.init_properties = {}
        #Erubis::Helpers::RailsHelper.show_src = false       # set true for debugging
        #Erubis::Helpers::RailsHelper.preprocessing = true   # set true to enable preprocessing
      
    2. restart web server.

    if Erubis::Helper::Rails.show_src is true, Erubis prints converted Ruby code into log file (‘log/development.log’ or so). if false, it doesn‘t. if nil, Erubis prints converted Ruby code if ENV[‘RAILS_ENV’] == ‘development’.

    Public Class methods

    @@engine_class = ::Erubis::FastEruby

    [Source]

    # File erubis/helpers/rails_helper.rb, line 47
          def self.engine_class
            @@engine_class
          end
    

    [Source]

    # File erubis/helpers/rails_helper.rb, line 50
          def self.engine_class=(klass)
            @@engine_class = klass
          end
    

    [Source]

    # File erubis/helpers/rails_helper.rb, line 56
          def self.init_properties
            @@init_properties
          end
    

    [Source]

    # File erubis/helpers/rails_helper.rb, line 59
          def self.init_properties=(hash)
            @@init_properties = hash
          end
    

    [Source]

    # File erubis/helpers/rails_helper.rb, line 74
          def self.preprocessing
            @@preprocessing
          end
    

    [Source]

    # File erubis/helpers/rails_helper.rb, line 77
          def self.preprocessing=(flag)
            @@preprocessing = flag
          end
    

    [Source]

    # File erubis/helpers/rails_helper.rb, line 65
          def self.show_src
            @@show_src
          end
    

    [Source]

    # File erubis/helpers/rails_helper.rb, line 68
          def self.show_src=(flag)
            @@show_src = flag
          end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/Helpers/RailsHelper/000077500000000000000000000000001170760342400240125ustar00rootroot00000000000000ruby-erubis-2.7.0/doc-api/classes/Erubis/Helpers/RailsHelper/TemplateConverter.html000066400000000000000000000161061170760342400303470ustar00rootroot00000000000000 Module: Erubis::Helpers::RailsHelper::TemplateConverter
    Module Erubis::Helpers::RailsHelper::TemplateConverter
    In: erubis/helpers/rails_helper.rb

    Public Instance methods

    [Source]

    # File erubis/helpers/rails_helper.rb, line 107
            def _create_preprocessor(template)
              return PreprocessingEruby.new(template, :escape=>true)
            end
    

    [Source]

    # File erubis/helpers/rails_helper.rb, line 113
            def _logger_info(message)
              logger.info message
            end
    

    [Source]

    # File erubis/helpers/rails_helper.rb, line 164
          def _logger_info(message)
            #logger.info message   # logger.info seems not available in Rails 2.2
            ActionController::Base.new.logger.info message
          end
    

    [Source]

    # File erubis/helpers/rails_helper.rb, line 110
            def _preprocessing_context_object
              return self
            end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/InterpolationEnhancer.html000066400000000000000000000457541170760342400253760ustar00rootroot00000000000000 Module: Erubis::InterpolationEnhancer
    Module Erubis::InterpolationEnhancer
    In: erubis/enhancer.rb

    convert "<h1><%=title%></h1>" into "_buf << %Q`<h1>#{title}</h1>`"

    this is only for Eruby.

    Public Instance methods

    [Source]

    # File erubis/enhancer.rb, line 707
        def _add_text_to_str(str, text)
          return if !text || text.empty?
          str << text.gsub(/[`\#\\]/, '\\\\\&')
        end
    

    [Source]

    # File erubis/enhancer.rb, line 712
        def add_expr_escaped(str, code)
          str << "\#{#{escaped_expr(code)}}"
        end
    

    [Source]

    # File erubis/enhancer.rb, line 716
        def add_expr_literal(str, code)
          str << "\#{#{code}}"
        end
    

    [Source]

    # File erubis/enhancer.rb, line 696
        def add_text(src, text)
          return if !text || text.empty?
          #src << " _buf << %Q`" << text << "`;"
          if text[-1] == ?\n
            text[-1] = "\\n"
            src << " #{@bufvar} << %Q`#{text}`\n"
          else
            src << " #{@bufvar} << %Q`#{text}`;"
          end
        end
    

    [Source]

    # File erubis/enhancer.rb, line 641
        def convert_input(src, input)
          pat = @pattern
          regexp = pat.nil? || pat == '<% %>' ? Basic::Converter::DEFAULT_REGEXP : pattern_regexp(pat)
          pos = 0
          is_bol = true     # is beginning of line
          str = ''
          input.scan(regexp) do |indicator, code, tailch, rspace|
            match = Regexp.last_match()
            len  = match.begin(0) - pos
            text = input[pos, len]
            pos  = match.end(0)
            ch   = indicator ? indicator[0] : nil
            lspace = ch == ?= ? nil : detect_spaces_at_bol(text, is_bol)
            is_bol = rspace ? true : false
            _add_text_to_str(str, text)
            ## * when '<%= %>', do nothing
            ## * when '<% %>' or '<%# %>', delete spaces iff only spaces are around '<% %>'
            if ch == ?=              # <%= %>
              rspace = nil if tailch && !tailch.empty?
              str << lspace if lspace
              add_expr(str, code, indicator)
              str << rspace if rspace
            elsif ch == ?\#          # <%# %>
              n = code.count("\n") + (rspace ? 1 : 0)
              if @trim && lspace && rspace
                add_text(src, str)
                str = ''
                add_stmt(src, "\n" * n)
              else
                str << lspace if lspace
                add_text(src, str)
                str = ''
                add_stmt(src, "\n" * n)
                str << rspace if rspace
              end
            else                     # <% %>
              if @trim && lspace && rspace
                add_text(src, str)
                str = ''
                add_stmt(src, "#{lspace}#{code}#{rspace}")
              else
                str << lspace if lspace
                add_text(src, str)
                str = ''
                add_stmt(src, code)
                str << rspace if rspace
              end
            end
          end
          #rest = $' || input                       # ruby1.8
          rest = pos == 0 ? input : input[pos..-1]  # ruby1.9
          _add_text_to_str(str, rest)
          add_text(src, str)
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/InterpolationEruby.html000066400000000000000000000051211170760342400247210ustar00rootroot00000000000000 Class: Erubis::InterpolationEruby
    Class Erubis::InterpolationEruby
    In: erubis/engine/enhanced.rb
    Parent: Eruby

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/JavaGenerator.html000066400000000000000000000446671170760342400236350ustar00rootroot00000000000000 Module: Erubis::JavaGenerator
    Module Erubis::JavaGenerator
    In: erubis/engine/ejava.rb

    Included Modules

    Public Instance methods

    [Source]

    # File erubis/engine/ejava.rb, line 68
        def add_expr_debug(src, code)
          code.strip!
          src << @indent if src.empty? || src[-1] == ?\n
          src << " System.err.println(\"*** debug: #{code}=\"+(#{code}));"
        end
    

    [Source]

    # File erubis/engine/ejava.rb, line 64
        def add_expr_escaped(src, code)
          add_expr_literal(src, escaped_expr(code))
        end
    

    [Source]

    # File erubis/engine/ejava.rb, line 58
        def add_expr_literal(src, code)
          src << @indent if src.empty? || src[-1] == ?\n
          code.strip!
          src << " #{@bufvar}.append(#{code});"
        end
    

    [Source]

    # File erubis/engine/ejava.rb, line 74
        def add_postamble(src)
          src << "\n" if src[-1] == ?;
          src << @indent << "return " << @bufvar << ".toString();\n"
          #src << @indent << "System.out.print(" << @bufvar << ".toString());\n"
        end
    

    [Source]

    # File erubis/engine/ejava.rb, line 32
        def add_preamble(src)
          src << "#{@indent}#{@bufclass} #{@bufvar} = new #{@bufclass}();"
        end
    

    [Source]

    # File erubis/engine/ejava.rb, line 54
        def add_stmt(src, code)
          src << code
        end
    

    [Source]

    # File erubis/engine/ejava.rb, line 41
        def add_text(src, text)
          return if text.empty?
          src << (src.empty? || src[-1] == ?\n ? @indent : ' ')
          src << @bufvar << ".append("
          i = 0
          text.each_line do |line|
            src << "\n" << @indent << '          + ' if i > 0
            i += 1
            src << '"' << escape_text(line) << '"'
          end
          src << ");" << (text[-1] == ?\n ? "\n" : "")
        end
    

    [Source]

    # File erubis/engine/ejava.rb, line 36
        def escape_text(text)
          @@table_ ||= { "\r"=>"\\r", "\n"=>"\\n", "\t"=>"\\t", '"'=>'\\"', "\\"=>"\\\\" }
          return text.gsub!(/[\r\n\t"\\]/) { |m| @@table_[m] } || text
        end
    

    [Source]

    # File erubis/engine/ejava.rb, line 24
        def init_generator(properties={})
          super
          @escapefunc ||= 'escape'
          @indent = properties[:indent] || ''
          @bufvar = properties[:bufvar] || '_buf'
          @bufclass = properties[:bufclass] || 'StringBuffer'
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/JavascriptGenerator.html000066400000000000000000000451551170760342400250530ustar00rootroot00000000000000 Module: Erubis::JavascriptGenerator
    Module Erubis::JavascriptGenerator
    In: erubis/engine/ejavascript.rb

    Included Modules

    Public Instance methods

    [Source]

    # File erubis/engine/ejavascript.rb, line 72
        def add_expr_debug(src, code)
          add_indent(src, @indent)
          code.strip!
          src << "alert(\"*** debug: #{code}=\"+(#{code}));"
        end
    

    [Source]

    # File erubis/engine/ejavascript.rb, line 68
        def add_expr_escaped(src, code)
          add_expr_literal(src, escaped_expr(code))
        end
    

    [Source]

    # File erubis/engine/ejavascript.rb, line 62
        def add_expr_literal(src, code)
          add_indent(src, @indent)
          code.strip!
          src << "#{@bufvar}.push(#{code});"
        end
    

    [Source]

    # File erubis/engine/ejavascript.rb, line 41
        def add_indent(src, indent)
          src << (src.empty? || src[-1] == ?\n ? indent : ' ')
        end
    

    [Source]

    # File erubis/engine/ejavascript.rb, line 78
        def add_postamble(src)
          src << "\n" if src[-1] == ?;
          if @docwrite
            src << @indent << 'document.write(' << @bufvar << ".join(\"\"));\n"
          else
            src << @indent << @bufvar << ".join(\"\");\n"
          end
        end
    

    [Source]

    # File erubis/engine/ejavascript.rb, line 32
        def add_preamble(src)
          src << "#{@indent}var #{@bufvar} = [];"
        end
    

    [Source]

    # File erubis/engine/ejavascript.rb, line 58
        def add_stmt(src, code)
          src << code
        end
    

    [Source]

    # File erubis/engine/ejavascript.rb, line 45
        def add_text(src, text)
          return if text.empty?
          add_indent(src, @indent)
          src << @bufvar << '.push("'
          s = escape_text(text)
          if s[-1] == ?\n
            s[-2, 2] = ''
            src << s << "\");\n"
          else
            src << s << "\");"
          end
        end
    

    [Source]

    # File erubis/engine/ejavascript.rb, line 36
        def escape_text(text)
          @@table_ ||= { "\r"=>"\\r", "\n"=>"\\n\\\n", "\t"=>"\\t", '"'=>'\\"', "\\"=>"\\\\" }
          return text.gsub!(/[\r\n\t"\\]/) { |m| @@table_[m] } || text
        end
    

    [Source]

    # File erubis/engine/ejavascript.rb, line 24
        def init_generator(properties={})
          super
          @escapefunc ||= 'escape'
          @indent = properties[:indent] || ''
          @bufvar = properties[:bufvar] || '_buf'
          @docwrite = properties[:docwrite] != false  # '!= false' will be removed in the next release
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/Main.html000066400000000000000000000630011170760342400217500ustar00rootroot00000000000000 Class: Erubis::Main
    Class Erubis::Main
    In: erubis/main.rb
    Parent: Object

    main class of command

    ex.

      Main.main(ARGV)
    

    Methods

    execute   main   new  

    Public Class methods

    [Source]

    # File erubis/main.rb, line 40
        def self.main(argv=ARGV)
          status = 0
          begin
            Main.new.execute(ARGV)
          rescue CommandOptionError => ex
            $stderr.puts ex.message
            status = 1
          end
          exit(status)
        end
    

    [Source]

    # File erubis/main.rb, line 51
        def initialize
          @single_options = "hvxztTSbeBXNUC"
          @arg_options    = "pcrfKIlaE" #C
          @option_names   = {
            'h' => :help,
            'v' => :version,
            'x' => :source,
            'z' => :syntax,
            'T' => :unexpand,
            't' => :untabify,      # obsolete
            'S' => :intern,
            'b' => :bodyonly,
            'B' => :binding,
            'p' => :pattern,
            'c' => :context,
            #'C' => :class,
            'e' => :escape,
            'r' => :requires,
            'f' => :datafiles,
            'K' => :kanji,
            'I' => :includes,
            'l' => :lang,
            'a' => :action,
            'E' => :enhancers,
            'X' => :notext,
            'N' => :linenum,
            'U' => :unique,
            'C' => :compact,
          }
          assert unless @single_options.length + @arg_options.length == @option_names.length
          (@single_options + @arg_options).each_byte do |ch|
            assert unless @option_names.key?(ch.chr)
          end
        end
    

    Public Instance methods

    [Source]

    # File erubis/main.rb, line 87
        def execute(argv=ARGV)
          ## parse command-line options
          options, properties = parse_argv(argv, @single_options, @arg_options)
          filenames = argv
          options['h'] = true if properties[:help]
          opts = Object.new
          arr = @option_names.collect {|ch, name| "def #{name}; @#{name}; end\n" }
          opts.instance_eval arr.join
          options.each do |ch, val|
            name = @option_names[ch]
            opts.instance_variable_set("@#{name}", val)
          end
    
          ## help, version, enhancer list
          if opts.help || opts.version
            puts version()         if opts.version
            puts usage()           if opts.help
            puts show_properties() if opts.help
            puts show_enhancers()  if opts.help
            return
          end
    
          ## include path
          opts.includes.split(/,/).each do |path|
            $: << path
          end if opts.includes
    
          ## require library
          opts.requires.split(/,/).each do |library|
            require library
          end if opts.requires
    
          ## action
          action = opts.action
          action ||= 'syntax'  if opts.syntax
          action ||= 'convert' if opts.source || opts.notext
    
          ## lang
          lang = opts.lang || 'ruby'
          action ||= 'convert' if opts.lang
    
          ## class name of Eruby
          #classname = opts.class
          classname = nil
          klass = get_classobj(classname, lang, properties[:pi])
    
          ## kanji code
          $KCODE = opts.kanji if opts.kanji
    
          ## read context values from yaml file
          datafiles = opts.datafiles
          context = load_datafiles(datafiles, opts)
    
          ## parse context data
          if opts.context
            context = parse_context_data(opts.context, opts)
          end
    
          ## properties for engine
          properties[:escape]   = true         if opts.escape && !properties.key?(:escape)
          properties[:pattern]  = opts.pattern if opts.pattern
          #properties[:trim]     = false        if opts.notrim
          properties[:preamble] = properties[:postamble] = false if opts.bodyonly
          properties[:pi]       = nil          if properties[:pi] == true
    
          ## create engine and extend enhancers
          engine = klass.new(nil, properties)
          enhancers = get_enhancers(opts.enhancers)
          #enhancers.push(Erubis::EscapeEnhancer) if opts.escape
          enhancers.each do |enhancer|
            engine.extend(enhancer)
            engine.bipattern = properties[:bipattern] if enhancer == Erubis::BiPatternEnhancer
          end
    
          ## no-text
          engine.extend(Erubis::NoTextEnhancer) if opts.notext
    
          ## convert and execute
          val = nil
          msg = "Syntax OK\n"
          if filenames && !filenames.empty?
            filenames.each do |filename|
              File.file?(filename)  or
                raise CommandOptionError.new("#{filename}: file not found.")
              engine.filename = filename
              engine.convert!(File.read(filename))
              val = do_action(action, engine, context, filename, opts)
              msg = nil if val
            end
          else
            engine.filename = filename = '(stdin)'
            engine.convert!($stdin.read())
            val = do_action(action, engine, context, filename, opts)
            msg = nil if val
          end
          print msg if action == 'syntax' && msg
    
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/NoCodeEnhancer.html000066400000000000000000000176771170760342400237210ustar00rootroot00000000000000 Module: Erubis::NoCodeEnhancer
    Module Erubis::NoCodeEnhancer
    In: erubis/enhancer.rb

    remove code and leave text, especially useful when validating HTML tags.

    ex.

      $ erubis -s -E NoCode file.eruby | tidy -errors
    

    this is language independent.

    Methods

    Public Instance methods

    [Source]

    # File erubis/enhancer.rb, line 317
        def add_expr(src, code, indicator)
          src << "\n" * code.count("\n")
        end
    

    [Source]

    # File erubis/enhancer.rb, line 310
        def add_postamble(src)
        end
    

    [Source]

    # File erubis/enhancer.rb, line 307
        def add_preamble(src)
        end
    

    [Source]

    # File erubis/enhancer.rb, line 321
        def add_stmt(src, code)
          src << "\n" * code.count("\n")
        end
    

    [Source]

    # File erubis/enhancer.rb, line 313
        def add_text(src, text)
          src << text
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/NoCodeEruby.html000066400000000000000000000050651170760342400232500ustar00rootroot00000000000000 Class: Erubis::NoCodeEruby
    Class Erubis::NoCodeEruby
    In: erubis/engine/enhanced.rb
    Parent: Eruby

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/NoTextEnhancer.html000066400000000000000000000106451170760342400237570ustar00rootroot00000000000000 Module: Erubis::NoTextEnhancer
    Module Erubis::NoTextEnhancer
    In: erubis/enhancer.rb

    remove text and leave code, especially useful when debugging.

    ex.

      $ erubis -s -E NoText file.eruby | more
    

    this is language independent.

    Methods

    add_text  

    Public Instance methods

    [Source]

    # File erubis/enhancer.rb, line 282
        def add_text(src, text)
          src << ("\n" * text.count("\n"))
          if text[-1] != ?\n
            text =~ /^(.*?)\z/
            src << (' ' * $1.length)
          end
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/NoTextEruby.html000066400000000000000000000050651170760342400233220ustar00rootroot00000000000000 Class: Erubis::NoTextEruby
    Class Erubis::NoTextEruby
    In: erubis/engine/enhanced.rb
    Parent: Eruby

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/NotSupportedError.html000066400000000000000000000047001170760342400245450ustar00rootroot00000000000000 Class: Erubis::NotSupportedError
    Class Erubis::NotSupportedError
    In: erubis/error.rb
    Parent: ErubisError

    raised when method or function is not supported

    ruby-erubis-2.7.0/doc-api/classes/Erubis/OptimizedEruby.html000066400000000000000000000101571170760342400240430ustar00rootroot00000000000000 Class: Erubis::OptimizedEruby
    Class Erubis::OptimizedEruby
    In: erubis/engine/optimized.rb
    Parent: Basic::Engine

    Eruby class which generates optimized ruby code

    Methods

    Public Instance methods

    [Source]

    # File erubis/engine/optimized.rb, line 106
        def init_converter(properties={})
          @pi = 'rb'
          super(properties)
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/OptimizedGenerator.html000066400000000000000000000502251170760342400247030ustar00rootroot00000000000000 Module: Erubis::OptimizedGenerator
    Module Erubis::OptimizedGenerator
    In: erubis/engine/optimized.rb

    Included Modules

    Public Instance methods

    [Source]

    # File erubis/engine/optimized.rb, line 20
        def init_generator(properties={})
          super
          @escapefunc ||= "Erubis::XmlHelper.escape_xml"
          @initialized = false
          @prev_is_expr = false
        end
    

    Protected Instance methods

    [Source]

    # File erubis/engine/optimized.rb, line 85
        def add_expr_debug(src, code)
          code.strip!
          s = (code.dump =~ /\A"(.*)"\z/) && $1
          src << ' $stderr.puts("*** debug: ' << s << '=#{(' << code << ').inspect}");'
        end
    

    [Source]

    # File erubis/engine/optimized.rb, line 79
        def add_expr_escaped(src, code)
          unless @initialized; src << "_buf = ''"; @initialized = true; end
          switch_to_expr(src)
          src << " << " << escaped_expr(code)
        end
    

    [Source]

    # File erubis/engine/optimized.rb, line 73
        def add_expr_literal(src, code)
          unless @initialized; src << "_buf = ''"; @initialized = true; end
          switch_to_expr(src)
          src << " << (" << code << ").to_s"
        end
    

    [Source]

    # File erubis/engine/optimized.rb, line 91
        def add_postamble(src)
          #super if @initialized
          src << "\n_buf\n" if @initialized
        end
    

    [Source]

    # File erubis/engine/optimized.rb, line 50
        def add_preamble(src)
          #@initialized = false
          #@prev_is_expr = false
        end
    

    [Source]

    # File erubis/engine/optimized.rb, line 66
        def add_stmt(src, code)
          switch_to_stmt(src) if @initialized
          #super
          src << code
          src << ';' unless code[-1] == ?\n
        end
    

    [Source]

    # File erubis/engine/optimized.rb, line 55
        def add_text(src, text)
          return if text.empty?
          if @initialized
            switch_to_expr(src)
            src << " << '" << escape_text(text) << "'"
          else
            src << "_buf = '" << escape_text(text) << "';"
            @initialized = true
          end
        end
    

    [Source]

    # File erubis/engine/optimized.rb, line 29
        def escape_text(text)
          text.gsub(/['\\]/, '\\\\\&')   # "'" => "\\'",  '\\' => '\\\\'
        end
    

    [Source]

    # File erubis/engine/optimized.rb, line 33
        def escaped_expr(code)
          @escapefunc ||= 'Erubis::XmlHelper.escape_xml'
          return "#{@escapefunc}(#{code})"
        end
    

    [Source]

    # File erubis/engine/optimized.rb, line 38
        def switch_to_expr(src)
          return if @prev_is_expr
          @prev_is_expr = true
          src << ' _buf'
        end
    

    [Source]

    # File erubis/engine/optimized.rb, line 44
        def switch_to_stmt(src)
          return unless @prev_is_expr
          @prev_is_expr = false
          src << ';'
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/OptimizedXmlEruby.html000066400000000000000000000104761170760342400245300ustar00rootroot00000000000000 Class: Erubis::OptimizedXmlEruby
    Class Erubis::OptimizedXmlEruby
    In: erubis/engine/optimized.rb
    Parent: OptimizedEruby

    XmlEruby class which generates optimized ruby code

    Methods

    Included Modules

    Public Instance methods

    [Source]

    # File erubis/engine/optimized.rb, line 120
        def add_expr_debug(src, code)
          switch_to_stmt(src) if indicator == '===' && !@initialized
          super
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/PI.html000066400000000000000000000061561170760342400214040ustar00rootroot00000000000000 Module: Erubis::PI
    ruby-erubis-2.7.0/doc-api/classes/Erubis/PI/000077500000000000000000000000001170760342400205065ustar00rootroot00000000000000ruby-erubis-2.7.0/doc-api/classes/Erubis/PI/Converter.html000066400000000000000000000340771170760342400233560ustar00rootroot00000000000000 Module: Erubis::PI::Converter
    Module Erubis::PI::Converter
    In: erubis/converter.rb

    Processing Instructions (PI) converter for XML. this class converts ’<?rb … ?>’ and ’${…}’ notation.

    Methods

    Included Modules

    Attributes

    pi  [RW] 
    prefix  [RW] 

    Public Instance methods

    [Source]

    # File erubis/converter.rb, line 224
        def convert(input)
          code = super(input)
          return @header || @footer ? "#{@header}#{code}#{@footer}" : code
        end
    

    [Source]

    # File erubis/converter.rb, line 215
        def init_converter(properties={})
          super(properties)
          @trim    = properties.fetch(:trim, true)
          @pi      = properties[:pi] if properties[:pi]
          @embchar = properties[:embchar] || '@'
          @pattern = properties[:pattern]
          @pattern = '<% %>' if @pattern.nil?  #|| @pattern == true
        end
    

    Protected Instance methods

    [Source]

    # File erubis/converter.rb, line 231
        def convert_input(codebuf, input)
          unless @regexp
            @pi ||= 'e'
            ch = Regexp.escape(@embchar)
            if @pattern
              left, right = @pattern.split(' ')
              @regexp = /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?|#{ch}(!*)?\{(.*?)\}#{ch}|#{left}(=+)(.*?)#{right}/m
            else
              @regexp = /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?|#{ch}(!*)?\{(.*?)\}#{ch}/m
            end
          end
          #
          is_bol = true
          pos = 0
          input.scan(@regexp) do |pi_arg, stmt, rspace,
                                  indicator1, expr1, indicator2, expr2|
            match = Regexp.last_match
            len = match.begin(0) - pos
            text = input[pos, len]
            pos = match.end(0)
            lspace = stmt ? detect_spaces_at_bol(text, is_bol) : nil
            is_bol = stmt && rspace ? true : false
            add_text(codebuf, text) # unless text.empty?
            #
            if stmt
              if @trim && lspace && rspace
                add_pi_stmt(codebuf, "#{lspace}#{stmt}#{rspace}", pi_arg)
              else
                add_text(codebuf, lspace) if lspace
                add_pi_stmt(codebuf, stmt, pi_arg)
                add_text(codebuf, rspace) if rspace
              end
            else
              add_pi_expr(codebuf, expr1 || expr2, indicator1 || indicator2)
            end
          end
          #rest = $' || input                        # ruby1.8
          rest = pos == 0 ? input : input[pos..-1]   # ruby1.9
          add_text(codebuf, rest)
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/PI/Ec.html000066400000000000000000000076711170760342400217360ustar00rootroot00000000000000 Class: Erubis::PI::Ec
    Class Erubis::PI::Ec
    In: erubis/engine/ec.rb
    Parent: PI::Engine

    class XmlEc < Ec

      include EscapeEnhancer
    

    end

    Methods

    Included Modules

    Public Instance methods

    [Source]

    # File erubis/engine/ec.rb, line 109
        def init_converter(properties={})
          @pi = 'c'
          super(properties)
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/PI/Ecpp.html000066400000000000000000000077171170760342400222770ustar00rootroot00000000000000 Class: Erubis::PI::Ecpp
    Class Erubis::PI::Ecpp
    In: erubis/engine/ecpp.rb
    Parent: PI::Engine

    class XmlEcpp < Ecpp

      include EscapeEnhancer
    

    end

    Methods

    Included Modules

    Public Instance methods

    [Source]

    # File erubis/engine/ecpp.rb, line 105
        def init_converter(properties={})
          @pi = 'cpp'
          super(properties)
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/PI/Ejava.html000066400000000000000000000077321170760342400224330ustar00rootroot00000000000000 Class: Erubis::PI::Ejava
    Class Erubis::PI::Ejava
    In: erubis/engine/ejava.rb
    Parent: PI::Engine

    class XmlEjava < Ejava

      include EscapeEnhancer
    

    end

    Methods

    Included Modules

    Public Instance methods

    [Source]

    # File erubis/engine/ejava.rb, line 103
        def init_converter(properties={})
          @pi = 'java'
          super(properties)
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/PI/Ejavascript.html000066400000000000000000000100241170760342400236440ustar00rootroot00000000000000 Class: Erubis::PI::Ejavascript
    Class Erubis::PI::Ejavascript
    In: erubis/engine/ejavascript.rb
    Parent: PI::Engine

    class XmlEjavascript < Ejavascript

      include EscapeEnhancer
    

    end

    Methods

    Included Modules

    Public Instance methods

    [Source]

    # File erubis/engine/ejavascript.rb, line 111
        def init_converter(properties={})
          @pi = 'js'
          super(properties)
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/PI/Engine.html000066400000000000000000000053131170760342400226030ustar00rootroot00000000000000 Class: Erubis::PI::Engine
    Class Erubis::PI::Engine
    In: erubis/engine.rb
    Parent: Engine

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/PI/Eperl.html000066400000000000000000000077311170760342400224530ustar00rootroot00000000000000 Class: Erubis::PI::Eperl
    Class Erubis::PI::Eperl
    In: erubis/engine/eperl.rb
    Parent: PI::Engine

    class XmlEperl < Eperl

      include EscapeEnhancer
    

    end

    Methods

    Included Modules

    Public Instance methods

    [Source]

    # File erubis/engine/eperl.rb, line 87
        def init_converter(properties={})
          @pi = 'perl'
          super(properties)
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/PI/Ephp.html000066400000000000000000000077161170760342400223030ustar00rootroot00000000000000 Class: Erubis::PI::Ephp
    Class Erubis::PI::Ephp
    In: erubis/engine/ephp.rb
    Parent: PI::Engine

    class XmlEphp < Ephp

      include EscapeEnhancer
    

    end

    Methods

    Included Modules

    Public Instance methods

    [Source]

    # File erubis/engine/ephp.rb, line 91
        def init_converter(properties={})
          @pi = 'php'
          super(properties)
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/PI/Eruby.html000066400000000000000000000076301170760342400224700ustar00rootroot00000000000000 Class: Erubis::PI::Eruby
    Class Erubis::PI::Eruby
    In: erubis/engine/eruby.rb
    Parent: PI::Engine

    Methods

    Included Modules

    Public Instance methods

    [Source]

    # File erubis/engine/eruby.rb, line 117
        def init_converter(properties={})
          @pi = 'rb'
          super(properties)
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/PI/Escheme.html000066400000000000000000000077601170760342400227570ustar00rootroot00000000000000 Class: Erubis::PI::Escheme
    Class Erubis::PI::Escheme
    In: erubis/engine/escheme.rb
    Parent: PI::Engine

    class XmlEscheme < Escheme

      include EscapeEnhancer
    

    end

    Methods

    Included Modules

    Public Instance methods

    [Source]

    # File erubis/engine/escheme.rb, line 106
        def init_converter(properties={})
          @pi = 'scheme'
          super(properties)
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/PI/TinyEruby.html000066400000000000000000000375231170760342400233400ustar00rootroot00000000000000 Class: Erubis::PI::TinyEruby
    Class Erubis::PI::TinyEruby
    In: erubis/tiny.rb
    Parent: Object

    Methods

    convert   evaluate   new   result  

    Constants

    EMBEDDED_PATTERN = /(^[ \t]*)?<\?rb(\s.*?)\?>([ \t]*\r?\n)?|@(!+)?\{(.*?)\}@/m

    Attributes

    src  [R] 

    Public Class methods

    [Source]

    # File erubis/tiny.rb, line 79
        def initialize(input=nil, options={})
          @escape  = options[:escape] || 'Erubis::XmlHelper.escape_xml'
          @src = convert(input) if input
        end
    

    Public Instance methods

    [Source]

    # File erubis/tiny.rb, line 88
        def convert(input)
          src = "_buf = '';"           # preamble
          pos = 0
          input.scan(EMBEDDED_PATTERN) do |lspace, stmt, rspace, indicator, expr|
            match = Regexp.last_match
            len   = match.begin(0) - pos
            text  = input[pos, len]
            pos   = match.end(0)
            #src << " _buf << '" << escape_text(text) << "';"
            text.gsub!(/['\\]/, '\\\\\&')
            src << " _buf << '" << text << "';" unless text.empty?
            if stmt                # <?rb ... ?>
              if lspace && rspace
                src << "#{lspace}#{stmt}#{rspace}"
              else
                src << " _buf << '" << lspace << "';" if lspace
                src << stmt << ";"
                src << " _buf << '" << rspace << "';" if rspace
              end
            else                       # ${...}, $!{...}
              if !indicator
                src << " _buf << " << @escape << "(" << expr << ");"
              elsif indicator == '!'
                src << " _buf << (" << expr << ").to_s;"
              end
            end
          end
          #rest = $' || input                        # ruby1.8
          rest = pos == 0 ? input : input[pos..-1]   # ruby1.9
          #src << " _buf << '" << escape_text(rest) << "';"
          rest.gsub!(/['\\]/, '\\\\\&')
          src << " _buf << '" << rest << "';" unless rest.empty?
          src << "\n_buf.to_s\n"       # postamble
          return src
        end
    

    [Source]

    # File erubis/tiny.rb, line 132
        def evaluate(_context=Object.new)
          if _context.is_a?(Hash)
            _obj = Object.new
            _context.each do |k, v| _obj.instance_variable_set("@#{k}", v) end
            _context = _obj
          end
          _context.instance_eval @src
        end
    

    def escape_text(text)

      return text.gsub!(/['\\]/, '\\\\\&') || text
    

    end

    [Source]

    # File erubis/tiny.rb, line 128
        def result(_binding=TOPLEVEL_BINDING)
          eval @src, _binding
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/PercentLineEnhancer.html000066400000000000000000000103011170760342400247330ustar00rootroot00000000000000 Module: Erubis::PercentLineEnhancer
    Module Erubis::PercentLineEnhancer
    In: erubis/enhancer.rb

    regards lines starting with ’%’ as program code

    this is for compatibility to eruby and ERB.

    this is language-independent.

    Methods

    add_text  

    Included Modules

    Public Instance methods

    [Source]

    # File erubis/enhancer.rb, line 516
        def add_text(src, text)
          unless @prefixrexp
            @prefixchar = '%'
            @prefixrexp = /^\%(.*?\r?\n)/
          end
          super(src, text)
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/PercentLineEruby.html000066400000000000000000000051111170760342400243010ustar00rootroot00000000000000 Class: Erubis::PercentLineEruby
    Class Erubis::PercentLineEruby
    In: erubis/engine/enhanced.rb
    Parent: Eruby

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/PerlGenerator.html000066400000000000000000000337731170760342400236520ustar00rootroot00000000000000 Module: Erubis::PerlGenerator
    Module Erubis::PerlGenerator
    In: erubis/engine/eperl.rb

    Included Modules

    Public Instance methods

    [Source]

    # File erubis/engine/eperl.rb, line 49
        def add_expr_debug(src, code)
          code.strip!
          s = code.gsub(/\'/, "\\'")
          src << @func << "('*** debug: #{code}=', #{code}, \"\\n\");"
        end
    

    [Source]

    # File erubis/engine/eperl.rb, line 45
        def add_expr_escaped(src, code)
          add_expr_literal(src, escaped_expr(code))
        end
    

    [Source]

    # File erubis/engine/eperl.rb, line 40
        def add_expr_literal(src, code)
          code.strip!
          src << @func << "(" << code << "); "
        end
    

    [Source]

    # File erubis/engine/eperl.rb, line 59
        def add_postamble(src)
          src << "\n" unless src[-1] == ?\n
        end
    

    [Source]

    # File erubis/engine/eperl.rb, line 28
        def add_preamble(src)
          src << "use HTML::Entities; ";
        end
    

    [Source]

    # File erubis/engine/eperl.rb, line 55
        def add_stmt(src, code)
          src << code
        end
    

    [Source]

    # File erubis/engine/eperl.rb, line 36
        def add_text(src, text)
          src << @func << "('" << escape_text(text) << "'); " unless text.empty?
        end
    

    [Source]

    # File erubis/engine/eperl.rb, line 32
        def escape_text(text)
          return text.gsub!(/['\\]/, '\\\\\&') || text
        end
    

    [Source]

    # File erubis/engine/eperl.rb, line 22
        def init_generator(properties={})
          super
          @escapefunc ||= 'encode_entities'
          @func = properties[:func] || 'print'
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/PhpGenerator.html000066400000000000000000000336461170760342400234760ustar00rootroot00000000000000 Module: Erubis::PhpGenerator
    Module Erubis::PhpGenerator
    In: erubis/engine/ephp.rb

    Included Modules

    Public Instance methods

    [Source]

    # File erubis/engine/ephp.rb, line 46
        def add_expr_debug(src, code)
          code.strip!
          s = code.gsub(/\'/, "\\'")
          src << "<?php error_log('*** debug: #{s}='.(#{code}), 0); ?>"
        end
    

    [Source]

    # File erubis/engine/ephp.rb, line 42
        def add_expr_escaped(src, code)
          add_expr_literal(src, escaped_expr(code))
        end
    

    [Source]

    # File erubis/engine/ephp.rb, line 37
        def add_expr_literal(src, code)
          code.strip!
          src << "<?php echo #{code}; ?>"
        end
    

    [Source]

    # File erubis/engine/ephp.rb, line 63
        def add_postamble(src)
          # empty
        end
    

    [Source]

    # File erubis/engine/ephp.rb, line 25
        def add_preamble(src)
          # empty
        end
    

    [Source]

    # File erubis/engine/ephp.rb, line 52
        def add_stmt(src, code)
          src << "<?php"
          src << " " if code[0] != ?\ #
          if code[-1] == ?\n
            code.chomp!
            src << code << "?>\n"
          else
            src << code << "?>"
          end
        end
    

    [Source]

    # File erubis/engine/ephp.rb, line 33
        def add_text(src, text)
          src << escape_text(text)
        end
    

    [Source]

    # File erubis/engine/ephp.rb, line 29
        def escape_text(text)
          return text.gsub!(/<\?xml\b/, '<<?php ?>?xml') || text
        end
    

    [Source]

    # File erubis/engine/ephp.rb, line 20
        def init_generator(properties={})
          super
          @escapefunc ||= 'htmlspecialchars'
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/PrefixedLineEnhancer.html000066400000000000000000000224411170760342400251110ustar00rootroot00000000000000 Module: Erubis::PrefixedLineEnhancer
    Module Erubis::PrefixedLineEnhancer
    In: erubis/enhancer.rb

    regards lines starting with ’^[ \t]*%’ as program code

    in addition you can specify prefix character (default ’%’)

    this is language-independent.

    Methods

    Public Instance methods

    [Source]

    # File erubis/enhancer.rb, line 454
        def add_text(src, text)
          unless @prefixrexp
            @prefixchar ||= '%'
            @prefixrexp = Regexp.compile("^([ \\t]*)\\#{@prefixchar}(.*?\\r?\\n)")
          end
          pos = 0
          text2 = ''
          text.scan(@prefixrexp) do
            space = $1
            line  = $2
            space, line = '', $1 unless $2
            match = Regexp.last_match
            len   = match.begin(0) - pos
            str   = text[pos, len]
            pos   = match.end(0)
            if text2.empty?
              text2 = str
            else
              text2 << str
            end
            if line[0, 1] == @prefixchar
              text2 << space << line
            else
              super(src, text2)
              text2 = ''
              add_stmt(src, space + line)
            end
          end
          #rest = pos == 0 ? text : $'             # ruby1.8
          rest = pos == 0 ? text : text[pos..-1]   # ruby1.9
          unless text2.empty?
            text2 << rest if rest
            rest = text2
          end
          super(src, rest)
        end
    

    [Source]

    # File erubis/enhancer.rb, line 449
        def init_generator(properties={})
          super
          @prefixchar = properties[:prefixchar]
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/PrefixedLineEruby.html000066400000000000000000000051151170760342400244530ustar00rootroot00000000000000 Class: Erubis::PrefixedLineEruby
    Class Erubis::PrefixedLineEruby
    In: erubis/engine/enhanced.rb
    Parent: Eruby

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/PreprocessingEruby.html000066400000000000000000000124541170760342400247240ustar00rootroot00000000000000 Class: Erubis::PreprocessingEruby
    Class Erubis::PreprocessingEruby
    In: erubis/preprocessing.rb
    Parent: Erubis::Eruby

    for preprocessing

    Methods

    Public Class methods

    [Source]

    # File erubis/preprocessing.rb, line 17
        def initialize(input, params={})
          params = params.dup
          params[:pattern] ||= '\[% %\]'    # use '[%= %]' instead of '<%= %>'
          #params[:escape] = true            # transport '[%= %]' and '[%== %]'
          super
        end
    

    Public Instance methods

    [Source]

    # File erubis/preprocessing.rb, line 24
        def add_expr_escaped(src, code)
          add_expr_literal(src, "_decode((#{code}))")
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/PreprocessingHelper.html000066400000000000000000000145551170760342400250610ustar00rootroot00000000000000 Module: Erubis::PreprocessingHelper
    Module Erubis::PreprocessingHelper
    In: erubis/preprocessing.rb

    helper methods for preprocessing

    Methods

    _?   _P   _decode   _p  

    Public Instance methods

    _?(arg)

    Alias for _p

    [Source]

    # File erubis/preprocessing.rb, line 42
        def _P(arg)
          return "<%=h(#{arg})%>"
        end
    

    [Source]

    # File erubis/preprocessing.rb, line 48
        def _decode(arg)
          arg = arg.to_s
          arg.gsub!(/%3C%25(?:=|%3D)(.*?)%25%3E/) { "<%=#{CGI.unescape($1)}%>" }
          arg.gsub!(/&lt;%=(.*?)%&gt;/) { "<%=#{CGI.unescapeHTML($1)}%>" }
          return arg
        end
    

    [Source]

    # File erubis/preprocessing.rb, line 38
        def _p(arg)
          return "<%=#{arg}%>"
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/PrintEnabledEnhancer.html000066400000000000000000000174301170760342400251040ustar00rootroot00000000000000 Module: Erubis::PrintEnabledEnhancer
    Module Erubis::PrintEnabledEnhancer
    In: erubis/enhancer.rb

    enable print function

    Notice: use Eruby#evaluate() and don‘t use Eruby#result() to be enable print function.

    this is only for Eruby.

    Methods

    Public Instance methods

    [Source]

    # File erubis/enhancer.rb, line 127
        def add_preamble(src)
          src << "@_buf = "
          super
        end
    

    [Source]

    # File erubis/enhancer.rb, line 138
        def evaluate(context=nil)
          _src = @src
          if context.is_a?(Hash)
            context.each do |key, val| instance_variable_set("@#{key}", val) end
          elsif context
            context.instance_variables.each do |name|
              instance_variable_set(name, context.instance_variable_get(name))
            end
          end
          return instance_eval(_src, (@filename || '(erubis)'))
        end
    

    [Source]

    # File erubis/enhancer.rb, line 132
        def print(*args)
          args.each do |arg|
            @_buf << arg.to_s
          end
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/PrintEnabledEruby.html000066400000000000000000000051151170760342400244440ustar00rootroot00000000000000 Class: Erubis::PrintEnabledEruby
    Class Erubis::PrintEnabledEruby
    In: erubis/engine/enhanced.rb
    Parent: Eruby

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/PrintOutEnhancer.html000066400000000000000000000200631170760342400243150ustar00rootroot00000000000000 Module: Erubis::PrintOutEnhancer
    Module Erubis::PrintOutEnhancer
    In: erubis/enhancer.rb

    use print statement instead of ‘_buf << …’

    this is only for Eruby.

    Public Instance methods

    [Source]

    # File erubis/enhancer.rb, line 102
        def add_expr_escaped(src, code)
          src << " print #{escaped_expr(code)};"
        end
    

    [Source]

    # File erubis/enhancer.rb, line 98
        def add_expr_literal(src, code)
          src << " print((#{code}).to_s);"
        end
    

    [Source]

    # File erubis/enhancer.rb, line 106
        def add_postamble(src)
          src << "\n" unless src[-1] == ?\n
        end
    

    [Source]

    # File erubis/enhancer.rb, line 91
        def add_preamble(src)
        end
    

    [Source]

    # File erubis/enhancer.rb, line 94
        def add_text(src, text)
          src << " print '#{escape_text(text)}';" unless text.empty?
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/PrintOutEruby.html000066400000000000000000000050751170760342400236660ustar00rootroot00000000000000 Class: Erubis::PrintOutEruby
    Class Erubis::PrintOutEruby
    In: erubis/engine/enhanced.rb
    Parent: Eruby

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/PrintOutSimplifiedEruby.html000066400000000000000000000052601170760342400256700ustar00rootroot00000000000000 Class: Erubis::PrintOutSimplifiedEruby
    Class Erubis::PrintOutSimplifiedEruby
    In: erubis/engine/enhanced.rb
    Parent: Eruby
    ruby-erubis-2.7.0/doc-api/classes/Erubis/RubyEvaluator.html000066400000000000000000000233141170760342400236730ustar00rootroot00000000000000 Module: Erubis::RubyEvaluator
    Module Erubis::RubyEvaluator
    In: erubis/evaluator.rb

    evaluator for Ruby

    Methods

    def_method   evaluate   result  

    Included Modules

    Public Instance methods

    if object is an Class or Module then define instance method to it, else define singleton method to it.

    [Source]

    # File erubis/evaluator.rb, line 79
        def def_method(object, method_name, filename=nil)
          m = object.is_a?(Module) ? :module_eval : :instance_eval
          object.__send__(m, "def #{method_name}; #{@src}; end", filename || @filename || '(erubis)')
        end
    

    invoke context.instance_eval(@src)

    [Source]

    # File erubis/evaluator.rb, line 69
        def evaluate(_context=Context.new)
          _context = Context.new(_context) if _context.is_a?(Hash)
          #return _context.instance_eval(@src, @filename || '(erubis)')
          #@_proc ||= eval("proc { #{@src} }", Erubis::EMPTY_BINDING, @filename || '(erubis)')
          @_proc ||= eval("proc { #{@src} }", binding(), @filename || '(erubis)')
          return _context.instance_eval(&@_proc)
        end
    

    eval(@src) with binding object

    [Source]

    # File erubis/evaluator.rb, line 53
        def result(_binding_or_hash=TOPLEVEL_BINDING)
          _arg = _binding_or_hash
          if _arg.is_a?(Hash)
            _b = binding()
            eval _arg.collect{|k,v| "#{k} = _arg[#{k.inspect}]; "}.join, _b
          elsif _arg.is_a?(Binding)
            _b = _arg
          elsif _arg.nil?
            _b = binding()
          else
            raise ArgumentError.new("#{self.class.name}#result(): argument should be Binding or Hash but passed #{_arg.class.name} object.")
          end
          return eval(@src, _b, (@filename || '(erubis'))
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/RubyGenerator.html000066400000000000000000000331421170760342400236570ustar00rootroot00000000000000 Module: Erubis::RubyGenerator
    Module Erubis::RubyGenerator
    In: erubis/engine/eruby.rb

    code generator for Ruby

    Included Modules

    Public Instance methods

    [Source]

    # File erubis/engine/eruby.rb, line 63
        def add_expr_debug(src, code)
          code.strip!
          s = (code.dump =~ /\A"(.*)"\z/) && $1
          src << ' $stderr.puts("*** debug: ' << s << '=#{(' << code << ').inspect}");'
        end
    

    [Source]

    # File erubis/engine/eruby.rb, line 59
        def add_expr_escaped(src, code)
          src << " #{@bufvar} << " << escaped_expr(code) << ';'
        end
    

    [Source]

    # File erubis/engine/eruby.rb, line 55
        def add_expr_literal(src, code)
          src << " #{@bufvar} << (" << code << ').to_s;'
        end
    

    [Source]

    # File erubis/engine/eruby.rb, line 49
        def add_stmt(src, code)
          #src << code << ';'
          src << code
          src << ';' unless code[-1] == ?\n
        end
    

    [Source]

    # File erubis/engine/eruby.rb, line 45
        def add_text(src, text)
          src << " #{@bufvar} << '" << escape_text(text) << "';" unless text.empty?
        end
    

    [Source]

    # File erubis/engine/eruby.rb, line 31
        def escape_text(text)
          text.gsub(/['\\]/, '\\\\\&')   # "'" => "\\'",  '\\' => '\\\\'
        end
    

    [Source]

    # File erubis/engine/eruby.rb, line 35
        def escaped_expr(code)
          return "#{@escapefunc}(#{code})"
        end
    

    [Source]

    # File erubis/engine/eruby.rb, line 21
        def init_generator(properties={})
          super
          @escapefunc ||= "Erubis::XmlHelper.escape_xml"
          @bufvar     = properties[:bufvar] || "_buf"
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/SchemeGenerator.html000066400000000000000000000421051170760342400241410ustar00rootroot00000000000000 Module: Erubis::SchemeGenerator
    Module Erubis::SchemeGenerator
    In: erubis/engine/escheme.rb

    Included Modules

    Public Instance methods

    [Source]

    # File erubis/engine/escheme.rb, line 71
        def add_expr_debug(src, code)
          s = (code.strip! || code).gsub(/\"/, '\\"')
          src << "(display \"*** debug: #{s}=\")(display #{code.strip})(display \"\\n\")"
        end
    

    [Source]

    # File erubis/engine/escheme.rb, line 67
        def add_expr_escaped(src, code)
          add_expr_literal(src, escaped_expr(code))
        end
    

    [Source]

    # File erubis/engine/escheme.rb, line 62
        def add_expr_literal(src, code)
          code.strip!
          src << "(#{@func} #{code})"
        end
    

    [Source]

    # File erubis/engine/escheme.rb, line 76
        def add_postamble(src)
          return unless @func == '_add'
          src << "\n" unless src[-1] == ?\n
          src << "  (reverse _buf))\n"
        end
    

    [Source]

    # File erubis/engine/escheme.rb, line 28
        def add_preamble(src)
          return unless @func == '_add'
          src << "(let ((_buf '())) " + \
                   "(define (_add x) (set! _buf (cons x _buf))) "
          #src << "(let* ((_buf '())" +        #             " (_add (lambda (x) (set! _buf (cons x _buf))))) "
        end
    

    [Source]

    # File erubis/engine/escheme.rb, line 58
        def add_stmt(src, code)
          src << code
        end
    

    [Source]

    # File erubis/engine/escheme.rb, line 47
        def add_text(src, text)
          return if text.empty?
          t = escape_text(text)
          if t[-1] == ?\n
            t[-1, 1] = ''
            src << "(#{@func} \"" << t << "\\n\")\n"
          else
            src << "(#{@func} \"" << t << '")'
          end
        end
    

    [Source]

    # File erubis/engine/escheme.rb, line 36
        def escape_text(text)
          @table_ ||= { '"'=>'\\"', '\\'=>'\\\\' }
          text.gsub!(/["\\]/) { |m| @table_[m] }
          return text
        end
    

    [Source]

    # File erubis/engine/escheme.rb, line 42
        def escaped_expr(code)
          code.strip!
          return "(#{@escapefunc} #{code})"
        end
    

    [Source]

    # File erubis/engine/escheme.rb, line 22
        def init_generator(properties={})
          super
          @escapefunc ||= 'escape'
          @func = properties[:func] || '_add'   # or 'display'
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/SimplifiedEruby.html000066400000000000000000000051011170760342400241550ustar00rootroot00000000000000 Class: Erubis::SimplifiedEruby
    Class Erubis::SimplifiedEruby
    In: erubis/engine/enhanced.rb
    Parent: Eruby

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/SimplifyEnhancer.html000066400000000000000000000174731170760342400243400ustar00rootroot00000000000000 Module: Erubis::SimplifyEnhancer
    Module Erubis::SimplifyEnhancer
    In: erubis/enhancer.rb

    get convert faster, but spaces around ’<%…%>’ are not trimmed.

    this is language-independent.

    Methods

    convert  

    Constants

    SIMPLE_REGEXP = /<%(=+|\#)?(.*?)-?%>/m   DEFAULT_REGEXP = /(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m

    Public Instance methods

    [Source]

    # File erubis/enhancer.rb, line 342
        def convert(input)
          src = ""
          add_preamble(src)
          #regexp = pattern_regexp(@pattern)
          pos = 0
          input.scan(SIMPLE_REGEXP) do |indicator, code|
            match = Regexp.last_match
            index = match.begin(0)
            text  = input[pos, index - pos]
            pos   = match.end(0)
            add_text(src, text)
            if !indicator              # <% %>
              add_stmt(src, code)
            elsif indicator[0] == ?\#  # <%# %>
              n = code.count("\n")
              add_stmt(src, "\n" * n)
            else                       # <%= %>
              add_expr(src, code, indicator)
            end
          end
          #rest = $' || input                      # ruby1.8
          rest = pos == 0 ? input : input[pos..-1]  # ruby1.9
          add_text(src, rest)
          add_postamble(src)
          return src
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/StdoutEnhancer.html000066400000000000000000000110631170760342400240130ustar00rootroot00000000000000 Module: Erubis::StdoutEnhancer
    Module Erubis::StdoutEnhancer
    In: erubis/enhancer.rb

    use $stdout instead of string

    this is only for Eruby.

    Methods

    Public Instance methods

    [Source]

    # File erubis/enhancer.rb, line 73
        def add_postamble(src)
          src << "\n''\n"
        end
    

    [Source]

    # File erubis/enhancer.rb, line 69
        def add_preamble(src)
          src << "#{@bufvar} = $stdout;"
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/StdoutEruby.html000066400000000000000000000050651170760342400233630ustar00rootroot00000000000000 Class: Erubis::StdoutEruby
    Class Erubis::StdoutEruby
    In: erubis/engine/enhanced.rb
    Parent: Eruby

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/StdoutSimplifiedEruby.html000066400000000000000000000052501170760342400253650ustar00rootroot00000000000000 Class: Erubis::StdoutSimplifiedEruby
    Class Erubis::StdoutSimplifiedEruby
    In: erubis/engine/enhanced.rb
    Parent: Eruby

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/StringBufferEnhancer.html000066400000000000000000000116241170760342400251340ustar00rootroot00000000000000 Module: Erubis::StringBufferEnhancer
    Module Erubis::StringBufferEnhancer
    In: erubis/enhancer.rb

    use String class for buffering

    this is only for Eruby.

    Methods

    Public Instance methods

    [Source]

    # File erubis/enhancer.rb, line 214
        def add_postamble(src)
          src << "\n" unless src[-1] == ?\n
          src << "#{@bufvar}.to_s\n"
        end
    

    [Source]

    # File erubis/enhancer.rb, line 210
        def add_preamble(src)
          src << "#{@bufvar} = '';"
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/StringBufferEruby.html000066400000000000000000000051151170760342400244750ustar00rootroot00000000000000 Class: Erubis::StringBufferEruby
    Class Erubis::StringBufferEruby
    In: erubis/engine/enhanced.rb
    Parent: Eruby

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/StringIOEruby.html000066400000000000000000000050311170760342400235700ustar00rootroot00000000000000 Class: Erubis::StringIOEruby
    Class Erubis::StringIOEruby
    In: erubis/engine/enhanced.rb
    Parent: Eruby

    Included Modules

    StringIOEnhancer
    ruby-erubis-2.7.0/doc-api/classes/Erubis/TinyEruby.html000066400000000000000000000337731170760342400230330ustar00rootroot00000000000000 Class: Erubis::TinyEruby
    Class Erubis::TinyEruby
    In: erubis/tiny.rb
    Parent: Object

    tiny and the simplest implementation of eRuby

    ex.

      eruby = TinyEruby.new(File.read('example.rhtml'))
      print eruby.src                 # print ruby code
      print eruby.result(binding())   # eval ruby code with Binding object
      print eruby.evalute(context)    # eval ruby code with context object
    

    Methods

    convert   evaluate   new   result  

    Constants

    EMBEDDED_PATTERN = /<%(=+|\#)?(.*?)-?%>/m

    Attributes

    src  [R] 

    Public Class methods

    [Source]

    # File erubis/tiny.rb, line 19
        def initialize(input=nil)
          @src = convert(input) if input
        end
    

    Public Instance methods

    [Source]

    # File erubis/tiny.rb, line 26
        def convert(input)
          src = "_buf = '';"           # preamble
          pos = 0
          input.scan(EMBEDDED_PATTERN) do |indicator, code|
            m = Regexp.last_match
            text = input[pos...m.begin(0)]
            pos  = m.end(0)
            #src << " _buf << '" << escape_text(text) << "';"
            text.gsub!(/['\\]/, '\\\\\&')
            src << " _buf << '" << text << "';" unless text.empty?
            if !indicator              # <% %>
              src << code << ";"
            elsif indicator == '#'     # <%# %>
              src << ("\n" * code.count("\n"))
            else                       # <%= %>
              src << " _buf << (" << code << ").to_s;"
            end
          end
          #rest = $' || input                        # ruby1.8
          rest = pos == 0 ? input : input[pos..-1]   # ruby1.9
          #src << " _buf << '" << escape_text(rest) << "';"
          rest.gsub!(/['\\]/, '\\\\\&')
          src << " _buf << '" << rest << "';" unless rest.empty?
          src << "\n_buf.to_s\n"       # postamble
          return src
        end
    

    [Source]

    # File erubis/tiny.rb, line 61
        def evaluate(_context=Object.new)
          if _context.is_a?(Hash)
            _obj = Object.new
            _context.each do |k, v| _obj.instance_variable_set("@#{k}", v) end
            _context = _obj
          end
          _context.instance_eval @src
        end
    

    def escape_text(text)

      return text.gsub!(/['\\]/, '\\\\\&') || text
    

    end

    [Source]

    # File erubis/tiny.rb, line 57
        def result(_binding=TOPLEVEL_BINDING)
          eval @src, _binding
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Erubis/XmlEruby.html000066400000000000000000000054111170760342400226340ustar00rootroot00000000000000 Class: Erubis::XmlEruby
    Class Erubis::XmlEruby
    In: erubis/engine/eruby.rb
    Parent: Eruby

    sanitize expression (<%= … %>) by default

    this is equivalent to EscapedEruby and is prepared only for compatibility.

    Included Modules

    ruby-erubis-2.7.0/doc-api/classes/Erubis/XmlHelper.html000066400000000000000000000214731170760342400227730ustar00rootroot00000000000000 Module: Erubis::XmlHelper
    Module Erubis::XmlHelper
    In: erubis/helper.rb

    helper for xml

    Methods

    escape_xml   escape_xml2   h   html_escape   u   url_encode  

    Constants

    ESCAPE_TABLE = { '&' => '&amp;', '<' => '&lt;', '>' => '&gt;', '"' => '&quot;', "'" => '&#039;', }

    Public Instance methods

    [Source]

    # File erubis/helper.rb, line 24
        def escape_xml(value)
          value.to_s.gsub(/[&<>"]/) { |s| ESCAPE_TABLE[s] }   # or /[&<>"']/
          #value.to_s.gsub(/[&<>"]/) { ESCAPE_TABLE[$&] }
        end
    

    [Source]

    # File erubis/helper.rb, line 29
        def escape_xml2(value)
          return value.to_s.gsub(/\&/,'&amp;').gsub(/</,'&lt;').gsub(/>/,'&gt;').gsub(/"/,'&quot;')
        end
    
    h(value)

    Alias for escape_xml

    html_escape(value)

    Alias for escape_xml

    u(str)

    Alias for url_encode

    [Source]

    # File erubis/helper.rb, line 36
        def url_encode(str)
          return str.gsub(/[^-_.a-zA-Z0-9]+/) { |s|
            s.unpack('C*').collect { |i| "%%%02X" % i }.join
          }
        end
    
    ruby-erubis-2.7.0/doc-api/classes/Kernel.html000066400000000000000000000107131170760342400210550ustar00rootroot00000000000000 Module: Kernel
    Module Kernel
    In: erubis/util.rb

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    Methods

    Private Instance methods

    raise NotImplementedError

    [Source]

    # File erubis/util.rb, line 11
      def not_implemented     #:doc:
        backtrace = caller()
        method_name = (backtrace.shift =~ /`(\w+)'$/) && $1
        mesg = "class #{self.class.name} must implement abstract method '#{method_name}()'."
        #mesg = "#{self.class.name}##{method_name}() is not implemented."
        err = NotImplementedError.new mesg
        err.set_backtrace backtrace
        raise err
      end
    
    ruby-erubis-2.7.0/doc-api/created.rid000066400000000000000000000000401170760342400174110ustar00rootroot00000000000000Sat, 02 Apr 2011 07:53:01 +0900 ruby-erubis-2.7.0/doc-api/files/000077500000000000000000000000001170760342400164125ustar00rootroot00000000000000ruby-erubis-2.7.0/doc-api/files/README_txt.html000066400000000000000000000132671170760342400211450ustar00rootroot00000000000000 File: README.txt

    README.txt

    Path: README.txt
    Last Update: Sat Apr 02 07:53:01 +0900 2011

    README

    release:2.7.0
    copyright:copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    About Erubis

    Erubis is an implementation of eRuby. It has the following features.

    • Very fast, almost three times faster than ERB and even 10% faster than eruby
    • Multi-language support (Ruby/PHP/C/Java/Scheme/Perl/Javascript)
    • Auto escaping support
    • Auto trimming spaces around ’<% %>’
    • Embedded pattern changeable (default ’<% %>’)
    • Enable to handle Processing Instructions (PI) as embedded pattern (ex. ’<?rb … ?>’)
    • Context object available and easy to combine eRuby template with YAML datafile
    • Print statement available
    • Easy to extend and customize in subclass
    • Ruby on Rails support

    Erubis is implemented in pure Ruby. It requires Ruby 1.8 or higher. Erubis now supports Ruby 1.9.

    See doc/users-guide.html for details.

    Installation

    • If you have installed RubyGems, just type gem install erubis.
        $ sudo gem install erubis
      
    • Else install abstract at first, and download erubis_X.X.X.tar.bz2 and install it by setup.rb.
        $ tar xjf abstract_X.X.X.tar.bz2
        $ cd abstract_X.X.X/
        $ sudo ruby setup.rb
        $ cd ..
        $ tar xjf erubis_X.X.X.tar.bz2
        $ cd erubis_X.X.X/
        $ sudo ruby setup.rb
      
    • (Optional) It is able to merge ‘lib/**/*.rb’ into ‘bin/erubis’ by ‘contrib/inline-require’ script.
        $ tar xjf erubis_X.X.X.tar.bz2
        $ cd erubis_X.X.X/
        $ cp /tmp/abstract_X.X.X/lib/abstract.rb lib
        $ unset RUBYLIB
        $ contrib/inline-require -I lib bin/erubis > contrib/erubis
      

    Ruby on Rails Support

    Erubis supports Ruby on Rails. All you have to do is to add the following code into your ‘config/environment.rb’ and restart web server.

         require 'erubis/helpers/rails_helper'
         #Erubis::Helpers::RailsHelper.engine_class = Erubis::Eruby
         #Erubis::Helpers::RailsHelper.init_properties = {}
         #Erubis::Helpers::RailsHelper.show_src = nil
    

    If Erubis::Helpers::RailsHelper.show_src is ture, Erubis prints converted Ruby code into log file (‘log/development.log’ or so). It is useful for debug.

    Exploring Guide

    If you are exploring Eruby, see the following class at first.

    • Erubis::TinyEruby (erubis/tiny.rb) — the most simple eRuby implementation.
    • Erubis::Engine (erubis/engine.rb) — base class of Eruby, Ephp, Ejava, and so on.
    • Erubis::Eruby (erubis/engine/eruby.rb) — engine class for eRuby.
    • Erubis::Converter (erubis/converter.rb) — convert eRuby script into Ruby code.

    Benchmark

    ‘benchmark/erubybenchmark.rb’ is a benchmark script of Erubis. Try ‘ruby erubybenchmark.rb’ in benchmark directory.

    License

    MIT License

    Author

    makoto kuwata <kwa(at)kuwata-lab.com>

    ruby-erubis-2.7.0/doc-api/files/erubis/000077500000000000000000000000001170760342400177035ustar00rootroot00000000000000ruby-erubis-2.7.0/doc-api/files/erubis/context_rb.html000066400000000000000000000041171170760342400227430ustar00rootroot00000000000000 File: context.rb

    context.rb

    Path: erubis/context.rb
    Last Update: Tue Jul 14 09:47:22 +0900 2009

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    ruby-erubis-2.7.0/doc-api/files/erubis/converter_rb.html000066400000000000000000000044241170760342400232670ustar00rootroot00000000000000 File: converter.rb

    converter.rb

    Path: erubis/converter.rb
    Last Update: Tue Mar 22 15:43:22 +0900 2011

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    Required files

    ruby-erubis-2.7.0/doc-api/files/erubis/engine/000077500000000000000000000000001170760342400211505ustar00rootroot00000000000000ruby-erubis-2.7.0/doc-api/files/erubis/engine/ec_rb.html000066400000000000000000000045241170760342400231150ustar00rootroot00000000000000 File: ec.rb

    ec.rb

    Path: erubis/engine/ec.rb
    Last Update: Tue Jul 14 09:47:22 +0900 2009

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    Required files

    ruby-erubis-2.7.0/doc-api/files/erubis/engine/ecpp_rb.html000066400000000000000000000045321170760342400234540ustar00rootroot00000000000000 File: ecpp.rb

    ecpp.rb

    Path: erubis/engine/ecpp.rb
    Last Update: Tue Mar 22 16:31:59 +0900 2011

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    Required files

    ruby-erubis-2.7.0/doc-api/files/erubis/engine/ejava_rb.html000066400000000000000000000045351170760342400236160ustar00rootroot00000000000000 File: ejava.rb

    ejava.rb

    Path: erubis/engine/ejava.rb
    Last Update: Mon Mar 21 20:51:19 +0900 2011

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    Required files

    ruby-erubis-2.7.0/doc-api/files/erubis/engine/ejavascript_rb.html000066400000000000000000000045571170760342400250470ustar00rootroot00000000000000 File: ejavascript.rb

    ejavascript.rb

    Path: erubis/engine/ejavascript.rb
    Last Update: Mon Mar 21 20:50:10 +0900 2011

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    Required files

    ruby-erubis-2.7.0/doc-api/files/erubis/engine/enhanced_rb.html000066400000000000000000000045501170760342400242720ustar00rootroot00000000000000 File: enhanced.rb

    enhanced.rb

    Path: erubis/engine/enhanced.rb
    Last Update: Tue Feb 22 21:00:22 +0900 2011

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    Required files

    ruby-erubis-2.7.0/doc-api/files/erubis/engine/eperl_rb.html000066400000000000000000000045351170760342400236370ustar00rootroot00000000000000 File: eperl.rb

    eperl.rb

    Path: erubis/engine/eperl.rb
    Last Update: Tue Jul 14 09:47:22 +0900 2009

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    Required files

    ruby-erubis-2.7.0/doc-api/files/erubis/engine/ephp_rb.html000066400000000000000000000045321170760342400234610ustar00rootroot00000000000000 File: ephp.rb

    ephp.rb

    Path: erubis/engine/ephp.rb
    Last Update: Tue Jul 14 09:47:22 +0900 2009

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    Required files

    ruby-erubis-2.7.0/doc-api/files/erubis/engine/eruby_rb.html000066400000000000000000000045351170760342400236560ustar00rootroot00000000000000 File: eruby.rb

    eruby.rb

    Path: erubis/engine/eruby.rb
    Last Update: Mon Mar 21 20:46:28 +0900 2011

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    Required files

    ruby-erubis-2.7.0/doc-api/files/erubis/engine/escheme_rb.html000066400000000000000000000045431170760342400241400ustar00rootroot00000000000000 File: escheme.rb

    escheme.rb

    Path: erubis/engine/escheme.rb
    Last Update: Tue Jul 14 09:47:22 +0900 2009

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    Required files

    ruby-erubis-2.7.0/doc-api/files/erubis/engine/optimized_rb.html000066400000000000000000000044471170760342400245360ustar00rootroot00000000000000 File: optimized.rb

    optimized.rb

    Path: erubis/engine/optimized.rb
    Last Update: Tue Jul 14 09:47:22 +0900 2009

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    Required files

    ruby-erubis-2.7.0/doc-api/files/erubis/engine_rb.html000066400000000000000000000047321170760342400225270ustar00rootroot00000000000000 File: engine.rb

    engine.rb

    Path: erubis/engine.rb
    Last Update: Mon Mar 21 08:26:29 +0900 2011

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    ruby-erubis-2.7.0/doc-api/files/erubis/enhancer_rb.html000066400000000000000000000041221170760342400230360ustar00rootroot00000000000000 File: enhancer.rb

    enhancer.rb

    Path: erubis/enhancer.rb
    Last Update: Mon Mar 21 20:39:56 +0900 2011

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    ruby-erubis-2.7.0/doc-api/files/erubis/error_rb.html000066400000000000000000000041111170760342400224020ustar00rootroot00000000000000 File: error.rb

    error.rb

    Path: erubis/error.rb
    Last Update: Tue Jul 14 09:47:22 +0900 2009

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    ruby-erubis-2.7.0/doc-api/files/erubis/evaluator_rb.html000066400000000000000000000045251170760342400232640ustar00rootroot00000000000000 File: evaluator.rb

    evaluator.rb

    Path: erubis/evaluator.rb
    Last Update: Tue Jul 14 09:47:22 +0900 2009

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    Required files

    ruby-erubis-2.7.0/doc-api/files/erubis/generator_rb.html000066400000000000000000000044241170760342400232460ustar00rootroot00000000000000 File: generator.rb

    generator.rb

    Path: erubis/generator.rb
    Last Update: Mon Mar 21 09:35:40 +0900 2011

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    Required files

    ruby-erubis-2.7.0/doc-api/files/erubis/helper_rb.html000066400000000000000000000041141170760342400225330ustar00rootroot00000000000000 File: helper.rb

    helper.rb

    Path: erubis/helper.rb
    Last Update: Tue Jul 14 09:47:22 +0900 2009

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    ruby-erubis-2.7.0/doc-api/files/erubis/helpers/000077500000000000000000000000001170760342400213455ustar00rootroot00000000000000ruby-erubis-2.7.0/doc-api/files/erubis/helpers/rails_form_helper_rb.html000066400000000000000000000041701170760342400264140ustar00rootroot00000000000000 File: rails_form_helper.rb

    rails_form_helper.rb

    Path: erubis/helpers/rails_form_helper.rb
    Last Update: Tue Jul 14 09:47:22 +0900 2009

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    ruby-erubis-2.7.0/doc-api/files/erubis/helpers/rails_helper_rb.html000066400000000000000000000046371170760342400254010ustar00rootroot00000000000000 File: rails_helper.rb

    rails_helper.rb

    Path: erubis/helpers/rails_helper.rb
    Last Update: Tue Jul 14 09:47:22 +0900 2009

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    Required files

    erubis   erubis/preprocessing   action_pack/version  
    ruby-erubis-2.7.0/doc-api/files/erubis/local-setting_rb.html000066400000000000000000000041411170760342400240210ustar00rootroot00000000000000 File: local-setting.rb

    local-setting.rb

    Path: erubis/local-setting.rb
    Last Update: Tue Jul 14 09:47:22 +0900 2009

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    ruby-erubis-2.7.0/doc-api/files/erubis/main_rb.html000066400000000000000000000062151170760342400222040ustar00rootroot00000000000000 File: main.rb

    main.rb

    Path: erubis/main.rb
    Last Update: Tue Mar 22 16:31:59 +0900 2011

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    ruby-erubis-2.7.0/doc-api/files/erubis/preprocessing_rb.html000066400000000000000000000043751170760342400241500ustar00rootroot00000000000000 File: preprocessing.rb

    preprocessing.rb

    Path: erubis/preprocessing.rb
    Last Update: Tue Jul 14 09:47:22 +0900 2009

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    Required files

    cgi  
    ruby-erubis-2.7.0/doc-api/files/erubis/tiny_rb.html000066400000000000000000000041061170760342400222400ustar00rootroot00000000000000 File: tiny.rb

    tiny.rb

    Path: erubis/tiny.rb
    Last Update: Tue Jul 14 09:47:22 +0900 2009

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    ruby-erubis-2.7.0/doc-api/files/erubis/util_rb.html000066400000000000000000000041061170760342400222320ustar00rootroot00000000000000 File: util.rb

    util.rb

    Path: erubis/util.rb
    Last Update: Mon Mar 21 09:32:48 +0900 2011

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    ruby-erubis-2.7.0/doc-api/files/erubis_rb.html000066400000000000000000000050721170760342400212600ustar00rootroot00000000000000 File: erubis.rb

    erubis.rb

    Path: erubis.rb
    Last Update: Mon Mar 21 09:44:53 +0900 2011

    $Release: 2.7.0 $ copyright(c) 2006-2011 kuwata-lab.com all rights reserved.

    ruby-erubis-2.7.0/doc-api/fr_class_index.html000066400000000000000000000211211170760342400211560ustar00rootroot00000000000000 Classes

    Classes

    ActionView
    ActionView::TemplateHandlers::ErubisHandler
    ERB
    Erubis
    Erubis::ArrayBufferEnhancer
    Erubis::ArrayBufferEruby
    Erubis::ArrayEnhancer
    Erubis::ArrayEruby
    Erubis::Basic
    Erubis::Basic::Converter
    Erubis::Basic::Engine
    Erubis::BiPatternEnhancer
    Erubis::BiPatternEruby
    Erubis::CGenerator
    Erubis::CommandOptionError
    Erubis::Context
    Erubis::Converter
    Erubis::CppGenerator
    Erubis::DeleteIndentEnhancer
    Erubis::DeleteIndentEruby
    Erubis::Ec
    Erubis::Ecpp
    Erubis::Ejava
    Erubis::Ejavascript
    Erubis::Engine
    Erubis::Eperl
    Erubis::Ephp
    Erubis::ErboutEnhancer
    Erubis::ErboutEruby
    Erubis::ErubisError
    Erubis::Eruby
    Erubis::EscapeEnhancer
    Erubis::EscapedEc
    Erubis::EscapedEcpp
    Erubis::EscapedEjava
    Erubis::EscapedEjavascript
    Erubis::EscapedEperl
    Erubis::EscapedEphp
    Erubis::EscapedEruby
    Erubis::EscapedEscheme
    Erubis::Escheme
    Erubis::Evaluator
    Erubis::FastEruby
    Erubis::Generator
    Erubis::HeaderFooterEnhancer
    Erubis::HeaderFooterEruby
    Erubis::Helpers
    Erubis::Helpers::RailsFormHelper
    Erubis::Helpers::RailsHelper
    Erubis::Helpers::RailsHelper::TemplateConverter
    Erubis::InterpolationEnhancer
    Erubis::InterpolationEruby
    Erubis::JavaGenerator
    Erubis::JavascriptGenerator
    Erubis::Main
    Erubis::NoCodeEnhancer
    Erubis::NoCodeEruby
    Erubis::NoTextEnhancer
    Erubis::NoTextEruby
    Erubis::NotSupportedError
    Erubis::OptimizedEruby
    Erubis::OptimizedGenerator
    Erubis::OptimizedXmlEruby
    Erubis::PI
    Erubis::PI::Converter
    Erubis::PI::Ec
    Erubis::PI::Ecpp
    Erubis::PI::Ejava
    Erubis::PI::Ejavascript
    Erubis::PI::Engine
    Erubis::PI::Eperl
    Erubis::PI::Ephp
    Erubis::PI::Eruby
    Erubis::PI::Escheme
    Erubis::PI::TinyEruby
    Erubis::PercentLineEnhancer
    Erubis::PercentLineEruby
    Erubis::PerlGenerator
    Erubis::PhpGenerator
    Erubis::PrefixedLineEnhancer
    Erubis::PrefixedLineEruby
    Erubis::PreprocessingEruby
    Erubis::PreprocessingHelper
    Erubis::PrintEnabledEnhancer
    Erubis::PrintEnabledEruby
    Erubis::PrintOutEnhancer
    Erubis::PrintOutEruby
    Erubis::PrintOutSimplifiedEruby
    Erubis::RubyEvaluator
    Erubis::RubyGenerator
    Erubis::SchemeGenerator
    Erubis::SimplifiedEruby
    Erubis::SimplifyEnhancer
    Erubis::StdoutEnhancer
    Erubis::StdoutEruby
    Erubis::StdoutSimplifiedEruby
    Erubis::StringBufferEnhancer
    Erubis::StringBufferEruby
    Erubis::StringIOEruby
    Erubis::TinyEruby
    Erubis::XmlEruby
    Erubis::XmlHelper
    Kernel
    ruby-erubis-2.7.0/doc-api/fr_file_index.html000066400000000000000000000051661170760342400210030ustar00rootroot00000000000000 Files ruby-erubis-2.7.0/doc-api/fr_method_index.html000066400000000000000000000630631170760342400213440ustar00rootroot00000000000000 Methods

    Methods

    [] (Erubis::Context)
    []= (Erubis::Context)
    _? (Erubis::PreprocessingHelper)
    _P (Erubis::PreprocessingHelper)
    _add_text_to_str (Erubis::InterpolationEnhancer)
    _create_preprocessor (Erubis::Helpers::RailsHelper::TemplateConverter)
    _decode (Erubis::PreprocessingHelper)
    _logger_info (Erubis::Helpers::RailsHelper::TemplateConverter)
    _logger_info (Erubis::Helpers::RailsHelper::TemplateConverter)
    _p (Erubis::PreprocessingHelper)
    _pp_check_box_checked? (Erubis::Helpers::RailsFormHelper)
    _pp_error_tags (Erubis::Helpers::RailsFormHelper)
    _pp_radio_button_checked? (Erubis::Helpers::RailsFormHelper)
    _pp_remove_error_div (Erubis::Helpers::RailsFormHelper)
    _pp_select (Erubis::Helpers::RailsFormHelper)
    _pp_select_options (Erubis::Helpers::RailsFormHelper)
    _preprocessing_context_object (Erubis::Helpers::RailsHelper::TemplateConverter)
    add_expr (Erubis::Basic::Converter)
    add_expr (Erubis::NoCodeEnhancer)
    add_expr (Erubis::EscapeEnhancer)
    add_expr_debug (Erubis::PhpGenerator)
    add_expr_debug (Erubis::JavascriptGenerator)
    add_expr_debug (Erubis::CGenerator)
    add_expr_debug (Erubis::OptimizedXmlEruby)
    add_expr_debug (Erubis::CppGenerator)
    add_expr_debug (Erubis::RubyGenerator)
    add_expr_debug (Erubis::JavaGenerator)
    add_expr_debug (Erubis::OptimizedGenerator)
    add_expr_debug (Erubis::PerlGenerator)
    add_expr_debug (Erubis::Generator)
    add_expr_debug (Erubis::SchemeGenerator)
    add_expr_escaped (Erubis::InterpolationEnhancer)
    add_expr_escaped (Erubis::PhpGenerator)
    add_expr_escaped (Erubis::OptimizedGenerator)
    add_expr_escaped (Erubis::SchemeGenerator)
    add_expr_escaped (Erubis::CppGenerator)
    add_expr_escaped (Erubis::JavascriptGenerator)
    add_expr_escaped (Erubis::PreprocessingEruby)
    add_expr_escaped (Erubis::JavaGenerator)
    add_expr_escaped (Erubis::PrintOutEnhancer)
    add_expr_escaped (Erubis::RubyGenerator)
    add_expr_escaped (Erubis::Generator)
    add_expr_escaped (Erubis::CGenerator)
    add_expr_escaped (Erubis::PerlGenerator)
    add_expr_literal (Erubis::SchemeGenerator)
    add_expr_literal (Erubis::JavaGenerator)
    add_expr_literal (Erubis::PrintOutEnhancer)
    add_expr_literal (Erubis::OptimizedGenerator)
    add_expr_literal (Erubis::Generator)
    add_expr_literal (Erubis::CGenerator)
    add_expr_literal (Erubis::InterpolationEnhancer)
    add_expr_literal (Erubis::PhpGenerator)
    add_expr_literal (Erubis::CppGenerator)
    add_expr_literal (Erubis::JavascriptGenerator)
    add_expr_literal (Erubis::RubyGenerator)
    add_expr_literal (Erubis::PerlGenerator)
    add_indent (Erubis::JavascriptGenerator)
    add_postamble (Erubis::ErboutEnhancer)
    add_postamble (Erubis::SchemeGenerator)
    add_postamble (Erubis::OptimizedGenerator)
    add_postamble (Erubis::JavaGenerator)
    add_postamble (Erubis::ArrayEnhancer)
    add_postamble (Erubis::CGenerator)
    add_postamble (Erubis::StdoutEnhancer)
    add_postamble (Erubis::PrintOutEnhancer)
    add_postamble (Erubis::StringBufferEnhancer)
    add_postamble (Erubis::Generator)
    add_postamble (Erubis::JavascriptGenerator)
    add_postamble (Erubis::PhpGenerator)
    add_postamble (Erubis::ArrayBufferEnhancer)
    add_postamble (Erubis::NoCodeEnhancer)
    add_postamble (Erubis::PerlGenerator)
    add_postamble (Erubis::CppGenerator)
    add_preamble (Erubis::PrintEnabledEnhancer)
    add_preamble (Erubis::JavascriptGenerator)
    add_preamble (Erubis::NoCodeEnhancer)
    add_preamble (Erubis::PhpGenerator)
    add_preamble (Erubis::ArrayBufferEnhancer)
    add_preamble (Erubis::StdoutEnhancer)
    add_preamble (Erubis::PrintOutEnhancer)
    add_preamble (Erubis::Generator)
    add_preamble (Erubis::CGenerator)
    add_preamble (Erubis::CppGenerator)
    add_preamble (Erubis::StringBufferEnhancer)
    add_preamble (Erubis::ArrayEnhancer)
    add_preamble (Erubis::JavaGenerator)
    add_preamble (Erubis::OptimizedGenerator)
    add_preamble (Erubis::PerlGenerator)
    add_preamble (Erubis::SchemeGenerator)
    add_preamble (Erubis::ErboutEnhancer)
    add_stmt (Erubis::JavaGenerator)
    add_stmt (Erubis::RubyGenerator)
    add_stmt (Erubis::SchemeGenerator)
    add_stmt (Erubis::JavascriptGenerator)
    add_stmt (Erubis::NoCodeEnhancer)
    add_stmt (Erubis::OptimizedGenerator)
    add_stmt (Erubis::PhpGenerator)
    add_stmt (Erubis::PerlGenerator)
    add_stmt (Erubis::CppGenerator)
    add_stmt (Erubis::CGenerator)
    add_stmt (Erubis::Generator)
    add_text (Erubis::CGenerator)
    add_text (Erubis::Generator)
    add_text (Erubis::InterpolationEnhancer)
    add_text (Erubis::CppGenerator)
    add_text (Erubis::PrintOutEnhancer)
    add_text (Erubis::PerlGenerator)
    add_text (Erubis::JavascriptGenerator)
    add_text (Erubis::NoTextEnhancer)
    add_text (Erubis::BiPatternEnhancer)
    add_text (Erubis::NoCodeEnhancer)
    add_text (Erubis::HeaderFooterEnhancer)
    add_text (Erubis::PhpGenerator)
    add_text (Erubis::PercentLineEnhancer)
    add_text (Erubis::SchemeGenerator)
    add_text (Erubis::PrefixedLineEnhancer)
    add_text (Erubis::RubyGenerator)
    add_text (Erubis::JavaGenerator)
    add_text (Erubis::OptimizedGenerator)
    compile (ActionView::TemplateHandlers::ErubisHandler)
    compile (ActionView::TemplateHandlers::ErubisHandler)
    compile (ActionView::TemplateHandlers::ErubisHandler)
    convert (Erubis::HeaderFooterEnhancer)
    convert (Erubis::Converter)
    convert (Erubis::SimplifyEnhancer)
    convert (Erubis::PI::TinyEruby)
    convert (Erubis::PI::Converter)
    convert (Erubis::TinyEruby)
    convert! (Erubis::Engine)
    convert_input (Erubis::Converter)
    convert_input (Erubis::Basic::Converter)
    convert_input (Erubis::InterpolationEnhancer)
    convert_input (Erubis::DeleteIndentEnhancer)
    convert_input (Erubis::PI::Converter)
    def_method (Erubis::RubyEvaluator)
    detect_spaces_at_bol (Erubis::Converter)
    each (Erubis::Context)
    engine_class (Erubis::Helpers::RailsHelper)
    engine_class= (Erubis::Helpers::RailsHelper)
    escape_text (Erubis::RubyGenerator)
    escape_text (Erubis::JavascriptGenerator)
    escape_text (Erubis::SchemeGenerator)
    escape_text (Erubis::OptimizedGenerator)
    escape_text (Erubis::PerlGenerator)
    escape_text (Erubis::Generator)
    escape_text (Erubis::JavaGenerator)
    escape_text (Erubis::CppGenerator)
    escape_text (Erubis::PhpGenerator)
    escape_text (Erubis::CGenerator)
    escape_xml (Erubis::XmlHelper)
    escape_xml2 (Erubis::XmlHelper)
    escaped_expr (Erubis::CppGenerator)
    escaped_expr (Erubis::CGenerator)
    escaped_expr (Erubis::RubyGenerator)
    escaped_expr (Erubis::Generator)
    escaped_expr (Erubis::SchemeGenerator)
    escaped_expr (Erubis::OptimizedGenerator)
    evaluate (Erubis::TinyEruby)
    evaluate (Erubis::PrintEnabledEnhancer)
    evaluate (Erubis::PI::TinyEruby)
    evaluate (Erubis::Evaluator)
    evaluate (Erubis::RubyEvaluator)
    execute (Erubis::Main)
    h (Erubis::XmlHelper)
    html_escape (Erubis::XmlHelper)
    init_converter (Erubis::PI::Ephp)
    init_converter (Erubis::PI::Converter)
    init_converter (Erubis::PI::Escheme)
    init_converter (Erubis::PI::Ecpp)
    init_converter (Erubis::PI::Ejavascript)
    init_converter (Erubis::PI::Ec)
    init_converter (Erubis::PI::Eperl)
    init_converter (Erubis::Converter)
    init_converter (Erubis::OptimizedEruby)
    init_converter (Erubis::PI::Eruby)
    init_converter (Erubis::PI::Ejava)
    init_converter (Erubis::Basic::Converter)
    init_evaluator (Erubis::Evaluator)
    init_generator (Erubis::PrefixedLineEnhancer)
    init_generator (Erubis::Generator)
    init_generator (Erubis::SchemeGenerator)
    init_generator (Erubis::JavaGenerator)
    init_generator (Erubis::CGenerator)
    init_generator (Erubis::JavascriptGenerator)
    init_generator (Erubis::RubyGenerator)
    init_generator (Erubis::CppGenerator)
    init_generator (Erubis::PhpGenerator)
    init_generator (Erubis::PerlGenerator)
    init_generator (Erubis::OptimizedGenerator)
    init_properties (Erubis::Helpers::RailsHelper)
    init_properties= (Erubis::Helpers::RailsHelper)
    keys (Erubis::Context)
    load_file (Erubis::Engine)
    main (Erubis::Main)
    new (Erubis::Main)
    new (Erubis::PreprocessingEruby)
    new (Erubis::PI::TinyEruby)
    new (Erubis::TinyEruby)
    new (Erubis::Context)
    new (Erubis::Engine)
    new (Erubis::BiPatternEnhancer)
    not_implemented (Kernel)
    pattern_regexp (Erubis::Basic::Converter)
    pp_check_box (Erubis::Helpers::RailsFormHelper)
    pp_collection_select (Erubis::Helpers::RailsFormHelper)
    pp_country_select (Erubis::Helpers::RailsFormHelper)
    pp_error_on (Erubis::Helpers::RailsFormHelper)
    pp_file_field (Erubis::Helpers::RailsFormHelper)
    pp_form_tag (Erubis::Helpers::RailsFormHelper)
    pp_hidden_field (Erubis::Helpers::RailsFormHelper)
    pp_image_submit_tag (Erubis::Helpers::RailsFormHelper)
    pp_password_field (Erubis::Helpers::RailsFormHelper)
    pp_radio_button (Erubis::Helpers::RailsFormHelper)
    pp_render_partial (Erubis::Helpers::RailsFormHelper)
    pp_select (Erubis::Helpers::RailsFormHelper)
    pp_submit_tag (Erubis::Helpers::RailsFormHelper)
    pp_tag_helper (Erubis::Helpers::RailsFormHelper)
    pp_template_filename (Erubis::Helpers::RailsFormHelper)
    pp_template_filename (Erubis::Helpers::RailsFormHelper)
    pp_text_area (Erubis::Helpers::RailsFormHelper)
    pp_text_field (Erubis::Helpers::RailsFormHelper)
    pp_time_zone_select (Erubis::Helpers::RailsFormHelper)
    preprocessing (Erubis::Helpers::RailsHelper)
    preprocessing= (Erubis::Helpers::RailsHelper)
    print (Erubis::PrintEnabledEnhancer)
    process (Erubis::Engine)
    process_proc (Erubis::Engine)
    result (Erubis::PI::TinyEruby)
    result (Erubis::Evaluator)
    result (Erubis::RubyEvaluator)
    result (Erubis::TinyEruby)
    show_src (Erubis::Helpers::RailsHelper)
    show_src= (Erubis::Helpers::RailsHelper)
    switch_to_expr (Erubis::OptimizedGenerator)
    switch_to_stmt (Erubis::OptimizedGenerator)
    to_hash (Erubis::Context)
    u (Erubis::XmlHelper)
    update (Erubis::Context)
    url_encode (Erubis::XmlHelper)
    ruby-erubis-2.7.0/doc-api/index.html000066400000000000000000000013521170760342400173060ustar00rootroot00000000000000 RDoc Documentation ruby-erubis-2.7.0/doc-api/rdoc-style.css000066400000000000000000000103321170760342400201060ustar00rootroot00000000000000 body { font-family: Verdana,Arial,Helvetica,sans-serif; font-size: 90%; margin: 0; margin-left: 40px; padding: 0; background: white; } h1,h2,h3,h4 { margin: 0; color: #efefef; background: transparent; } h1 { font-size: 150%; } h2,h3,h4 { margin-top: 1em; } a { background: #eef; color: #039; text-decoration: none; } a:hover { background: #039; color: #eef; } /* Override the base stylesheet's Anchor inside a table cell */ td > a { background: transparent; color: #039; text-decoration: none; } /* and inside a section title */ .section-title > a { background: transparent; color: #eee; text-decoration: none; } /* === Structural elements =================================== */ div#index { margin: 0; margin-left: -40px; padding: 0; font-size: 90%; } div#index a { margin-left: 0.7em; } div#index .section-bar { margin-left: 0px; padding-left: 0.7em; background: #ccc; font-size: small; } div#classHeader, div#fileHeader { width: auto; color: white; padding: 0.5em 1.5em 0.5em 1.5em; margin: 0; margin-left: -40px; border-bottom: 3px solid #006; } div#classHeader a, div#fileHeader a { background: inherit; color: white; } div#classHeader td, div#fileHeader td { background: inherit; color: white; } div#fileHeader { background: #057; } div#classHeader { background: #048; } .class-name-in-header { font-size: 180%; font-weight: bold; } div#bodyContent { padding: 0 1.5em 0 1.5em; } div#description { padding: 0.5em 1.5em; background: #efefef; border: 1px dotted #999; } div#description h1,h2,h3,h4,h5,h6 { color: #125;; background: transparent; } div#validator-badges { text-align: center; } div#validator-badges img { border: 0; } div#copyright { color: #333; background: #efefef; font: 0.75em sans-serif; margin-top: 5em; margin-bottom: 0; padding: 0.5em 2em; } /* === Classes =================================== */ table.header-table { color: white; font-size: small; } .type-note { font-size: small; color: #DEDEDE; } .xxsection-bar { background: #eee; color: #333; padding: 3px; } .section-bar { color: #333; border-bottom: 1px solid #999; margin-left: -20px; } .section-title { background: #79a; color: #eee; padding: 3px; margin-top: 2em; margin-left: -30px; border: 1px solid #999; } .top-aligned-row { vertical-align: top } .bottom-aligned-row { vertical-align: bottom } /* --- Context section classes ----------------------- */ .context-row { } .context-item-name { font-family: monospace; font-weight: bold; color: black; } .context-item-value { font-size: small; color: #448; } .context-item-desc { color: #333; padding-left: 2em; } /* --- Method classes -------------------------- */ .method-detail { background: #efefef; padding: 0; margin-top: 0.5em; margin-bottom: 1em; border: 1px dotted #ccc; } .method-heading { color: black; background: #ccc; border-bottom: 1px solid #666; padding: 0.2em 0.5em 0 0.5em; } .method-signature { color: black; background: inherit; } .method-name { font-weight: bold; } .method-args { font-style: italic; } .method-description { padding: 0 0.5em 0 0.5em; } /* --- Source code sections -------------------- */ a.source-toggle { font-size: 90%; } div.method-source-code { background: #262626; color: #ffdead; margin: 1em; padding: 0.5em; border: 1px dashed #999; overflow: hidden; } div.method-source-code pre { color: #ffdead; overflow: hidden; } /* --- Ruby keyword styles --------------------- */ .standalone-code { background: #221111; color: #ffdead; overflow: hidden; } .ruby-constant { color: #7fffd4; background: transparent; } .ruby-keyword { color: #00ffff; background: transparent; } .ruby-ivar { color: #eedd82; background: transparent; } .ruby-operator { color: #00ffee; background: transparent; } .ruby-identifier { color: #ffdead; background: transparent; } .ruby-node { color: #ffa07a; background: transparent; } .ruby-comment { color: #b22222; font-weight: bold; background: transparent; } .ruby-regexp { color: #ffa07a; background: transparent; } .ruby-value { color: #7fffd4; background: transparent; }ruby-erubis-2.7.0/doc/000077500000000000000000000000001170760342400145415ustar00rootroot00000000000000ruby-erubis-2.7.0/doc/docstyle.css000066400000000000000000000053401170760342400171030ustar00rootroot00000000000000body { background-color:#FFFFFF; } .mainbody { color:#333333; line-height:150%; margin: 5px 30px 5px 30px; } a:link, a:active, a:hover { color:#CC6600; } a:visited { color:#DD9900; } p { color:#333333; line-height:150%; } pre { width: 100%; line-height:130%; white-space:pre; } pre.program { border-style:solid; border-width:1px; border-color:#6699FF; color:#333333; background-color:#DDEEFF; padding:8px 9px 8px 9px; margin:0px; word-break:break-all; } pre.terminal { border-style:solid; border-width:1; border-color:#999999; color:#333333; background-color:#E0E0E0; padding:9px 10px 9px 10px; margin:0px; word-break:break-all; } pre.output { border-style:solid; border-width:1px; border-color:#CCCCCC; color:#333333; background-color:#FFFFFF; padding:8px 9px 8px 9px; margin:0px; word-break:break-all; } pre strong { color: #990000; font-weight: bold; } .program_caption { margin-top: 20px; } .terminal_caption { margin-top: 20px; } .output_caption { margin-top: 20px; } ul,ol,dl { /* margin:0px; */ /* padding:0px; */ color:#333333; line-height:140%; } .dt2, .dt3 { font-weight:bold; } .table1 { padding:2px; color:#333333; background-color:#DDDDCC; line-height:130%; /* border-width:1px; border-style:solid; border-color:#FFFFFF; */ margin:5; } .th1, .th2 { padding:1px; color:#333333; /* background-color:#DDDDCC; */ background-color:#CCCCBB; line-height:130%; } .td1, .th2 { padding:1px; color:#333333; background-color:#EEEEDD; line-height:130%; } .caption1, .caption2 { /* font-size:x-small; */ color:#333333; } .table2 { padding:1px; color:#333333; background-color:#DDDDCC; line-height:130%; /* border-width:1px; border-style:solid; border-color:#FFFFFF; */ margin:5; } h1, .chapter, .doctitle { color:#333333; font-weight:bold; padding:30px 0px 10px 0px; } h2, .section { color:#333333; font-weight:bold; border-style:solid; border-color:#6699FF; border-width:0px 0px 2px 30px; padding:10px 20px 0px 5px; } h3, .subsection { color:#333333; font-weight:bold; border-style:solid; border-color:#6699FF; border-width: 0px 0px 0px 15px; padding: 10px 20px 0px 5px; } .em { font-weight:bold; } .toc { /* font-size:small; */ /* line-height:100%; */ } .footnote { font-size:small; } div.note, div.tips { background-color:#FFFFDD; border-style:solid; border-width:0px 1px 0px 1px; border-color:#DDDD66; color:#333300; /* font-size:small; */ line-height:120%; margin-top: 10px; padding: 5px 20px 5px 20px; } div.note span.caption, div.tips span.caption { color: #C60; } .figure { /* border-width:1px; border-color:#DDDD66; white-space:pre; */ } strong { color: #630; font-weight; bold; } em { font-style: italic; } ruby-erubis-2.7.0/doc/users-guide.html000066400000000000000000003333571170760342400177010ustar00rootroot00000000000000 Erubis Users' Guide

    Erubis Users' Guide

    release: 2.7.0

    Preface

    Erubis is an implementation of eRuby. It has the following features.

    • Very fast, almost three times faster than ERB and about ten percent faster than eruby (implemented in C)
    • File caching of converted Ruby script support
    • Auto escaping support
    • Auto trimming spaces around '<% %>'
    • Embedded pattern changeable (default '<% %>')
    • Enable to handle Processing Instructions (PI) as embedded pattern (ex. '<?rb ... ?>')
    • Multi-language support (Ruby/PHP/C/Java/Scheme/Perl/Javascript)
    • Context object available and easy to combine eRuby template with YAML datafile
    • Print statement available
    • Easy to expand and customize in subclass
    • Ruby on Rails support
    • mod_ruby support|#topcs-modruby

    Erubis is implemented in pure Ruby. It requires Ruby 1.8 or higher. Erubis now supports Ruby 1.9.

    Table of Contents



    Installation

    • If you have installed RubyGems, just type gem install --remote erubis.
      $ sudo gem install --remote erubis
      
    • Else install abstract at first, and download erubis_X.X.X.tar.bz2 and install it by setup.rb.
      $ tar xjf abstract_X.X.X.tar.bz2
      $ cd abstract_X.X.X/
      $ sudo ruby setup.rb
      $ cd ..
      $ tar xjf erubis_X.X.X.tar.bz2
      $ cd erubis_X.X.X/
      $ sudo ruby setup.rb
      
    • (Optional) 'contrib/inline-require' enables you to merge 'lib/**/*.rb' into 'bin/erubis'.
      $ tar xjf erubis_X.X.X.tar.bz2
      $ cd erubis_X.X.X/
      $ unset RUBYLIB
      $ contrib/inline-require -I lib bin/erubis > contrib/erubis
      

    Tutorial

    Basic Example

    Here is a basic example of Erubis.

    example1.eruby
    <ul>
      <% for item in list %>
      <li><%= item %></li>
      <% end %>
      <%# here is ignored because starting with '#' %>
    </ul>
    
    example1.rb
    require 'erubis'
    input = File.read('example1.eruby')
    eruby = Erubis::Eruby.new(input)    # create Eruby object
    
    puts "---------- script source ---"
    puts eruby.src                      # print script source
    
    puts "---------- result ----------"
    list = ['aaa', 'bbb', 'ccc']
    puts eruby.result(binding())        # get result
    ## or puts eruby.result(:list=>list)  # or pass Hash instead of Binding
    
    ## # or
    ## eruby = Erubis::Eruby.new
    ## input = File.read('example1.eruby')
    ## src = eruby.convert(input)
    ## eval src
    
    output
    $ ruby example1.rb
    ---------- script source ---
    _buf = ''; _buf << '<ul>
    ';   for item in list 
     _buf << '  <li>'; _buf << ( item ).to_s; _buf << '</li>
    ';   end 
    
     _buf << '</ul>
    ';
    _buf.to_s
    ---------- result ----------
    <ul>
      <li>aaa</li>
      <li>bbb</li>
      <li>ccc</li>
    </ul>
    

    Erubis has command 'erubis'. Command-line option '-x' shows the compiled source code of eRuby script.

    example of command-line option '-x'
    $ erubis -x example1.eruby
    _buf = ''; _buf << '<ul>
    ';   for item in list 
     _buf << '  <li>'; _buf << ( item ).to_s; _buf << '</li>
    ';   end 
    
     _buf << '</ul>
    ';
    _buf.to_s
    

    Trimming Spaces

    Erubis deletes spaces around '<% %>' automatically, while it leaves spaces around '<%= %>'.

    example2.eruby
    <ul>
      <% for item in list %>      # trimmed
      <li>
        <%= item %>               # not trimmed
      </li>
      <% end %>                   # trimmed
    </ul>
    
    compiled source code
    $ erubis -x example2.eruby
    _buf = ''; _buf << '<ul>
    ';   for item in list 
     _buf << '  <li>
        '; _buf << ( item ).to_s; _buf << '
    '; _buf << '  </li>
    ';   end 
     _buf << '</ul>
    ';
    _buf.to_s
    

    If you want leave spaces around '<% %>', add command-line property '--trim=false'.

    compiled source code with command-line property '--trim=false'
    $ erubis -x --trim=false example2.eruby
    _buf = ''; _buf << '<ul>
    '; _buf << '  '; for item in list ; _buf << '
    '; _buf << '  <li>
        '; _buf << ( item ).to_s; _buf << '
    '; _buf << '  </li>
    '; _buf << '  '; end ; _buf << '
    '; _buf << '</ul>
    ';
    _buf.to_s
    

    Or add option :trim=>false to Erubis::Eruby.new().

    example2.rb
    require 'erubis'
    input = File.read('example2.eruby')
    eruby = Erubis::Eruby.new(input, :trim=>false)
    
    puts "----- script source ---"
    puts eruby.src                            # print script source
    
    puts "----- result ----------"
    list = ['aaa', 'bbb', 'ccc']
    puts eruby.result(binding())              # get result
    
    output
    $ ruby example2.rb
    ----- script source ---
    _buf = ''; _buf << '<ul>
    '; _buf << '  '; for item in list ; _buf << '
    '; _buf << '  <li>
        '; _buf << ( item ).to_s; _buf << '
    '; _buf << '  </li>
    '; _buf << '  '; end ; _buf << '
    '; _buf << '</ul>
    ';
    _buf.to_s
    ----- result ----------
    <ul>
      
      <li>
        aaa
      </li>
      
      <li>
        bbb
      </li>
      
      <li>
        ccc
      </li>
      
    </ul>
    

    Escape

    Erubis has ability to escape (sanitize) expression. Erubis::Eruby class act as the following:

    • <%= expr %> - not escaped.
    • <%== expr %> - escaped.
    • <%=== expr %> - out to $stderr.
    • <%==== expr %> - ignored.

    Erubis::EscapedEruby(*1) class handle '<%= %>' as escaped and '<%== %>' as not escaped. It means that using Erubis::EscapedEruby you can escape expression by default. Also Erubis::XmlEruby class (which is equivalent to Erubis::EscapedEruby) is provided for compatibility with Erubis 1.1.

    example3.eruby
    <% for item in list %>
      <p><%= item %></p>
      <p><%== item %></p>
      <p><%=== item %></p>
    
    <% end %>
    
    example3.rb
    require 'erubis'
    input = File.read('example3.eruby')
    eruby = Erubis::EscapedEruby.new(input)    # or Erubis::XmlEruby
    
    puts "----- script source ---"
    puts eruby.src                             # print script source
    
    puts "----- result ----------"
    list = ['<aaa>', 'b&b', '"ccc"']
    puts eruby.result(binding())               # get result
    
    output
    $ ruby example3.rb 2> stderr.log
    ----- script source ---
    _buf = ''; for item in list 
     _buf << '  <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
      <p>'; _buf << ( item ).to_s; _buf << '</p>
      <p>'; $stderr.puts("*** debug: item=#{(item).inspect}"); _buf << '</p>
    
    '; end 
    _buf.to_s
    ----- result ----------
      <p>&lt;aaa&gt;</p>
      <p><aaa></p>
      <p></p>
    
      <p>b&amp;b</p>
      <p>b&b</p>
      <p></p>
    
      <p>&quot;ccc&quot;</p>
      <p>"ccc"</p>
      <p></p>
    
    $ cat stderr.log
    *** debug: item="<aaa>"
    *** debug: item="b&b"
    *** debug: item="\"ccc\""
    

    The command-line option '-e' will do the same action as Erubis::EscapedEruby. This option is available for any language.

    $ erubis -l ruby -e example3.eruby
    _buf = ''; for item in list 
     _buf << '  <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
      <p>'; _buf << ( item ).to_s; _buf << '</p>
      <p>'; $stderr.puts("*** debug: item=#{(item).inspect}"); _buf << '</p>
    
    '; end 
    _buf.to_s
    

    Escaping function (default 'Erubis::XmlHelper.escape_xml()') can be changed by command-line property '--escapefunc=xxx' or by overriding Erubis::Eruby#escaped_expr() in subclass.

    example to override Erubis::Eruby#escaped_expr()
    class CGIEruby < Erubis::Eruby
      def escaped_expr(code)
        return "CGI.escapeHTML((#{code.strip}).to_s)"
        #return "h(#{code.strip})"
      end
    end
    
    class LatexEruby < Erubi::Eruby
      def escaped_expr(code)
        return "(#{code}).gsub(/[%\\]/,'\\\\\&')"
      end
    end
    
    (*1)
    Erubis::EscapedEruby class includes Erubis::EscapeEnhancer which swtches the action of '<%= %>' and '<%== %>'.

    Embedded Pattern

    You can change embedded pattern '<% %>' to another by command-line option '-p' or option ':pattern=>...' of Erubis::Eruby.new().

    example4.eruby
    <!--% for item in list %-->
      <p><!--%= item %--></p>
    <!--% end %-->
    
    compiled source code with command-line option '-p'
    $ erubis -x -p '<!--% %-->' example4.eruby
    _buf = ''; for item in list 
     _buf << '  <p>'; _buf << ( item ).to_s; _buf << '</p>
    '; end 
    _buf.to_s
    
    example4.rb
    require 'erubis'
    input = File.read('example4.eruby')
    eruby = Erubis::Eruby.new(input, :pattern=>'<!--% %-->')
                                          # or '<(?:!--)?% %(?:--)?>'
    
    puts "---------- script source ---"
    puts eruby.src                            # print script source
    
    puts "---------- result ----------"
    list = ['aaa', 'bbb', 'ccc']
    puts eruby.result(binding())              # get result
    
    output
    $ ruby example4.rb
    ---------- script source ---
    _buf = ''; for item in list 
     _buf << '  <p>'; _buf << ( item ).to_s; _buf << '</p>
    '; end 
    _buf.to_s
    ---------- result ----------
      <p>aaa</p>
      <p>bbb</p>
      <p>ccc</p>
    

    It is able to specify regular expression with :pattern option. Notice that you must use '(?: )' instead of '( )' for grouping. For example, '<(!--)?% %(--)?>' will not work while '<(?:!--)?% %(?:--)?>' will work.


    Context Object

    Context object is a set of data which are used in eRuby script. Using context object makes clear which data to be used. In Erubis, Hash object and Erubis::Context object are available as context object.

    Context data can be accessible via instance variables in eRuby script.

    example5.eruby
    <span><%= @val %></span>
    <ul>
     <% for item in @list %>
      <li><%= item %></li>
     <% end %>
    </ul>
    
    example5.rb
    require 'erubis'
    input = File.read('example5.eruby')
    eruby = Erubis::Eruby.new(input)      # create Eruby object
    
    ## create context object
    ## (key means var name, which may be string or symbol.)
    context = {
      :val   => 'Erubis Example',
      'list' => ['aaa', 'bbb', 'ccc'],
    }
    ## or
    # context = Erubis::Context.new()
    # context['val'] = 'Erubis Example'
    # context[:list] = ['aaa', 'bbb', 'ccc'],
    
    puts eruby.evaluate(context)         # get result
    
    output
    $ ruby example5.rb
    <span>Erubis Example</span>
    <ul>
      <li>aaa</li>
      <li>bbb</li>
      <li>ccc</li>
    </ul>
    

    The difference between Erubis#result(binding) and Erubis#evaluate(context) is that the former invokes 'eval @src, binding' and the latter invokes 'context.instance_eval @src'. This means that data is passed into eRuby script via local variables when Eruby::binding() is called, or passed via instance variables when Eruby::evaluate() is called.

    Here is the definition of Erubis#result() and Erubis#evaluate().

    definition of result(binding) and evaluate(context)
    def result(_binding=TOPLEVEL_BINDING)
      if _binding.is_a?(Hash)
        # load hash data as local variable
        _h = _binding
        _binding = binding()
        eval _h.collect{|k,v| "#{k} = _h[#{k.inspect}];"}.join, _binding
      end
      return eval(@src, _binding)
    end
    
    def evaluate(_context=Erubis::Context.new)
      if _context.is_a?(Hash)
        # convert hash object to Context object
        _hash = _context
        _context = Erubis::Context.new
        _hash.each {|k, v| _context[k] = v }
      end
      return _context.instance_eval(@src)
    end
    

    instance_eval() is defined at Object class so it is able to use any object as a context object as well as Hash or Erubis::Context.

    example6.rb
    class MyData
      attr_accessor :val, :list
    end
    
    ## any object can be a context object
    mydata = MyData.new
    mydata.val = 'Erubis Example'
    mydata.list = ['aaa', 'bbb', 'ccc']
    
    require 'erubis'
    eruby = Erubis::Eruby.new(File.read('example5.eruby'))
    puts eruby.evaluate(mydata)
    
    output
    $ ruby example6.rb
    <span>Erubis Example</span>
    <ul>
      <li>aaa</li>
      <li>bbb</li>
      <li>ccc</li>
    </ul>
    

    It is recommended to use 'Erubis::Eruby#evaluate(context)' rather than 'Erubis::Eruby#result(binding())' because the latter has some problems. See evaluate(context) v.s. result(binding) section for details.


    Context Data File

    Command-line option '-f' specifies context data file. Erubis load context data file and use it as context data. Context data file can be YAML file ('*.yaml' or '*.yml') or Ruby script ('*.rb').

    example7.eruby
    <h1><%= @title %></h1>
    <ul>
     <% for user in @users %>
      <li>
        <a href="mailto:<%= user['mail']%>"><%= user['name'] %></a>
      </li>
     <% end %>
    </ul>
    
    context.yaml
    title: Users List
    users:
      - name:  foo
        mail:  foo@mail.com
      - name:  bar
        mail:  bar@mail.net
      - name:  baz
        mail:  baz@mail.org
    
    context.rb
    @title = 'Users List'
    @users = [
       { 'name'=>'foo', 'mail'=>'foo@mail.com' },
       { 'name'=>'bar', 'mail'=>'bar@mail.net' },
       { 'name'=>'baz', 'mail'=>'baz@mail.org' },
    ]
    
    example of command-line option '-f'
    $ erubis -f context.yaml example7.eruby
    <h1>Users List</h1>
    <ul>
      <li>
        <a href="mailto:foo@mail.com">foo</a>
      </li>
      <li>
        <a href="mailto:bar@mail.net">bar</a>
      </li>
      <li>
        <a href="mailto:baz@mail.org">baz</a>
      </li>
    </ul>
    $ erubis -f context.rb example7.eruby
    <h1>Users List</h1>
    <ul>
      <li>
        <a href="mailto:foo@mail.com">foo</a>
      </li>
      <li>
        <a href="mailto:bar@mail.net">bar</a>
      </li>
      <li>
        <a href="mailto:baz@mail.org">baz</a>
      </li>
    </ul>
    

    Command-line option '-S' converts keys of mapping in YAML data file from string into symbol. Command-line option '-B' invokes 'Erubis::Eruby#result(binding())' instead of 'Erubis::Eruby#evaluate(context)'.


    Context Data String

    Command-line option '-c str' enables you to specify context data in command-line. str can be YAML flow-style or Ruby code.

    example8.eruby
    <h1><%= @title %></h1>
    <ul>
    <% for item in @list %>
     <li><%= item %></li>
    <% end %>
    </ul>
    
    example of YAML flow style
    $ erubis -c '{title: Example, list: [AAA, BBB, CCC]}' example8.eruby
    <h1>Example</h1>
    <ul>
     <li>AAA</li>
     <li>BBB</li>
     <li>CCC</li>
    </ul>
    
    example of Ruby code
    $ erubis -c '@title="Example"; @list=%w[AAA BBB CCC]' example8.eruby
    <h1>Example</h1>
    <ul>
     <li>AAA</li>
     <li>BBB</li>
     <li>CCC</li>
    </ul>
    

    Preamble and Postamble

    The first line ('_buf = '';') in the compiled source code is called preamble and the last line ('_buf.to_s') is called postamble.

    Command-line option '-b' skips the output of preamble and postamble.

    example9.eruby
    <% for item in @list %>
     <b><%= item %></b>
    <% end %>
    
    compiled source code with and without command-line option '-b'
    $ erubis -x example9.eruby
    _buf = ''; for item in @list 
     _buf << ' <b>'; _buf << ( item ).to_s; _buf << '</b>
    '; end 
    _buf.to_s
    $ erubis -x -b example9.eruby
     for item in @list 
     _buf << ' <b>'; _buf << ( item ).to_s; _buf << '</b>
    '; end 
    

    Erubis::Eruby.new option ':preamble=>false' and ':postamble=>false' also suppress output of preamble or postamle.

    example9.rb
    require 'erubis'
    input = File.read('example9.eruby')
    eruby1 = Erubis::Eruby.new(input)
    eruby2 = Erubis::Eruby.new(input, :preamble=>false, :postamble=>false)
    
    puts eruby1.src   # print preamble and postamble
    puts "--------------"
    puts eruby2.src   # don't print preamble and postamble
    
    output
    $ ruby example9.rb
    _buf = ''; for item in @list 
     _buf << ' <b>'; _buf << ( item ).to_s; _buf << '</b>
    '; end 
    _buf.to_s
    --------------
     for item in @list 
     _buf << ' <b>'; _buf << ( item ).to_s; _buf << '</b>
    '; end 
    

    Processing Instruction (PI) Converter

    Erubis can parse Processing Instructions (PI) as embedded pattern.

    • '<?rb ... ?>' represents Ruby statement.
    • '@{...}@' represents escaped expression value.
    • '@!{...}@' represents normal expression value.
    • '@!!{...}@' prints expression value to standard output.
    • (experimental) '<%= ... %>' is also available to print expression value.

    This is more useful than basic embedded pattern ('<% ... >') because PI doesn't break XML or HTML at all. For example the following XHTML file is well-formed and HTML validator got no errors on this example.

    example10.xhtml
    <?xml version="1.0" ?>
    <?rb
      lang = 'en'
      list = ['<aaa>', 'b&b', '"ccc"']
    ?>
    <html lang="@!{lang}@">
     <body>
      <ul>
      <?rb for item in list ?>
       <li>@{item}@</li>
      <?rb end ?>
      </ul>
     </body>
    </html>
    

    If the command-line property '--pi=name' is specified, erubis command parses input with PI converter. If name is omitted then the following name is used according to '-l lang'.

    '-l' option PI name
    -l ruby <?rb ... ?>
    -l php <?php ... ?>
    -l perl <?perl ... ?>
    -l java <?java ... ?>
    -l javascript <?js ... ?>
    -l scheme <?scheme ... ?>
    output
    $ erubis -x --pi example10.xhtml
    _buf = ''; _buf << '<?xml version="1.0" ?>
    ';
      lang = 'en'
      list = ['<aaa>', 'b&b', '"ccc"']
    
     _buf << '<html lang="'; _buf << (lang).to_s; _buf << '">
     <body>
      <ul>
    ';   for item in list 
     _buf << '   <li>'; _buf << Erubis::XmlHelper.escape_xml(item); _buf << '</li>
    ';   end 
     _buf << '  </ul>
     </body>
    </html>
    ';
    _buf.to_s
    

    Expression character can be changeable by command-line property '--embchar=char. Default is '@'.

    Use Erubis::PI::Eruby instead of Erubis::Eruby if you want to use PI as embedded pattern.

    example10.rb
    require 'erubis'
    input = File.read('example10.xhtml')
    eruby = Erubis::PI::Eruby.new(input)
    print eruby.src
    
    output
    $ ruby example10.rb
    _buf = ''; _buf << '<?xml version="1.0" ?>
    ';
      lang = 'en'
      list = ['<aaa>', 'b&b', '"ccc"']
    
     _buf << '<html lang="'; _buf << (lang).to_s; _buf << '">
     <body>
      <ul>
    ';   for item in list 
     _buf << '   <li>'; _buf << Erubis::XmlHelper.escape_xml(item); _buf << '</li>
    ';   end 
     _buf << '  </ul>
     </body>
    </html>
    ';
    _buf.to_s
    

    (experimental) Erubis supports '<%= ... %>' pattern with PI pattern.

    example of Rails view template
    <table>
      <tr>
    <?rb for item in @list ?>
        <td>@{item.id}@</td>
        <td>@{item.name}@</td>
        <td>
           <%= link_to 'Destroy', {:action=>'destroy', :id=>item.id},
                           :confirm=>'Are you OK?' %>
        </td>
    <?rb end ?>
      </tr>
    </table>
    

    Retrieve Ruby Code

    Similar to '-x', ommand-line option '-X' shows converted Ruby source code. The difference between '-x' and 'X' is that the former converts text part but the latter ignores it. It means that you can retrieve Ruby code from eRuby script by '-X' option.

    For example, see the following eRuby script. This is some complex, so it is difficult to grasp the program code.

    example11.rhtml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
              "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
      <body>
        <h3>List</h3>
        <% if @list.nil? || @list.empty? %>
        <p>not found.</p>
        <% else %>
        <table>
          <tbody>
            <% @list.each_with_index do |item, i| %>
            <tr bgcolor="<%= i % 2 == 0 ? '#FCC' : '#CCF' %>">
              <td><%= item %></td>
            </tr>
            <% end %>
          </tbody>
        </table>
        <% end %>
      </body>
    </html>
    

    Command-line option '-X' extracts only the ruby code from eRuby script.

    result
    $ erubis -X example11.rhtml
    _buf = '';
    
    
    
    
    
         if @list.nil? || @list.empty? 
    
         else 
    
    
             @list.each_with_index do |item, i| 
                          _buf << ( i % 2 == 0 ? '#FCC' : '#CCF' ).to_s;
                   _buf << ( item ).to_s;
    
             end 
    
    
         end 
    
    
    _buf.to_s
    

    Command-line option '-C' (cmpact) deletes empty lines.

    result
    $ erubis -XC example11.rhtml
    _buf = '';
         if @list.nil? || @list.empty? 
         else 
             @list.each_with_index do |item, i| 
                          _buf << ( i % 2 == 0 ? '#FCC' : '#CCF' ).to_s;
                   _buf << ( item ).to_s;
             end 
         end 
    _buf.to_s
    

    Option '-U' (unique) converts empty lines into a line.

    result
    $ erubis -XU example11.rhtml
    _buf = '';
    
         if @list.nil? || @list.empty? 
    
         else 
    
             @list.each_with_index do |item, i| 
                          _buf << ( i % 2 == 0 ? '#FCC' : '#CCF' ).to_s;
                   _buf << ( item ).to_s;
    
             end 
    
         end 
    
    _buf.to_s
    

    Option '-N' (number) adds line number. It is available with '-C' or '-U'.

    result
    $ erubis -XNU example11.rhtml
        1:  _buf = '';
    
        7:       if @list.nil? || @list.empty? 
    
        9:       else 
    
       12:           @list.each_with_index do |item, i| 
       13:                        _buf << ( i % 2 == 0 ? '#FCC' : '#CCF' ).to_s;
       14:                 _buf << ( item ).to_s;
    
       16:           end 
    
       19:       end 
    
       22:  _buf.to_s
    

    Command-line option '-X' is available with PHP script.

    example11.php
    <?xml version="1.0"?>
    <html>
      <body>
        <h3>List</h3>
        <?php if (!$list) { ?>
        <p>not found.</p>
        <?php } else { ?>
        <table>
          <tbody>
            <?php $i = 0; ?>
            <?php foreach ($list as $item) { ?>
            <tr bgcolor="<?php echo ++$i % 2 == 1 ? '#FCC' : '#CCF'; ?>">
              <td><?php echo $item; ?></td>
            </tr>
            <?php } ?>
          </tbody>
        </table>
        <?php } ?>
      </body>
    </html>
    
    result
    $ erubis -XNU -l php --pi=php --trim=false example11.php
    
        5:      <?php if (!$list) { ?>
    
        7:      <?php } else { ?>
    
       10:          <?php $i = 0; ?>
       11:          <?php foreach ($list as $item) { ?>
       12:                       <?php echo ++$i % 2 == 1 ? '#FCC' : '#CCF'; ?>
       13:                <?php echo $item; ?>
    
       15:          <?php } ?>
    
       18:      <?php } ?>
    
    


    Enhancer

    Enhancer is a module to add a certain feature into Erubis::Eruby class. Enhancer may be language-independent or only for Erubis::Eruby class.

    To use enhancers, define subclass and include them. The folloing is an example to use EscapeEnhancer, PercentLineEnhancer, and BiPatternEnhancer.

    class MyEruby < Erubis::Eruby
      include EscapeEnhancer
      include PercentLineEnhancer
      include BiPatternEnhancer
    end
    

    You can specify enhancers in command-line with option '-E'. The following is an example to use some enhancers in command-line.

    $ erubis -xE Escape,PercentLine,BiPattern example.eruby
    

    The following is the list of enhancers.

    EscapeEnhander (language-independent)
    Switch '<%= %>' to escaped and '<%== %>' to unescaped.
    StdoutEnhancer (only for Eruby)
    Use $stdout instead of array buffer.
    PrintOutEnhancer (only for Eruby)
    Use "print(...)" statement insead of "_buf << ...".
    PrintEnabledEnhancer (only for Eruby)
    Enable to use print() in '<% ... %>'.
    ArrayEnhancer (only for Eruby)
    Return array of string instead of returning string.
    ArrayBufferEnhancer (only for Eruby)
    Use array buffer. It is a little slower than StringBufferEnhancer.
    StringBufferEnhancer (only for Eruby)
    Use string buffer. This is included in Erubis::Eruby by default.
    ErboutEnhancer (only for Eruby)
    Set '_erbout = _buf = "";' to be compatible with ERB.
    NoTextEnhancer (language-independent)
    Print embedded code only and ignore normal text.
    NoCodeEnhancer (language-independent)
    Print normal text only and ignore code.
    SimplifyEnhancer (language-independent)
    Make compile faster but don't trim spaces around '<% %>'.
    BiPatternEnhancer (language-independent)
    [experimental] Enable to use another embedded pattern with '<% %>'.
    PercentLineEnhancer (language-independent)
    Regard lines starting with '%' as Ruby code. This is for compatibility with eruby and ERB.
    HeaderFooterEnhancer (language-independent)
    [experimental] Enable you to add header and footer in eRuby script.
    InterpolationEnhancer (only for Eruby)
    [experimental] convert '<p><%= text %></p>' into '_buf << %Q`<p>#{text}</p>`'.
    DeleteIndentEnhancer (language-independent)
    [experimental] delete indentation of HTML file and eliminate page size.

    If you required 'erubis/engine/enhanced', Eruby subclasses which include each enhancers are defined. For example, class BiPatternEruby includes BiPatternEnhancer.

    EscapeEnhancer

    EscapeEnhancer switches '<%= ... %>' to escaped and '<%== ... %>' to unescaped.

    example.eruby
    <div>
    <% for item in list %>
      <p><%= item %></p>
      <p><%== item %></p>
    <% end %>
    </div>
    
    compiled source code
    $ erubis -xE Escape example.eruby
    _buf = ''; _buf << '<div>
    '; for item in list 
     _buf << '  <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
      <p>'; _buf << ( item ).to_s; _buf << '</p>
    '; end 
     _buf << '</div>
    ';
    _buf.to_s
    

    EscapeEnhancer is language-independent.


    StdoutEnhancer

    StdoutEnhancer use $sdtdout instead of array buffer. Therefore, you can use 'print' statement in embedded ruby code.

    compiled source code
    $ erubis -xE Stdout example.eruby
    _buf = $stdout; _buf << '<div>
    '; for item in list 
     _buf << '  <p>'; _buf << ( item ).to_s; _buf << '</p>
      <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
    '; end 
     _buf << '</div>
    ';
    ''
    

    StdoutEnhancer is only for Eruby.


    PrintOutEnhancer

    PrintOutEnhancer makes compiled source code to use 'print(...)' instead of '_buf << ...'.

    compiled source code
    $ erubis -xE PrintOut example.eruby
     print '<div>
    '; for item in list 
     print '  <p>'; print(( item ).to_s); print '</p>
      <p>'; print Erubis::XmlHelper.escape_xml( item ); print '</p>
    '; end 
     print '</div>
    ';
    

    PrintOutEnhancer is only for Eruby.


    PrintEnabledEnhancer

    PrintEnabledEnhancer enables you to use print() method in '<% ... %>'.

    printenabled-example.eruby
    <% for item in @list %>
      <b><% print item %></b>
    <% end %>
    
    printenabled-example.rb
    require 'erubis'
    class PrintEnabledEruby < Erubis::Eruby
      include Erubis::PrintEnabledEnhancer
    end
    input = File.read('printenabled-example.eruby')
    eruby = PrintEnabledEruby.new(input)
    list = ['aaa', 'bbb', 'ccc']
    print eruby.evaluate(:list=>list)
    
    output result
    $ ruby printenabled-example.rb
      <b>aaa</b>
      <b>bbb</b>
      <b>ccc</b>
    

    Notice to use Eruby#evaluate() and not to use Eruby#result(), because print() method in '<% ... %>' invokes not Kernel#print() but PrintEnabledEnhancer#print().

    PrintEnabledEnhancer is only for Eruby.


    ArrayEnhancer

    ArrayEnhancer makes Eruby to return an array of strings.

    compiled source code
    $ erubis -xE Array example.eruby
    _buf = []; _buf << '<div>
    '; for item in list 
     _buf << '  <p>'; _buf << ( item ).to_s; _buf << '</p>
      <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
    '; end 
     _buf << '</div>
    ';
    _buf
    

    ArrayEnhancer is only for Eruby.


    ArrayBufferEnhancer

    ArrayBufferEnhancer makes Eruby to use array buffer. Array buffer is a litte slower than String buffer.

    ArrayBufferEnhancer is only for Eruby.

    compiled source code
    $ erubis -xE ArrayBuffer example.eruby
    _buf = []; _buf << '<div>
    '; for item in list 
     _buf << '  <p>'; _buf << ( item ).to_s; _buf << '</p>
      <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
    '; end 
     _buf << '</div>
    ';
    _buf.join
    

    StringBufferEnhancer

    StringBufferEnhancer makes Eruby to use string buffer. String buffer is a little faster than array buffer. Erubis::Eruby includes this enhancer by default.

    compiled source code
    $ erubis -xE StringBuffer example.eruby
    _buf = ''; _buf << '<div>
    '; for item in list 
     _buf << '  <p>'; _buf << ( item ).to_s; _buf << '</p>
      <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
    '; end 
     _buf << '</div>
    ';
    _buf.to_s
    

    StringBufferEnhancer is only for Eruby.


    ErboutEnhancer

    ErboutEnhancer makes Eruby to be compatible with ERB. This is useful especially for Ruby on Rails.

    compiled source code
    $ erubis -xE Erbout example.eruby
    _erbout = _buf = ''; _buf << '<div>
    '; for item in list 
     _buf << '  <p>'; _buf << ( item ).to_s; _buf << '</p>
      <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
    '; end 
     _buf << '</div>
    ';
    _buf.to_s
    

    ErboutEnhancer is only for Eruby.


    NoTextEnhancer

    NoTextEnhancer suppress output of text and prints only embedded code. This is useful especially when debugging a complex eRuby script.

    notext-example.eruby
    <h3>List</h3>
    <% if !@list || @list.empty? %>
    <p>not found.</p>
    <% else %>
    <table>
      <tbody>
        <% @list.each_with_index do |item, i| %>
        <tr bgcolor="<%= i%2 == 0 ? '#FFCCCC' : '#CCCCFF' %>">
          <td><%= item %></td>
        </tr>
        <% end %>
      </tbody>
    </table>
    <% end %>
    
    output example of NoTextEnhancer
    $ erubis -xE NoText notext-example.eruby
    _buf = '';
     if !@list || @list.empty? 
    
     else 
    
    
         @list.each_with_index do |item, i| 
                      _buf << ( i%2 == 0 ? '#FFCCCC' : '#CCCCFF' ).to_s;
               _buf << ( item ).to_s;
    
         end 
    
    
     end 
    _buf.to_s
    

    NoTextEnhancer is language-independent. It is useful even if you are PHP user, see this section.


    NoCodeEnhancer

    NoCodeEnhancer suppress output of embedded code and prints only normal text. This is useful especially when validating HTML tags.

    nocode-example.eruby
    <h3>List</h3>
    <% if !@list || @list.empty? %>
    <p>not found.</p>
    <% else %>
    <table>
      <tbody>
        <% @list.each_with_index do |item, i| %>
        <tr bgcolor="<%= i%2 == 0 ? '#FFCCCC' : '#CCCCFF' %>">
          <td><%= item %></td>
        </tr>
        <% end %>
      </tbody>
    </table>
    <% end %>
    
    output example of NoCodeEnhancer
    $ erubis -xE NoCode notext-example.eruby
    <h3>List</h3>
    
    <p>not found.</p>
    
    <table>
      <tbody>
    
        <tr bgcolor="">
          <td></td>
        </tr>
    
      </tbody>
    </table>
    
    

    NoCodeEnhancer is language-independent. It is useful even if you are PHP user, see this section.


    SimplifyEnhancer

    SimplifyEnhancer makes compiling a little faster but don't trim spaces around '<% %>'.

    compiled source code
    $ erubis -xE Simplify example.eruby
    _buf = ''; _buf << '<div>
    '; for item in list ; _buf << '
      <p>'; _buf << ( item ).to_s; _buf << '</p>
      <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
    '; end ; _buf << '
    </div>
    ';
    _buf.to_s
    

    SimplifyEnhancer is language-independent.


    BiPatternEnhancer

    BiPatternEnhancer enables to use another embedded pattern with '<% %>'. By Default, '[= ... =]' is available for expression. You can specify pattern by :bipattern property.

    bipattern-example.rhtml
    <% for item in list %>
      <b>[= item =]</b>
      <b>[== item =]</b>
    <% end %>
    
    compiled source code
    $ erubis -xE BiPattern bipattern-example.rhtml
    _buf = ''; for item in list 
     _buf << '  <b>'; _buf << ( item ).to_s; _buf << '</b>
      <b>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</b>
    '; end 
    _buf.to_s
    

    BiPatternEnhancer is language-independent.


    PercentLineEnhancer

    PercentLineEnhancer regards lines starting with '%' as Ruby code. This is for compatibility with eruby and ERB.

    percentline-example.rhtml
    <ul>
    % for item in list
      <li><%= item %></li>
    % end
    </ul>
    %% lines with '%%'
    
    compiled source code
    $ erubis -xE PercentLine percentline-example.rhtml
    _buf = ''; _buf << '<ul>
    '; for item in list
     _buf << '  <li>'; _buf << ( item ).to_s; _buf << '</li>
    '; end
     _buf << '</ul>
    % lines with \'%%\'
    ';
    _buf.to_s
    

    PercentLineEnhancer is language-independent.


    PrefixedLineEnhancer

    PrefixedlineEnhancer regards lines starting with '%' as Ruby code. It is similar to PercentLineEnhancer, but there are some differences.

    • PrefixedlineEnhancer allows to indent lines starting with '%', but PercentLineEnhancer doesn't.
    • PrefixedlineEnhancer allows to change prefixed character (default '%'), but PercentLineEnhancer doesn't.
    prefixedline-example.rhtml
    <ul>
      ! for item in list
      <li><%= item %></li>
      ! end
    </ul>
      !! lines with '!!'
    
    prefixedline-example.rb
    require 'erubis'
    
    class PrefixedLineEruby < Erubis::Eruby
      include Erubis::PrefixedLineEnhancer
    end
    
    input = File.read('prefixedline-example.rhtml')
    eruby = PrefixedLineEruby.new(input, :prefixchar=>'!')  # default '%'
    print eruby.src
    
    compiled source code
    $ ruby prefixedline-example.rb
    _buf = ''; _buf << '<ul>
    ';   for item in list
     _buf << '  <li>'; _buf << ( item ).to_s; _buf << '</li>
    ';   end
     _buf << '</ul>
      ! lines with \'!!\'
    ';
    _buf.to_s
    

    PrefixedLineEnhancer is language-independent.


    HeaderFooterEnhancer

    [experimental]

    HeaderFooterEnhancer enables you to add header and footer in eRuby script.

    headerfooter-example.eruby
    <!--#header:
    def list_items(items)
    #-->
    <% for item in items %>
      <b><%= item %></b>
    <% end %>
    <!--#footer:
    end
    #-->
    
    compiled source code
    $ erubis -xE HeaderFooter headerfooter-example.eruby
    
    def list_items(items)
    
    _buf = ''; for item in items 
     _buf << '  <b>'; _buf << ( item ).to_s; _buf << '</b>
    '; end 
    _buf.to_s
    
    end
    
    

    Compare to the following:

    normal-eruby-test.eruby
    <%
    def list_items(items)
    %>
    <% for item in items %>
    <li><%= item %></li>
    <% end %>
    <%
    end
    %>
    
    compiled source code
    $ erubis -x normal-eruby-test.eruby
    _buf = '';
    def list_items(items)
    
     for item in items 
     _buf << '<li>'; _buf << ( item ).to_s; _buf << '</li>
    '; end 
    
    end
    
    _buf.to_s
    

    Header and footer can be in any position in eRuby script, that is, header is no need to be in the head of eRuby script.

    headerfooter-example2.rhtml
    <?xml version="1.0"?>
    <html>
    <!--#header:
    def page(list)
    #-->
     :
    <!--#footer:
    end
    #-->
    </html>
    
    compiled source code
    $ erubis -xE HeaderFooter headerfooter-example2.rhtml
    
    def page(list)
    
    _buf = ''; _buf << '<?xml version="1.0"?>
    <html>
    '; _buf << ' :
    '; _buf << '</html>
    ';
    _buf.to_s
    
    end
    
    

    HeaderFooterEnhancer is experimental and is language-independent.


    InterpolationEnhancer

    [experimental]

    InterpolationEnhancer converts "<h1><%= title %></h1>" into "_buf << %Q`<h1>#{ title }</h1>`". This makes Eruby a litter faster because method call of String#<< are eliminated by expression interpolations.

    InterpolationEnhancer elmininates method call of String#<<.
    ## Assume that input is '<a href="<%=url%>"><%=name%></a>'.
    ## Eruby convert input into the following code.  String#<< is called 5 times.
    _buf << '<a href="'; _buf << (url).to_s; _buf << '">'; _buf << (name).to_s; _buf << '</a>';
    
    ## If InterpolationEnhancer is used, String#<< is called only once.
    _buf << %Q`<a href="#{url}">#{name}</a>`;
    
    compiled source code
    $ erubis -xE Interpolation example.eruby
    _buf = ''; _buf << %Q`<div>\n`
     for item in list 
     _buf << %Q`  <p>#{ item }</p>
      <p>#{Erubis::XmlHelper.escape_xml( item )}</p>\n`
     end 
     _buf << %Q`</div>\n`
    _buf.to_s
    

    Erubis provides Erubis::FastEruby class which includes InterpolationEnhancer. You can use Erubis::FastEruby class instead of Erubis::Eruby class.

    InterpolationEnhancer is only for Eruby.


    DeleteIndentEnhancer

    [experimental] DeleteIndentEnhancer deletes indentation of HTML file.

    compiled source code
    $ erubis -xE DeleteIndent example.eruby
    _buf = ''; _buf << '<div>
    '; for item in list 
     _buf << '<p>'; _buf << ( item ).to_s; _buf << '</p>
    <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
    '; end 
     _buf << '</div>
    ';
    _buf.to_s
    

    Notice that DeleteIndentEnhancer isn't intelligent. It deletes indentations even if they are in <PRE></PRE>.

    DeleteIndentEnhancer is language-independent.



    Multi-Language Support

    Erubis supports the following languages(*2):

    (*2)
    If you need template engine in pure PHP/Perl/JavaScript, try Tenjin (http://www.kuwata-lab.com/tenjin/). Tenjin is a very fast and full-featured template engine implemented in pure PHP/Perl/JavaScript.

    PHP

    example.ephp
    <?xml version="1.0"?>
    <html>
     <body>
      <p>Hello <%= $user %>!</p>
      <table>
       <tbody>
        <% $i = 0; %>
        <% foreach ($list as $item) { %>
        <%   $i++; %>
        <tr bgcolor="<%= $i % 2 == 0 ? '#FFCCCC' : '#CCCCFF' %>">
         <td><%= $i %></td>
         <td><%== $item %></td>
        </tr>
        <% } %>
       </tbody>
      </table>
     </body>
    </html>
    
    compiled source code
    $ erubis -l php example.ephp
    <<?php ?>?xml version="1.0"?>
    <html>
     <body>
      <p>Hello <?php echo $user; ?>!</p>
      <table>
       <tbody>
    <?php     $i = 0; ?>
    <?php     foreach ($list as $item) { ?>
    <?php       $i++; ?>
        <tr bgcolor="<?php echo $i % 2 == 0 ? '#FFCCCC' : '#CCCCFF'; ?>">
         <td><?php echo $i; ?></td>
         <td><?php echo htmlspecialchars($item); ?></td>
        </tr>
    <?php     } ?>
       </tbody>
      </table>
     </body>
    </html>
    

    C

    example.ec
    <%
    #include <stdio.h>
    
    int main(int argc, char *argv[])
    {
        int i;
    
    %>
    <html>
     <body>
      <p>Hello <%= "%s", argv[0] %>!</p>
      <table>
       <tbody>
        <% for (i = 1; i < argc; i++) { %>
        <tr bgcolor="<%= i % 2 == 0 ? "#FFCCCC" : "#CCCCFF" %>">
          <td><%= "%d", i %></td>
          <td><%= "%s", argv[i] %></td>
        </tr>
        <% } %>
       </tbody>
      </table>
     </body>
    </html>
    <%
        return 0; 
    }
    %>
    
    compiled source code
    $ erubis -l c example.ec
    #line 1 "example.ec"
    
    #include <stdio.h>
    
    int main(int argc, char *argv[])
    {
        int i;
    
    
    fputs("<html>\n"
          " <body>\n"
          "  <p>Hello ", stdout); fprintf(stdout, "%s", argv[0]); fputs("!</p>\n"
          "  <table>\n"
          "   <tbody>\n", stdout);
         for (i = 1; i < argc; i++) { 
    fputs("    <tr bgcolor=\"", stdout); fprintf(stdout, i % 2 == 0 ? "#FFCCCC" : "#CCCCFF"); fputs("\">\n"
          "      <td>", stdout); fprintf(stdout, "%d", i); fputs("</td>\n"
          "      <td>", stdout); fprintf(stdout, "%s", argv[i]); fputs("</td>\n"
          "    </tr>\n", stdout);
         } 
    fputs("   </tbody>\n"
          "  </table>\n"
          " </body>\n"
          "</html>\n", stdout);
    
        return 0; 
    }
    
    

    C++

    example.ecpp
    <%
    #include <string>
    #include <iostream>
    #include <sstream>
    
    int main(int argc, char *argv[])
    {
        std::stringstream _buf;
    %>
    <html>
     <body>
      <p>Hello <%= argv[0] %>!</p>
      <table>
       <tbody>
        <% for (int i = 1; i < argc; i++) { %>
        <tr bgcolor="<%= i % 2 == 0 ? "#FFCCCC" : "#CCCCFF" %>">
          <td><%= i %></td>
          <td><%= argv[i] %></td>
        </tr>
        <% } %>
       </tbody>
      </table>
     </body>
    </html>
    <%
        std::string output = _buf.str();
        std::cout << output;
        return 0; 
    }
    %>
    
    compiled source code
    $ erubis -l cpp example.ecpp
    #line 1 "example.ecpp"
    
    #include <string>
    #include <iostream>
    #include <sstream>
    
    int main(int argc, char *argv[])
    {
        std::stringstream _buf;
    
    _buf << "<html>\n"
            " <body>\n"
            "  <p>Hello "; _buf << (argv[0]); _buf << "!</p>\n"
            "  <table>\n"
            "   <tbody>\n";
         for (int i = 1; i < argc; i++) { 
    _buf << "    <tr bgcolor=\""; _buf << (i % 2 == 0 ? "#FFCCCC" : "#CCCCFF"); _buf << "\">\n"
            "      <td>"; _buf << (i); _buf << "</td>\n"
            "      <td>"; _buf << (argv[i]); _buf << "</td>\n"
            "    </tr>\n";
         } 
    _buf << "   </tbody>\n"
            "  </table>\n"
            " </body>\n"
            "</html>\n";
    
        std::string output = _buf.str();
        std::cout << output;
        return 0; 
    }
    
    

    Java

    Example.ejava
    <%
    import java.util.*;
    
    public class Example {
      private String user;
      private String[] list;
      public example(String user, String[] list) {
        this.user = user;
        this.list = list;
      }
    
      public String view() {
        StringBuffer _buf = new StringBuffer();
    %>
    <html>
     <body>
      <p>Hello <%= user %>!</p>
      <table>
       <tbody>
        <% for (int i = 0; i < list.length; i++) { %>
        <tr bgcolor="<%= i % 2 == 0 ? "#FFCCCC" : "#CCCCFF" %>">
         <td><%= i + 1 %></td>
         <td><%== list[i] %></td>
        </tr>
        <% } %>
       </tbody>
      </table>
     <body>
    </html>
    <%
        return _buf.toString();
      }
    
      public static void main(String[] args) {
        String[] list = { "<aaa>", "b&b", "\"ccc\"" };
        Example ex = Example.new("Erubis", list);
        System.out.print(ex.view());
      }
    
      public static String escape(String s) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
          char ch = s.charAt(i);
          switch (ch) {
          case '<':   sb.append("&lt;"); break;
          case '>':   sb.append("&gt;"); break;
          case '&':   sb.append("&amp;"); break;
          case '"':   sb.append("&quot;"); break;
          default:    sb.append(ch);
          }
        }
        return sb.toString();
      }
    }
    %>
    
    compiled source code
    $ erubis -b -l java example.ejava
    
    import java.util.*;
    
    public class Example {
      private String user;
      private String[] list;
      public example(String user, String[] list) {
        this.user = user;
        this.list = list;
      }
    
      public String view() {
        StringBuffer _buf = new StringBuffer();
    
    _buf.append("<html>\n"
              + " <body>\n"
              + "  <p>Hello "); _buf.append(user); _buf.append("!</p>\n"
              + "  <table>\n"
              + "   <tbody>\n");
         for (int i = 0; i < list.length; i++) { 
    _buf.append("    <tr bgcolor=\""); _buf.append(i % 2 == 0 ? "#FFCCCC" : "#CCCCFF"); _buf.append("\">\n"
              + "     <td>"); _buf.append(i + 1); _buf.append("</td>\n"
              + "     <td>"); _buf.append(escape(list[i])); _buf.append("</td>\n"
              + "    </tr>\n");
         } 
    _buf.append("   </tbody>\n"
              + "  </table>\n"
              + " <body>\n"
              + "</html>\n");
    
        return _buf.toString();
      }
    
      public static void main(String[] args) {
        String[] list = { "<aaa>", "b&b", "\"ccc\"" };
        Example ex = Example.new("Erubis", list);
        System.out.print(ex.view());
      }
    
      public static String escape(String s) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
          char ch = s.charAt(i);
          switch (ch) {
          case '<':   sb.append("&lt;"); break;
          case '>':   sb.append("&gt;"); break;
          case '&':   sb.append("&amp;"); break;
          case '"':   sb.append("&quot;"); break;
          default:    sb.append(ch);
          }
        }
        return sb.toString();
      }
    }
    
    

    Scheme

    example.escheme
    <html>
     <body>
    <%
    (let ((user "Erubis")
          (items '("<aaa>" "b&b" "\"ccc\""))
          (i 0))
     %>
      <p>Hello <%= user %>!</p>
      <table>
    <%
      (for-each
       (lambda (item)
         (set! i (+ i 1))
     %>
       <tr bgcolor="<%= (if (= (modulo i 2) 0) "#FFCCCC" "#CCCCFF") %>">
        <td><%= i %></td>
        <td><%= item %></td>
       </tr>
    <%
       ) ; lambda end
       items) ; for-each end
     %>
      </table>
    <%
    ) ; let end
    %>
     </body>
    </html>
    
    compiled source code
    $ erubis -l scheme example.escheme
    (let ((_buf '())) (define (_add x) (set! _buf (cons x _buf))) (_add "<html>
     <body>\n")
    
    (let ((user "Erubis")
          (items '("<aaa>" "b&b" "\"ccc\""))
          (i 0))
     
    (_add "  <p>Hello ")(_add user)(_add "!</p>
      <table>\n")
    
      (for-each
       (lambda (item)
         (set! i (+ i 1))
     
    (_add "   <tr bgcolor=\"")(_add (if (= (modulo i 2) 0) "#FFCCCC" "#CCCCFF"))(_add "\">
        <td>")(_add i)(_add "</td>
        <td>")(_add item)(_add "</td>
       </tr>\n")
    
       ) ; lambda end
       items) ; for-each end
     
    (_add "  </table>\n")
    
    ) ; let end
    
    (_add " </body>
    </html>\n")
      (reverse _buf))
    
    compiled source code (with --func=display property)
    $ erubis -l scheme --func=display example.escheme
    (display "<html>
     <body>\n")
    
    (let ((user "Erubis")
          (items '("<aaa>" "b&b" "\"ccc\""))
          (i 0))
     
    (display "  <p>Hello ")(display user)(display "!</p>
      <table>\n")
    
      (for-each
       (lambda (item)
         (set! i (+ i 1))
     
    (display "   <tr bgcolor=\"")(display (if (= (modulo i 2) 0) "#FFCCCC" "#CCCCFF"))(display "\">
        <td>")(display i)(display "</td>
        <td>")(display item)(display "</td>
       </tr>\n")
    
       ) ; lambda end
       items) ; for-each end
     
    (display "  </table>\n")
    
    ) ; let end
    
    (display " </body>
    </html>\n")
    

    Perl

    example.eperl
    <%
       my $user = 'Erubis';
       my @list = ('<aaa>', 'b&b', '"ccc"');
    %>
    <html>
     <body>
      <p>Hello <%= $user %>!</p>
      <table>
       <% $i = 0; %>
       <% for $item (@list) { %>
       <tr bgcolor=<%= ++$i % 2 == 0 ? '#FFCCCC' : '#CCCCFF' %>">
        <td><%= $i %></td>
        <td><%= $item %></td>
       </tr>
       <% } %>
      </table>
     </body>
    </html>
    
    compiled source code
    $ erubis -l perl example.eperl
    use HTML::Entities; 
       my $user = 'Erubis';
       my @list = ('<aaa>', 'b&b', '"ccc"');
    
    print('<html>
     <body>
      <p>Hello '); print($user); print('!</p>
      <table>
    ');     $i = 0; 
        for $item (@list) { 
    print('   <tr bgcolor='); print(++$i % 2 == 0 ? '#FFCCCC' : '#CCCCFF'); print('">
        <td>'); print($i); print('</td>
        <td>'); print($item); print('</td>
       </tr>
    ');     } 
    print('  </table>
     </body>
    </html>
    '); 
    

    JavaScript

    example.ejs
    <%
       var user = 'Erubis';
       var list = ['<aaa>', 'b&b', '"ccc"'];
     %>
    <html>
     <body>
      <p>Hello <%= user %>!</p>
      <table>
       <tbody>
        <% var i; %>
        <% for (i = 0; i < list.length; i++) { %>
        <tr bgcolor="<%= i % 2 == 0 ? '#FFCCCC' : '#CCCCFF' %>">
         <td><%= i + 1 %></td>
         <td><%= list[i] %></td>
        </tr>
        <% } %>
       </tbody>
      </table>
     </body>
    </html>
    
    compiled source code
    $ erubis -l js example.ejs
    var _buf = [];
       var user = 'Erubis';
       var list = ['<aaa>', 'b&b', '"ccc"'];
     
    _buf.push("<html>\n\
     <body>\n\
      <p>Hello "); _buf.push(user); _buf.push("!</p>\n\
      <table>\n\
       <tbody>\n");
         var i; 
         for (i = 0; i < list.length; i++) { 
    _buf.push("    <tr bgcolor=\""); _buf.push(i % 2 == 0 ? '#FFCCCC' : '#CCCCFF'); _buf.push("\">\n\
         <td>"); _buf.push(i + 1); _buf.push("</td>\n\
         <td>"); _buf.push(list[i]); _buf.push("</td>\n\
        </tr>\n");
         } 
    _buf.push("   </tbody>\n\
      </table>\n\
     </body>\n\
    </html>\n");
    document.write(_buf.join(""));
    

    If command-line option '--docwrite=false' is specified, '_buf.join("");' is used instead of 'document.write(_buf.join(""));'. This is useful when passing converted source code to eval() function in JavaScript.

    You can pass :docwrite=>false to Erubis::Ejavascript.new() in your Ruby script.

    s = File.read('example.jshtml')
    engine = Erubis::Ejavascript.new(s, :docwrite=>false)
    

    If you want to specify any JavaScript code, use '--postamble=...'.

    Notice that default value of 'docwrite' property will be false in the future release.



    Ruby on Rails Support

    NOTICE: Rails 3 adopts Erubis as default default engine. You don't need to do anything at all when using Rails 3. This section is for Rails 2.

    Erubis supports Ruby on Rails. This section describes how to use Erubis with Ruby on Rails.

    Settings

    Add the following code to your 'config/environment.rb' and restart web server. This replaces ERB in Rails by Erubis entirely.

    config/environment.rb
    require 'erubis/helpers/rails_helper'
    #Erubis::Helpers::RailsHelper.engine_class = Erubis::Eruby # or Erubis::FastEruby
    #Erubis::Helpers::RailsHelper.init_properties = {}
    #Erubis::Helpers::RailsHelper.show_src = nil
    #Erubis::Helpers::RailsHelper.preprocessing = false
    

    Options:

    Erubis::Helpers::RailsHelper.engine_class (=Erubis::Eruby)

    Erubis engine class (default Erubis::Eruby).

    Erubis::Helpers::RailsHelper.init_properties (={})

    Optional arguments for Erubis::Eruby#initialize() method (default {}).

    Erubis::Helpers::RailsHelper.show_src (=nil)

    Whether to print converted Ruby code into log file. If true, Erubis prints coverted code into log file. If false, Erubis doesn't. If nil, Erubis prints when ENV['RAILS_ENV'] == 'development'. Default is nil.

    Erubis::Helpers::RailsHelper.preprocessing (=false)

    Enable preprocessing if true (default false).


    Preprosessing

    Erubis supports preprocessing of template files. Preprocessing make your Ruby on Rails application about 20-40 percent faster. To enable preprocessing, set Erubis::Helpers::RailsHelper.preprocessing to true in your 'environment.rb' file.

    For example, assume the following template. This is slow because link_to() method is called every time when template is rendered.

    <%= link_to 'Create', :action=>'create' %>
    

    The following is faster than the above, but not flexible because url is fixed.

    <a href="/users/create">Create</a>
    

    Preprocessing solves this problem. If you use '[%= %]' instead of '<%= %>', preprocessor evaluate it only once when template is loaded.

    [%= link_to 'Create', :action=>'create'%]
    

    The above is evaluated by preprocessor and replaced to the following code automatically.

    <a href="/users/create">Create</a>
    

    Notice that this is done only once when template file is loaded. It means that link_to() method is not called when template is rendered.

    If link_to() method have variable arguments, use _?() helper method.

    <% for user in @users %>
    [%= link_to _?('user.name'), :action=>'show', :id=>_?('user.id') %]
    <% end %>
    

    The above is evaluated by preprocessor when template is loaded and expanded into the following code. This will be much faster because link_to() method is not called when rendering.

    <% for user in @users %>
    <a href="/users/show/<%=user.id%>"><%=user.name%></a>
    <% end %>
    

    Preprocessing statement ([% %]) is also available as well as preprocessing expression ([%= %]).

    <select name="state">
      <option value="">-</option>
    [% for code in states.keys.sort %]
      <option value="[%= code %]">[%= states[code] %]</option>
    [% end %]
    </select>
    

    The above will be evaluated by preprocessor and expanded into the following when template is loaded. In the result, rendering speed will be much faster because for-loop is not executed when rendering.

    <select name="state">
      <option value="">-</option>
      <option value="AK">Alaska</option>
      <option value="AL">Alabama</option>
      <option value="AR">Arkansas</option>
      <option value="AS">American Samoa</option>
      <option value="AZ">Arizona</option>
      <option value="CA">California</option>
      <option value="CO">Colorado</option>
       ....
    </select>
    

    Notice that it is not recommended to use preprocessing with tag helpers, because tag helpers generate different html code when form parameter has errors or not.

    Helper methods of Ruby on Rails are divided into two groups.

    • link_to() or _() (method of gettext package) are not need to call for every time as template is rendered because it returns same value when same arguments are passed. These methods can be got faster by preprocessing.
    • Tag helper methods should be called for every time as template is rendered because it may return differrent value even if the same arguments are passed. Preprocessing is not available with these methods.

    In Ruby on Rails 2.0, _?('user_id') is OK but _?('user.id') is NG because the latter contains period ('.') character.

    <!-- NG in Rails 2.0, because _?('') contains period -->
    [%= link_to 'Edit', edit_user_path(_?('@user.id')) %]
    [%= link_to 'Show', @user %]
    [%= link_to 'Delete', @user, :confirm=>'OK?', :method=>:delete %]
    
    <!-- OK in Rails 2.0 -->
    <%= user_id = @user.id %>
    [%= link_to 'Edit', edit_user_path(_?('user_id')) %]
    [%= link_to 'Show', :action=>'show', :id=>_?('user_id') %]
    [%= link_to 'Delete', {:action=>'destroy', :id=>_?('user_id')},
                          {:confirm=>'OK?', :method=>:delete} %]
    

    Form Helpers for Preprocessing

    (Experimental)

    Erubis provides form helper methods for preprocessing. These are defined in 'erubis/helpers/rails_form_helper.rb'. If you want to use it, require it and include Erubis::Helpers::RailsFormHelper in 'app/helpers/applition_helper.rb'

    app/helpers/xxx_helper.rb
    require 'erubis/helpers/rails_form_helper'
    module ApplicationHelper
      include Erubis::Helpers::RailsFormHelper
    end
    

    Form helper methods defined in Erubis::Helpers::RailsFormHelper are named as 'pp_xxxx' ('pp' represents preprocessing).

    Assume the following view template:

    _form.rhtml
     <p>
      Name: <%= text_field :user, :name %>
     </p>
     <p>
      Name: [%= pp_text_field :user, :name %]
     </p>
    

    Erubis preprocessor converts it to the following eRuby string:

    preprocessed
     <p>
      Name: <%= text_field :user, :name %>
     </p>
     <p>
      Name: <input id="stock_name" name="stock[name]" size="30" type="text" value="<%=h @stock.name%>" />
     </p>
    

    Erubis converts it to the following Ruby code:

    Ruby code
     _buf << ' <p>
      Name: '; _buf << ( text_field :stock, :name ).to_s; _buf << '
    '; _buf << ' </p>
     <p>
      Name: <input id="stock_name" name="stock[name]" size="30" type="text" value="'; _buf << (h @stock.name).to_s; _buf << '" />
     </p>
    ';
    

    The above Ruby code shows that text_field() is called everytime when rendering, but pp_text_field() is called only once when template is loaded. This means that pp_text_field() with preprocessing makes view layer very fast.

    Module Erubis::Helpers::RailsFormHelper defines the following form helper methods.

    • pp_render_partial(basename)
    • pp_form_tag(url_for_options={}, options={}, *parameters_for_url, &block)
    • pp_text_field(object_name, method, options={})
    • pp_password_field(object_name, method, options={})
    • pp_hidden_field(object_name, method, options={})
    • pp_file_field(object_name, method, options={})
    • pp_text_area(object_name, method, options={})
    • pp_check_box(object_name, method, options={}, checked_value="1", unchecked_value="0")
    • pp_radio_button(object_name, method, tag_value, options={})
    • pp_select(object, method, collection, options={}, html_options={})
    • pp_collection_select(object, method, collection, value_method, text_method, options={}, html_options={})
    • pp_country_select(object, method, priority_countries=nil, options={}, html_options={})
    • pp_time_zone_select(object, method, priority_zones=nil, options={}, html_options={})
    • pp_submit_tag(value="Save changes", options={})
    • pp_image_submit_tag(source, options={})

    Notice that pp_form_for() is not provided.

    CAUTION: These are experimental and may not work in Ruby on Rails 2.0.


    Others

    • ActionView::Helpers::CaptureHelper#capture() and ActionView::Helpers::Texthelper#concat() are available.
    • Form helper methods are not tested in Ruby on Rails 2.0.
    • ERB::Util.h() is redefined if you require 'erubis/helpers/rails_helper.rb'. Original definition of ERB::Util.h() is the following and it is slow because it scans string four times.
       def html_escape(s)
         s.to_s.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;")
       end
       alias h html_escape
      

      New definition in 'erubis/helpers/rails_helper.rb' is faster than the above because it scans string only once.

       ESCAPE_TABLE = { '&'=>'&amp;', '<'=>'&lt;', '>'=>'&gt;', '"'=>'&quot;', "'"=>'&#039;', }
       def h(value)
         value.to_s.gsub(/[&<>"]/) { |s| ESCAPE_TABLE[s] }
       end
      

      Notice that the new definition may be slow if string contains many '< > & "' characters because block is call many time. You should use ERB::Util.html_hscape() if string contains a lot of '< > & "' characters.



    Other Topics

    Erubis::FastEruby Class

    Erubis::FastEruby class generates more effective code than Erubis::Eruby.

    fasteruby-example.rb
    require 'erubis'
    input = File.read('example.eruby')
    
    puts "----- Erubis::Eruby -----"
    print Erubis::Eruby.new(input).src
    
    puts "----- Erubis::FastEruby -----"
    print Erubis::FastEruby.new(input).src
    
    result
    $ ruby fasteruby-example.rb
    ----- Erubis::Eruby -----
    _buf = ''; _buf << '<div>
    '; for item in list 
     _buf << '  <p>'; _buf << ( item ).to_s; _buf << '</p>
      <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
    '; end 
     _buf << '</div>
    ';
    _buf.to_s
    ----- Erubis::FastEruby -----
    _buf = ''; _buf << %Q`<div>\n`
     for item in list 
     _buf << %Q`  <p>#{ item }</p>
      <p>#{Erubis::XmlHelper.escape_xml( item )}</p>\n`
     end 
     _buf << %Q`</div>\n`
    _buf.to_s
    

    Technically, Erubis::FastEruby is just a subclass of Erubis::Eruby and includes InterpolationEnhancer. Erubis::FastEruby is faster than Erubis::Eruby but is not extensible compared to Erubis::Eruby. This is the reason why Erubis::FastEruby is not the default class of Erubis.


    :bufvar Option

    Since 2.7.0, Erubis supports :bufvar option which allows you to change buffer variable name (default '_buf').

    bufvar-example.rb
    require 'erubis'
    input = File.read('example.eruby')
    
    puts "----- default -----"
    eruby = Erubis::FastEruby.new(input)
    puts eruby.src
    
    puts "----- with :bufvar option -----"
    eruby = Erubis::FastEruby.new(input, :bufvar=>'@_out_buf')
    print eruby.src
    
    result
    $ ruby bufvar-example.rb
    ----- default -----
    _buf = ''; _buf << %Q`<div>\n`
     for item in list 
     _buf << %Q`  <p>#{ item }</p>
      <p>#{Erubis::XmlHelper.escape_xml( item )}</p>\n`
     end 
     _buf << %Q`</div>\n`
    _buf.to_s
    ----- with :bufvar option -----
    @_out_buf = ''; @_out_buf << %Q`<div>\n`
     for item in list 
     @_out_buf << %Q`  <p>#{ item }</p>
      <p>#{Erubis::XmlHelper.escape_xml( item )}</p>\n`
     end 
     @_out_buf << %Q`</div>\n`
    @_out_buf.to_s
    

    '<%= =%>' and '<%= -%>'

    Since 2.6.0, '<%= -%>' remove tail spaces and newline. This is for compatibiliy with ERB when trim mode is '-'. '<%= =%>' also removes tail spaces and newlines, and this is Erubis-original enhancement (cooler than '<%= -%>', isn't it?).

    tailnewline.rhtml
    <div>
    <%= @var -%>          # or <%= @var =%>
    </div>
    
    result (version 2.5.0):
    $ erubis -c '{var: "AAA\n"}' tailnewline.rhtml
    <div>
    AAA
    
    </div>
    
    result (version 2.6.0):
    $ erubis -c '{var: "AAA\n"}' tailnewline.rhtml
    <div>
    AAA
    </div>
    

    '<%% %>' and '<%%= %>'

    Since 2.6.0, '<%% %>' and '<%%= %>' are converted into '<% %>' and '<%= %>' respectively. This is for compatibility with ERB.

    doublepercent.rhtml:
    <ul>
    <%% for item in @list %>
      <li><%%= item %></li>
    <%% end %>
    </ul>
    
    result:
    $ erubis doublepercent.rhtml
    <ul>
    <% for item in @list %>
      <li><%= item %></li>
    <% end %>
    </ul>
    

    evaluate(context) v.s. result(binding)

    It is recommended to use 'Erubis::Eruby#evaluate(context)' instead of 'Erubis::Eruby#result(binding)' because Ruby's Binding object has some problems.

    • It is not able to specify variables to use. Using binding() method, all of local variables are passed to templates.
    • Changing local variables in templates may affect to varialbes in main program. If you assign '10' to local variable 'x' in templates, it may change variable 'x' in main program unintendedly.

    The following example shows that assignment of some values into variable 'x' in templates affect to local variable 'x' in main program unintendedly.

    template1.rhtml (intended to be passed 'items' from main program)
    <% for x in items %>
    item = <%= x %>
    <% end %>
    ** debug: local variables=<%= local_variables().inspect() %>
    
    main_program1.rb (intended to pass 'items' to template)
    require 'erubis'
    eruby = Erubis::Eruby.new(File.read('template1.rhtml'))
    items = ['foo', 'bar', 'baz']
    x = 1
    ## local variable 'x' and 'eruby' are passed to template as well as 'items'!
    print eruby.result(binding())    
    ## local variable 'x' is changed unintendedly because it is changed in template!
    puts "** debug: x=#{x.inspect}"  #=> "baz"
    
    Result:
    $ ruby main_program1.rb
    item = foo
    item = bar
    item = baz
    ** debug: local variables=["eruby", "items", "x", "_buf"]
    ** debug: x="baz"
    

    This problem is caused because Ruby's Binding class is poor to use in template engine. Binding class should support the following features.

    b = Binding.new     # create empty Binding object
    b['x'] = 1          # set local variables using binding object
    

    But the above features are not implemented in Ruby.

    A pragmatic solution is to use 'Erubis::Eruby#evaluate(context)' instead of 'Erubis::Eruby#result(binding)'. 'evaluate(context)' uses Erubis::Context object and instance variables instead of Binding object and local variables.

    template2.rhtml (intended to be passed '@items' from main program)
    <% for x in @items %>
    item = <%= x %>
    <% end %>
    ** debug: local variables=<%= local_variables().inspect() %>
    
    main_program2.rb (intended to pass '@items' to template)
    require 'erubis'
    eruby = Erubis::Eruby.new(File.read('template2.rhtml'))
    items = ['foo', 'bar', 'baz']
    x = 1
    ## only 'items' are passed to template
    print eruby.evaluate(:items=>items)    
    ## local variable 'x' is not changed!
    puts "** debug: x=#{x.inspect}"  #=> 1
    
    Result:
    $ ruby main_program2.rb
    item = foo
    item = bar
    item = baz
    ** debug: local variables=["_context", "x", "_buf"]
    ** debug: x=1
    

    Class Erubis::FastEruby

    [experimental]

    Erubis provides Erubis::FastEruby class which includes InterpolationEnhancer and works faster than Erubis::Eruby class. If you desire more speed, try Erubis::FastEruby class.

    File 'fasteruby.rhtml':
    <html>
      <body>
        <h1><%== @title %></h1>
        <table>
    <% i = 0 %>
    <% for item in @list %>
    <%   i += 1 %>
          <tr>
            <td><%= i %></td>
            <td><%== item %></td>
          </tr>
    <% end %>
        </table>
      </body>
    </html>
    
    File 'fasteruby.rb':
    require 'erubis'
    input = File.read('fasteruby.rhtml')
    eruby = Erubis::FastEruby.new(input)    # create Eruby object
    
    puts "---------- script source ---"
    puts eruby.src
    
    puts "---------- result ----------"
    context = { :title=>'Example', :list=>['aaa', 'bbb', 'ccc'] }
    output = eruby.evaluate(context)
    print output
    
    output
    $ ruby fasteruby.rb
    ---------- script source ---
    _buf = ''; _buf << %Q`<html>
      <body>
        <h1>#{Erubis::XmlHelper.escape_xml( @title )}</h1>
        <table>\n`
     i = 0 
     for item in @list 
       i += 1 
     _buf << %Q`      <tr>
            <td>#{ i }</td>
            <td>#{Erubis::XmlHelper.escape_xml( item )}</td>
          </tr>\n`
     end 
     _buf << %Q`    </table>
      </body>
    </html>\n`
    _buf.to_s
    ---------- result ----------
    <html>
      <body>
        <h1>Example</h1>
        <table>
          <tr>
            <td>1</td>
            <td>aaa</td>
          </tr>
          <tr>
            <td>2</td>
            <td>bbb</td>
          </tr>
          <tr>
            <td>3</td>
            <td>ccc</td>
          </tr>
        </table>
      </body>
    </html>
    

    Syntax Checking

    Command-line option '-z' checks syntax. It is similar to 'erubis -x file.rhtml | ruby -wc', but it can take several file names.

    example of command-line option '-z'
    $ erubis -z app/views/*/*.rhtml
    Syntax OK
    

    File Caching

    Erubis::Eruby.load_file(filename) convert file into Ruby script and return Eruby object. In addition, it caches converted Ruby script into cache file (filename + '.cache') if cache file is old or not exist. If cache file exists and is newer than eruby file, Erubis::Eruby.load_file() loads cache file.

    example of Erubis::Eruby.load_file()
    require 'erubis'
    filename = 'example.rhtml'
    eruby = Erubis::Eruby.load_file(filename)
    cachename = filename + '.cache'
    if test(?f, cachename)
      puts "*** cache file '#{cachename}' created."
    end
    

    Since 2.6.0, it is able to specify cache filename.

    specify cache filename.
    filename = 'example.rhtml'
    eruby = Erubis::Eruby.load_file(filename, :cachename=>filename+'.cache')
    

    Caching makes Erubis about 40-50 percent faster than no-caching. See benchmark for details.


    Erubis::TinyEruby class

    Erubis::TinyEruby class in 'erubis/tiny.rb' is the smallest implementation of eRuby. If you don't need any enhancements of Erubis and only require simple eRuby implementation, try Erubis::TinyEruby class.


    NoTextEnhancer and NoCodeEnhancer in PHP

    NoTextEnhancer and NoCodEnahncer are quite useful not only for eRuby but also for PHP. The former "drops" HTML text and show up embedded Ruby/PHP code and the latter drops embedded Ruby/PHP code and leave HTML text.

    For example, see the following PHP script.

    notext-example.php
    <html>
      <body>
        <h3>List</h3>
        <?php if (!$list || count($list) == 0) { ?>
        <p>not found.</p>
        <?php } else { ?>
        <table>
          <tbody>
            <?php $i = 0; ?>
            <?php foreach ($list as $item) { ?>
            <tr bgcolor="<?php echo ++$i % 2 == 1 ? '#FFCCCC' : '#CCCCFF'; ?>">
              <td><?php echo $item; ?></td>
            </tr>
            <?php } ?>
          </tbody>
        </table>
        <?php } ?>
      </body>
    </html>
    

    This is complex because PHP code and HTML document are mixed. NoTextEnhancer can separate PHP code from HTML document.

    example of using NoTextEnhancer with PHP file
    $ erubis -l php --pi=php -N -E NoText --trim=false notext-example.php
        1:  
        2:  
        3:  
        4:      <?php if (!$list || count($list) == 0) { ?>
        5:  
        6:      <?php } else { ?>
        7:  
        8:  
        9:          <?php $i = 0; ?>
       10:          <?php foreach ($list as $item) { ?>
       11:                       <?php echo ++$i % 2 == 1 ? '#FFCCCC' : '#CCCCFF'; ?>
       12:                <?php echo $item; ?>
       13:  
       14:          <?php } ?>
       15:  
       16:  
       17:      <?php } ?>
       18:  
       19:  
    

    In the same way, NoCodeEnhancer can extract HTML tags.

    example of using NoCodeEnhancer with PHP file
    $ erubis -l php --pi=php -N -E NoCode --trim=false notext-example.php
        1:  <html>
        2:    <body>
        3:      <h3>List</h3>
        4:      
        5:      <p>not found.</p>
        6:      
        7:      <table>
        8:        <tbody>
        9:          
       10:          
       11:          <tr bgcolor="">
       12:            <td></td>
       13:          </tr>
       14:          
       15:        </tbody>
       16:      </table>
       17:      
       18:    </body>
       19:  </html>
    

    Helper Class for mod_ruby

    Thanks Andrew R Jackson, he developed 'erubis-run.rb' which enables you to use Erubis with mod_ruby.

    1. Copy 'erubis-2.7.0/contrib/erubis-run.rb' to the 'RUBYLIBDIR/apache' directory (for example '/usr/local/lib/ruby/1.8/apache') which contains 'ruby-run.rb', 'eruby-run.rb', and so on.
      $ cd erubis-2.7.0/
      $ sudo copy contrib/erubis-run.rb /usr/local/lib/ruby/1.8/apache/
      
    2. Add the following example to your 'httpd.conf' (for example '/usr/local/apache2/conf/httpd.conf')
      LoadModule ruby_module modules/mod_ruby.so
      <IfModule mod_ruby.c>
        RubyRequire apache/ruby-run
        RubyRequire apache/eruby-run
        RubyRequire apache/erubis-run
        <Location /erubis>
          SetHandler ruby-object
          RubyHandler Apache::ErubisRun.instance
        </Location>
        <Files *.rhtml>
          SetHandler ruby-object
          RubyHandler Apache::ErubisRun.instance
        </Files>
      </IfModule>
      
    3. Restart Apache web server.
      $ sudo /usr/local/apache2/bin/apachectl stop
      $ sudo /usr/local/apache2/bin/apachectl start
      
    4. Create *.rhtml file, for example:
      <html>
       <body>
        Now is <%= Time.now %>
        Erubis version is <%= Erubis::VERSION %>
       </body>
      </html>
      
    5. Change mode of your directory to be writable by web server process.
      $ cd /usr/local/apache2/htdocs/erubis
      $ sudo chgrp daemon .
      $ sudo chmod 775 .
      
    6. Access the *.rhtml file and you'll get the web page.

    You must set your directories to be writable by web server process, because Apache::ErubisRun calls Erubis::Eruby.load_file() internally which creates cache files in the same directory in which '*.rhtml' file exists.


    Helper CGI Script for Apache

    Erubis provides helper CGI script for Apache. Using this script, it is very easy to publish *.rhtml files as *.html.

    ### install Erubis
    $ tar xzf erubis-X.X.X.tar.gz
    $ cd erubis-X.X.X/
    $ ruby setup.py install
    ### copy files to ~/public_html
    $ mkdir -p ~/public_html
    $ cp public_html/_htaccess   ~/public_html/.htaccess
    $ cp public_html/index.cgi   ~/public_html/
    $ cp public_html/index.rhtml ~/public_html/
    ### add executable permission to index.cgi
    $ chmod a+x ~/public_html/index.cgi
    ### edit .htaccess
    $ vi ~/public_html/.htaccess
    ### (optional) edit index.cgi to configure
    $ vi ~/public_html/index.cgi
    

    Edit ~/public_html/.htaccess and modify user name.

    ~/public_html/.htaccess
    ## enable mod_rewrie
    RewriteEngine on
    ## deny access to *.rhtml and *.cache
    #RewriteRule \.(rhtml|cache)$ - [R=404,L]
    RewriteRule \.(rhtml|cache)$ - [F,L]
    ## rewrite only if requested file is not found
    RewriteCond %{SCRIPT_FILENAME} !-f
    ## handle request to *.html and directories by index.cgi
    RewriteRule (\.html|/|^)$ /~username/index.cgi
    #RewriteRule (\.html|/|^)$ index.cgi
    

    After these steps, *.rhtml will be published as *.html. For example, if you access to http://host.domain/~username/index.html (or http://host.domain/~username/), file ~/public_html/index.rhtml will be displayed.


    Define method

    Erubis::Eruby#def_method() defines instance method or singleton method.

    require 'erubis'
    s = "hello <%= name %>"
    eruby = Erubis::Eruby.new(s)
    filename = 'hello.rhtml'
    
    ## define instance method to Dummy class (or module)
    class Dummy; end
    eruby.def_method(Dummy, 'render(name)', filename)  # filename is optional
    p Dummy.new.render('world')    #=> "hello world"
    
    ## define singleton method to dummy object
    obj = Object.new
    eruby.def_method(obj, 'render(name)', filename)    # filename is optional
    p obj.render('world')          #=> "hello world"
    

    Benchmark

    A benchmark script is included in Erubis package at 'erubis-2.7.0/benchark/' directory. Here is an example result of benchmark.

    MacOS X 10.4 Tiger, Intel CoreDuo 1.83GHz, Ruby1.8.6, eruby1.0.5, gcc4.0.1
    $ cd erubis-2.7.0/benchmark/
    $ ruby bench.rb -n 10000 -m execute
    *** ntimes=10000, testmode=execute
                                        user     system      total        real
    eruby                          12.720000   0.240000  12.960000 ( 12.971888)
    ERB                            36.760000   0.350000  37.110000 ( 37.112019)
    ERB(cached)                    11.990000   0.440000  12.430000 ( 12.430375)
    Erubis::Eruby                  10.840000   0.300000  11.140000 ( 11.144426)
    Erubis::Eruby(cached)           7.540000   0.410000   7.950000 (  7.969305)
    Erubis::FastEruby              10.440000   0.300000  10.740000 ( 10.737808)
    Erubis::FastEruby(cached)       6.940000   0.410000   7.350000 (  7.353666)
    Erubis::TinyEruby               9.550000   0.290000   9.840000 (  9.851729)
    Erubis::ArrayBufferEruby       11.010000   0.300000  11.310000 ( 11.314339)
    Erubis::PrintOutEruby          11.640000   0.290000  11.930000 ( 11.942141)
    Erubis::StdoutEruby            11.590000   0.300000  11.890000 ( 11.886512)
    

    This shows that...

    • Erubis::Eruby runs more than 10 percent faster than eruby.
    • Erubis::Eruby runs about 3 times faster than ERB.
    • Caching (by Erubis::Eruby.load_file()) makes Erubis about 40-50 percent faster.
    • Erubis::FastEruby is a litte faster than Erubis::Eruby.
    • Array buffer (ArrayBufferEnhancer) is a little slower than string buffer (StringBufferEnhancer which Erubis::Eruby includes)
    • $stdout and print() make Erubis a little slower.
    • Erubis::TinyEruby (at 'erubis/tiny.rb') is the fastest in all eRuby implementations when no caching.

    Escaping HTML characters (such as '< > & "') makes Erubis more faster than eruby and ERB, because Erubis::XmlHelper#escape_xml() works faster than CGI.escapeHTML() and ERB::Util#h(). The following shows that Erubis runs more than 40 percent (when no-cached) or 90 percent (when cached) faster than eruby if HTML characters are escaped.

    When escaping HTML characters with option '-e'
    $ ruby bench.rb -n 10000 -m execute -ep
    *** ntimes=10000, testmode=execute
                                        user     system      total        real
    eruby                          21.700000   0.290000  21.990000 ( 22.050687)
    ERB                            45.140000   0.390000  45.530000 ( 45.536976)
    ERB(cached)                    20.340000   0.470000  20.810000 ( 20.822653)
    Erubis::Eruby                  14.830000   0.310000  15.140000 ( 15.147930)
    Erubis::Eruby(cached)          11.090000   0.420000  11.510000 ( 11.514954)
    Erubis::FastEruby              14.850000   0.310000  15.160000 ( 15.172499)
    Erubis::FastEruby(cached)      10.970000   0.430000  11.400000 ( 11.399605)
    Erubis::ArrayBufferEruby       14.970000   0.300000  15.270000 ( 15.281061)
    Erubis::PrintOutEruby          15.780000   0.300000  16.080000 ( 16.088289)
    Erubis::StdoutEruby            15.840000   0.310000  16.150000 ( 16.235338)
    


    Command Reference

    Usage

    erubis [..options..] [file ...]


    Options

    -h, --help
    Help.
    -v
    Release version.
    -x
    Show compiled source.
    -X
    Show compiled source but only Ruby code. This is equivarent to '-E NoText'.
    -N
    Numbering: add line numbers. (for '-x/-X')
    -U
    Unique mode: zip empty lines into a line. (for '-x/-X')
    -C
    Compact: remove empty lines. (for '-x/-X')
    -b
    Body only: no preamble nor postamble. (for '-x/-X') This is equivarent to '--preamble=false --postamble=false'.
    -z
    Syntax checking.
    -e
    Escape. This is equivarent to '-E Escape'.
    -p pattern
    Embedded pattern (default '<% %>'). This is equivarent to '--pattern=pattern'.
    -l lang
    Language name. This option makes erubis command to compile script but no execute.
    -E enhacers
    Enhancer name (Escape, PercentLine, ...). It is able to specify several enhancer name separating with ',' (ex. -f Escape,PercentLine,HeaderFooter).
    -I path
    Require library path ($:). It is able to specify several paths separating with ',' (ex. -f path1,path2,path3).
    -K kanji
    Kanji code (euc, sjis, utf8, or none) (default none).
    -f datafile
    Context data file in YAML format ('*.yaml', '*.yml') or Ruby script ('*.rb'). It is able to specify several filenames separating with ',' (ex. -f file1,file2,file3).
    -c context
    Context data string in YAML inline style or Ruby code.
    -T
    Don't expand tab characters in YAML file.
    -S
    Convert mapping key from string to symbol in YAML file.
    -B
    invoke Eruby#result() instead of Eruby#evaluate()
    --pi[=name]
    parse '<?name ... ?>' instead of '<% ... %>'
    --trim=false
    No trimming spaces around '<% %>'.

    Properties

    Some Eruby classes can take optional properties to change it's compile option. For example, property '--indent=" "' may change indentation of compiled source code. Try 'erubis -h' for details.



    ruby-erubis-2.7.0/examples/000077500000000000000000000000001170760342400156125ustar00rootroot00000000000000ruby-erubis-2.7.0/examples/basic/000077500000000000000000000000001170760342400166735ustar00rootroot00000000000000ruby-erubis-2.7.0/examples/basic/Makefile000066400000000000000000000027621170760342400203420ustar00rootroot00000000000000all = example.rb example.php example.c example.cpp example.java example.scm example.pl example.js all: $(all) example.rb: example.eruby erubis -l ruby example.eruby > example.rb example.php: example.ephp erubis -l php example.ephp > example.php example.c: example.ec erubis -bl c example.ec > example.c example.cpp: example.ecpp erubis -bl cpp example.ecpp > example.cpp example.java: example.ejava erubis -bl java example.ejava > example.java example.scm: example.escheme erubis -l scheme --func=display example.escheme > example.scm # erubis -l scheme example.escheme > example.scm example.pl: example.eperl erubis -l perl example.eperl > example.pl example.js: example.ejs erubis -l javascript example.ejs > example.js ###---------- src = example.eruby example.ephp example.ec example.ecpp example.ejava example.escheme example.eperl example.ejs Makefile clean: rm -f `ruby -e 'puts(Dir.glob("*.*") - %w[$(src)])'` # rm -f $(all) compile: example.bin example.class example.bin: example.c cc -o example.bin example.c g++ -o example.bin2 example.cpp example.class: example.java jikes example.java output: $(all) example.bin example.class erubis example.eruby > example.ruby.out php example.php > example.php.out ./example.bin '' 'b&b' '"ccc"' > example.c.out ./example.bin2 '' 'b&b' '"ccc"' > example.cpp.out java example > example.javexample.bin gosh example.scm > example.scm.out # guile example.scm > example.scm.out perl example.pl > example.pl.out ruby-erubis-2.7.0/examples/basic/example.ec000066400000000000000000000014521170760342400206410ustar00rootroot00000000000000<% #include void escape(char *str, FILE *out); int main(int argc, char *argv[]) { int i; %>

    Hello <%== argv[0] %>!

    <% for (i = 1; i < argc; i++) { %> "> <% } %>
    <%= "%d", i %> <%== argv[i] %>
    <% return 0; } void escape(char *str, FILE *out) { char *pch; for (pch = str; *pch != '\0'; pch++) { switch (*pch) { case '&': fputs("&", out); break; case '>': fputs(">", out); break; case '<': fputs("<", out); break; case '"': fputs(""", out); break; case '\'': fputs("'", out); break; default: fputc(*pch, out); } } } %> ruby-erubis-2.7.0/examples/basic/example.ecpp000066400000000000000000000007761170760342400212110ustar00rootroot00000000000000<% #include #include #include int main(int argc, char *argv[]) { int i; std::stringstream _buf; %>

    Hello <%= argv[0] %>!

    <% for (i = 1; i < argc; i++) { %> "> <% } %>
    <%= i %> <%= argv[i] %>
    <% std::string _output = _buf.str(); std::cout << _output; return 0; } %> ruby-erubis-2.7.0/examples/basic/example.ejava000066400000000000000000000020121170760342400213310ustar00rootroot00000000000000<% import java.util.*; public class example { public static void main(String[] args) { String user = "Erubis"; String[] list = { "", "b&b", "\"ccc\"" }; StringBuffer _buf = new StringBuffer(); %>

    Hello <%== user %>!

    <% for (int i = 0; i < list.length; i++) { %> "> <% } %>
    <%= i + 1 %> <%== list[i] %>
    <% System.out.print(_buf.toString()); } public static String escape(String s) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); switch (ch) { case '<': sb.append("<"); break; case '>': sb.append(">"); break; case '&': sb.append("&"); break; case '"': sb.append("""); break; default: sb.append(ch); } } return sb.toString(); } public static String escape(int i) { return Integer.toString(i); } } %> ruby-erubis-2.7.0/examples/basic/example.ejs000066400000000000000000000005241170760342400210320ustar00rootroot00000000000000<% var user = 'Erubis'; var list = ['', 'b&b', '"ccc"']; %>

    Hello <%= user %>!

    <% var i; %> <% for (i = 0; i < list.length; i++) { %> <% } %>
    <%= i + 1 %> <%= list[i] %>
    ruby-erubis-2.7.0/examples/basic/example.eperl000066400000000000000000000005041170760342400213560ustar00rootroot00000000000000<% my $user = 'Erubis'; my @list = ('', 'b&b', '"ccc"'); %>

    Hello <%== $user %>!

    <% $i = 0; %> <% for $item (@list) { %> "> <% } %>
    <%= $i %> <%== $item %>
    ruby-erubis-2.7.0/examples/basic/example.ephp000066400000000000000000000005301170760342400212020ustar00rootroot00000000000000<% $user = "World"; $list = array('', 'b&b', '"ccc"'); %>

    Hello <%= $user %>!

    <% $i = 0 %> <% foreach ($list as $item) { %> <% $i++; %> <% } %>
    <%= $i %> <%== $item %>
    ruby-erubis-2.7.0/examples/basic/example.eruby000066400000000000000000000004671170760342400214050ustar00rootroot00000000000000<% user = 'Erubis' list = ['', 'b&b', '"ccc"'] %>

    Hello <%= user %>!

    <% list.each_with_index do |item, i| %> <% end %>
    <%= i + 1 %> <%== item %>
    ruby-erubis-2.7.0/examples/basic/example.escheme000066400000000000000000000006251170760342400216640ustar00rootroot00000000000000<% (let ((user "Erubis") (items '("" "b&b" "\"ccc\"")) (i 0)) %>

    Hello <%= user %>!

    <% (for-each (lambda (item) (set! i (+ i 1)) %> "> <% ) ; lambda end items) ; for-each end %>
    <%= i %> <%= item %>
    <% ) ; let end %> ruby-erubis-2.7.0/examples/pi/000077500000000000000000000000001170760342400162225ustar00rootroot00000000000000ruby-erubis-2.7.0/examples/pi/Makefile000066400000000000000000000026331170760342400176660ustar00rootroot00000000000000all = example.rb example.php example.c example.java example.scm example.pl example.js all: $(all) example.rb: example.eruby erubis --pi -l ruby example.eruby > example.rb example.php: example.ephp erubis --pi -l php example.ephp > example.php example.c: example.ec erubis --pi -bl c example.ec > example.c example.java: example.ejava erubis --pi -bl java example.ejava > example.java example.scm: example.escheme erubis --pi -l scheme --func=display example.escheme > example.scm # erubis --pi -l scheme example.escheme > example.scm example.pl: example.eperl erubis --pi -l perl example.eperl > example.pl example.js: example.ejs erubis --pi -l javascript example.ejs > example.js ###---------- src = example.eruby example.ephp example.ec example.ejava example.escheme example.eperl example.ejs Makefile clean: rm -f `ruby -e 'puts(Dir.glob("*.*") - %w[$(src)])'` # rm -f $(all) compile: example.bin example.class example.bin: example.c cc -o example.bin example.c example.class: example.java jikes example.java output: $(all) example.bin example.class erubis --pi example.eruby > example.ruby.result #ruby example.rb > example.ruby.result php example.php > example.php.result ./example.bin '' 'b&b' '"ccc"' > example.c.result java example > example.java.result gosh example.scm > example.scm.result #guile example.scm > example.scm.result perl example.pl > example.pl.result ruby-erubis-2.7.0/examples/pi/example.ec000066400000000000000000000014421170760342400201670ustar00rootroot00000000000000 void escape(char *str, FILE *out); int main(int argc, char *argv[]) { int i; ?>

    Hello @!{argv[0]}@!

    @!{"%d", i}@ @{argv[i]}@
    ': fputs(">", out); break; case '<': fputs("<", out); break; case '"': fputs(""", out); break; case '\'': fputs("'", out); break; default: fputc(*pch, out); } } } ?> ruby-erubis-2.7.0/examples/pi/example.ejava000066400000000000000000000020151170760342400206630ustar00rootroot00000000000000", "b&b", "\"ccc\"" }; StringBuffer _buf = new StringBuffer(); ?>

    Hello @{user}@!

    @!{i + 1}@ @{list[i]}@
    ': sb.append(">"); break; case '&': sb.append("&"); break; case '"': sb.append("""); break; default: sb.append(ch); } } return sb.toString(); } public static String escape(int i) { return Integer.toString(i); } } ?> ruby-erubis-2.7.0/examples/pi/example.ejs000066400000000000000000000005201170760342400203550ustar00rootroot00000000000000', 'b&b', '"ccc"']; ?>

    Hello @{user}@!

    @{i + 1}@ @{list[i]}@
    ruby-erubis-2.7.0/examples/pi/example.eperl000066400000000000000000000005101170760342400207020ustar00rootroot00000000000000', 'b&b', '"ccc"'); ?>

    Hello @{$user}@!

    @!{$i}@ @{$item}@
    ruby-erubis-2.7.0/examples/pi/example.ephp000066400000000000000000000005341170760342400205350ustar00rootroot00000000000000', 'b&b', '"ccc"'); ?>

    Hello @{$user}@!

    @!{$i}@ @{$item}@
    ruby-erubis-2.7.0/examples/pi/example.eruby000066400000000000000000000004621170760342400207270ustar00rootroot00000000000000', 'b&b', '"ccc"'] ?>

    Hello @{user}@!

    @!{i + 1}@ @{item}@
    ruby-erubis-2.7.0/examples/pi/example.escheme000066400000000000000000000006451170760342400212150ustar00rootroot00000000000000" "b&b" "\"ccc\"")) (i 0)) ?>

    Hello @!{user}@!

    @!{i}@ @!{item}@
    ruby-erubis-2.7.0/lib/000077500000000000000000000000001170760342400145425ustar00rootroot00000000000000ruby-erubis-2.7.0/lib/erubis.rb000066400000000000000000000033251170760342400163630ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## ## ## an implementation of eRuby ## ## ex. ## input = <<'END' ##
      ## <% for item in @list %> ##
    • <%= item %> ## <%== item %>
    • ## <% end %> ##
    ## END ## list = ['', 'b&b', '"ccc"'] ## eruby = Erubis::Eruby.new(input) ## puts "--- code ---" ## puts eruby.src ## puts "--- result ---" ## context = Erubis::Context.new() # or new(:list=>list) ## context[:list] = list ## puts eruby.evaluate(context) ## ## result: ## --- source --- ## _buf = ''; _buf << '
      ## '; for item in @list ## _buf << '
    • '; _buf << ( item ).to_s; _buf << ' ## '; _buf << ' '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '
    • ## '; end ## _buf << '
    ## '; ## _buf.to_s ## --- result --- ##
      ##
    • ## <aaa>
    • ##
    • b&b ## b&b
    • ##
    • "ccc" ## "ccc"
    • ##
    ## module Erubis VERSION = ('$Release: 2.7.0 $' =~ /([.\d]+)/) && $1 end require 'erubis/engine' #require 'erubis/generator' #require 'erubis/converter' #require 'erubis/evaluator' #require 'erubis/error' #require 'erubis/context' #requier 'erubis/util' require 'erubis/helper' require 'erubis/enhancer' #require 'erubis/tiny' require 'erubis/engine/eruby' #require 'erubis/engine/enhanced' # enhanced eruby engines #require 'erubis/engine/optimized' # generates optimized ruby code #require 'erubis/engine/ephp' #require 'erubis/engine/ec' #require 'erubis/engine/ejava' #require 'erubis/engine/escheme' #require 'erubis/engine/eperl' #require 'erubis/engine/ejavascript' require 'erubis/local-setting' ruby-erubis-2.7.0/lib/erubis/000077500000000000000000000000001170760342400160335ustar00rootroot00000000000000ruby-erubis-2.7.0/lib/erubis/context.rb000066400000000000000000000031501170760342400200430ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## module Erubis ## ## context object for Engine#evaluate ## ## ex. ## template = <<'END' ## Hello <%= @user %>! ## <% for item in @list %> ## - <%= item %> ## <% end %> ## END ## ## context = Erubis::Context.new(:user=>'World', :list=>['a','b','c']) ## # or ## # context = Erubis::Context.new ## # context[:user] = 'World' ## # context[:list] = ['a', 'b', 'c'] ## ## eruby = Erubis::Eruby.new(template) ## print eruby.evaluate(context) ## class Context include Enumerable def initialize(hash=nil) hash.each do |name, value| self[name] = value end if hash end def [](key) return instance_variable_get("@#{key}") end def []=(key, value) return instance_variable_set("@#{key}", value) end def keys return instance_variables.collect { |name| name[1..-1] } end def each instance_variables.each do |name| key = name[1..-1] value = instance_variable_get(name) yield(key, value) end end def to_hash hash = {} self.keys.each { |key| hash[key] = self[key] } return hash end def update(context_or_hash) arg = context_or_hash if arg.is_a?(Hash) arg.each do |key, val| self[key] = val end else arg.instance_variables.each do |varname| key = varname[1..-1] val = arg.instance_variable_get(varname) self[key] = val end end end end end ruby-erubis-2.7.0/lib/erubis/converter.rb000066400000000000000000000250501170760342400203710ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## require 'erubis/util' module Erubis ## ## convert ## module Converter attr_accessor :preamble, :postamble, :escape def self.supported_properties # :nodoc: return [ [:preamble, nil, "preamble (no preamble when false)"], [:postamble, nil, "postamble (no postamble when false)"], [:escape, nil, "escape expression or not in default"], ] end def init_converter(properties={}) @preamble = properties[:preamble] @postamble = properties[:postamble] @escape = properties[:escape] end ## convert input string into target language def convert(input) codebuf = "" # or [] @preamble.nil? ? add_preamble(codebuf) : (@preamble && (codebuf << @preamble)) convert_input(codebuf, input) @postamble.nil? ? add_postamble(codebuf) : (@postamble && (codebuf << @postamble)) @_proc = nil # clear cached proc object return codebuf # or codebuf.join() end protected ## ## detect spaces at beginning of line ## def detect_spaces_at_bol(text, is_bol) lspace = nil if text.empty? lspace = "" if is_bol elsif text[-1] == ?\n lspace = "" else rindex = text.rindex(?\n) if rindex s = text[rindex+1..-1] if s =~ /\A[ \t]*\z/ lspace = s #text = text[0..rindex] text[rindex+1..-1] = '' end else if is_bol && text =~ /\A[ \t]*\z/ #lspace = text #text = nil lspace = text.dup text[0..-1] = '' end end end return lspace end ## ## (abstract) convert input to code ## def convert_input(codebuf, input) not_implemented end end module Basic end ## ## basic converter which supports '<% ... %>' notation. ## module Basic::Converter include Erubis::Converter def self.supported_properties # :nodoc: return [ [:pattern, '<% %>', "embed pattern"], [:trim, true, "trim spaces around <% ... %>"], ] end attr_accessor :pattern, :trim def init_converter(properties={}) super(properties) @pattern = properties[:pattern] @trim = properties[:trim] != false end protected ## return regexp of pattern to parse eRuby script def pattern_regexp(pattern) @prefix, @postfix = pattern.split() # '<% %>' => '<%', '%>' #return /(.*?)(^[ \t]*)?#{@prefix}(=+|\#)?(.*?)-?#{@postfix}([ \t]*\r?\n)?/m #return /(^[ \t]*)?#{@prefix}(=+|\#)?(.*?)-?#{@postfix}([ \t]*\r?\n)?/m return /#{@prefix}(=+|-|\#|%)?(.*?)([-=])?#{@postfix}([ \t]*\r?\n)?/m end module_function :pattern_regexp #DEFAULT_REGEXP = /(.*?)(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m #DEFAULT_REGEXP = /(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m #DEFAULT_REGEXP = /<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m DEFAULT_REGEXP = pattern_regexp('<% %>') public def convert_input(src, input) pat = @pattern regexp = pat.nil? || pat == '<% %>' ? DEFAULT_REGEXP : pattern_regexp(pat) pos = 0 is_bol = true # is beginning of line input.scan(regexp) do |indicator, code, tailch, rspace| match = Regexp.last_match() len = match.begin(0) - pos text = input[pos, len] pos = match.end(0) ch = indicator ? indicator[0] : nil lspace = ch == ?= ? nil : detect_spaces_at_bol(text, is_bol) is_bol = rspace ? true : false add_text(src, text) if text && !text.empty? ## * when '<%= %>', do nothing ## * when '<% %>' or '<%# %>', delete spaces iff only spaces are around '<% %>' if ch == ?= # <%= %> rspace = nil if tailch && !tailch.empty? add_text(src, lspace) if lspace add_expr(src, code, indicator) add_text(src, rspace) if rspace elsif ch == ?\# # <%# %> n = code.count("\n") + (rspace ? 1 : 0) if @trim && lspace && rspace add_stmt(src, "\n" * n) else add_text(src, lspace) if lspace add_stmt(src, "\n" * n) add_text(src, rspace) if rspace end elsif ch == ?% # <%% %> s = "#{lspace}#{@prefix||='<%'}#{code}#{tailch}#{@postfix||='%>'}#{rspace}" add_text(src, s) else # <% %> if @trim && lspace && rspace add_stmt(src, "#{lspace}#{code}#{rspace}") else add_text(src, lspace) if lspace add_stmt(src, code) add_text(src, rspace) if rspace end end end #rest = $' || input # ruby1.8 rest = pos == 0 ? input : input[pos..-1] # ruby1.9 add_text(src, rest) end ## add expression code to src def add_expr(src, code, indicator) case indicator when '=' @escape ? add_expr_escaped(src, code) : add_expr_literal(src, code) when '==' @escape ? add_expr_literal(src, code) : add_expr_escaped(src, code) when '===' add_expr_debug(src, code) end end end module PI end ## ## Processing Instructions (PI) converter for XML. ## this class converts '' and '${...}' notation. ## module PI::Converter include Erubis::Converter def self.desc # :nodoc: "use processing instructions (PI) instead of '<% %>'" end def self.supported_properties # :nodoc: return [ [:trim, true, "trim spaces around <% ... %>"], [:pi, 'rb', "PI (Processing Instrunctions) name"], [:embchar, '@', "char for embedded expression pattern('@{...}@')"], [:pattern, '<% %>', "embed pattern"], ] end attr_accessor :pi, :prefix def init_converter(properties={}) super(properties) @trim = properties.fetch(:trim, true) @pi = properties[:pi] if properties[:pi] @embchar = properties[:embchar] || '@' @pattern = properties[:pattern] @pattern = '<% %>' if @pattern.nil? #|| @pattern == true end def convert(input) code = super(input) return @header || @footer ? "#{@header}#{code}#{@footer}" : code end protected def convert_input(codebuf, input) unless @regexp @pi ||= 'e' ch = Regexp.escape(@embchar) if @pattern left, right = @pattern.split(' ') @regexp = /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?|#{ch}(!*)?\{(.*?)\}#{ch}|#{left}(=+)(.*?)#{right}/m else @regexp = /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?|#{ch}(!*)?\{(.*?)\}#{ch}/m end end # is_bol = true pos = 0 input.scan(@regexp) do |pi_arg, stmt, rspace, indicator1, expr1, indicator2, expr2| match = Regexp.last_match len = match.begin(0) - pos text = input[pos, len] pos = match.end(0) lspace = stmt ? detect_spaces_at_bol(text, is_bol) : nil is_bol = stmt && rspace ? true : false add_text(codebuf, text) # unless text.empty? # if stmt if @trim && lspace && rspace add_pi_stmt(codebuf, "#{lspace}#{stmt}#{rspace}", pi_arg) else add_text(codebuf, lspace) if lspace add_pi_stmt(codebuf, stmt, pi_arg) add_text(codebuf, rspace) if rspace end else add_pi_expr(codebuf, expr1 || expr2, indicator1 || indicator2) end end #rest = $' || input # ruby1.8 rest = pos == 0 ? input : input[pos..-1] # ruby1.9 add_text(codebuf, rest) end #-- #def convert_input(codebuf, input) # parse_stmts(codebuf, input) # #parse_stmts2(codebuf, input) #end # #def parse_stmts(codebuf, input) # #regexp = pattern_regexp(@pattern) # @pi ||= 'e' # @stmt_pattern ||= /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?/m # is_bol = true # pos = 0 # input.scan(@stmt_pattern) do |pi_arg, code, rspace| # match = Regexp.last_match # len = match.begin(0) - pos # text = input[pos, len] # pos = match.end(0) # lspace = detect_spaces_at_bol(text, is_bol) # is_bol = rspace ? true : false # parse_exprs(codebuf, text) # unless text.empty? # if @trim && lspace && rspace # add_pi_stmt(codebuf, "#{lspace}#{code}#{rspace}", pi_arg) # else # add_text(codebuf, lspace) # add_pi_stmt(codebuf, code, pi_arg) # add_text(codebuf, rspace) # end # end # rest = $' || input # parse_exprs(codebuf, rest) #end # #def parse_exprs(codebuf, input) # unless @expr_pattern # ch = Regexp.escape(@embchar) # if @pattern # left, right = @pattern.split(' ') # @expr_pattern = /#{ch}(!*)?\{(.*?)\}#{ch}|#{left}(=+)(.*?)#{right}/ # else # @expr_pattern = /#{ch}(!*)?\{(.*?)\}#{ch}/ # end # end # pos = 0 # input.scan(@expr_pattern) do |indicator1, code1, indicator2, code2| # indicator = indicator1 || indicator2 # code = code1 || code2 # match = Regexp.last_match # len = match.begin(0) - pos # text = input[pos, len] # pos = match.end(0) # add_text(codebuf, text) # unless text.empty? # add_pi_expr(codebuf, code, indicator) # end # rest = $' || input # add_text(codebuf, rest) #end #++ def add_pi_stmt(codebuf, code, pi_arg) # :nodoc: case pi_arg when nil ; add_stmt(codebuf, code) when 'header' ; @header = code when 'footer' ; @footer = code when 'comment'; add_stmt(codebuf, "\n" * code.count("\n")) when 'value' ; add_expr_literal(codebuf, code) else ; add_stmt(codebuf, code) end end def add_pi_expr(codebuf, code, indicator) # :nodoc: case indicator when nil, '', '==' # @{...}@ or <%== ... %> @escape == false ? add_expr_literal(codebuf, code) : add_expr_escaped(codebuf, code) when '!', '=' # @!{...}@ or <%= ... %> @escape == false ? add_expr_escaped(codebuf, code) : add_expr_literal(codebuf, code) when '!!', '===' # @!!{...}@ or <%=== ... %> add_expr_debug(codebuf, code) else # ignore end end end end ruby-erubis-2.7.0/lib/erubis/engine.rb000066400000000000000000000056721170760342400176370ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## require 'erubis/generator' require 'erubis/converter' require 'erubis/evaluator' require 'erubis/context' module Erubis ## ## (abstract) abstract engine class. ## subclass must include evaluator and converter module. ## class Engine #include Evaluator #include Converter #include Generator def initialize(input=nil, properties={}) #@input = input init_generator(properties) init_converter(properties) init_evaluator(properties) @src = convert(input) if input end ## ## convert input string and set it to @src ## def convert!(input) @src = convert(input) end ## ## load file, write cache file, and return engine object. ## this method create code cache file automatically. ## cachefile name can be specified with properties[:cachename], ## or filname + 'cache' is used as default. ## def self.load_file(filename, properties={}) cachename = properties[:cachename] || (filename + '.cache') properties[:filename] = filename timestamp = File.mtime(filename) if test(?f, cachename) && timestamp == File.mtime(cachename) engine = self.new(nil, properties) engine.src = File.read(cachename) else input = File.open(filename, 'rb') {|f| f.read } engine = self.new(input, properties) tmpname = cachename + rand().to_s[1,8] File.open(tmpname, 'wb') {|f| f.write(engine.src) } File.rename(tmpname, cachename) File.utime(timestamp, timestamp, cachename) end engine.src.untaint # ok? return engine end ## ## helper method to convert and evaluate input text with context object. ## context may be Binding, Hash, or Object. ## def process(input, context=nil, filename=nil) code = convert(input) filename ||= '(erubis)' if context.is_a?(Binding) return eval(code, context, filename) else context = Context.new(context) if context.is_a?(Hash) return context.instance_eval(code, filename) end end ## ## helper method evaluate Proc object with contect object. ## context may be Binding, Hash, or Object. ## def process_proc(proc_obj, context=nil, filename=nil) if context.is_a?(Binding) filename ||= '(erubis)' return eval(proc_obj, context, filename) else context = Context.new(context) if context.is_a?(Hash) return context.instance_eval(&proc_obj) end end end # end of class Engine ## ## (abstract) base engine class for Eruby, Eperl, Ejava, and so on. ## subclass must include generator. ## class Basic::Engine < Engine include Evaluator include Basic::Converter include Generator end class PI::Engine < Engine include Evaluator include PI::Converter include Generator end end ruby-erubis-2.7.0/lib/erubis/engine/000077500000000000000000000000001170760342400173005ustar00rootroot00000000000000ruby-erubis-2.7.0/lib/erubis/engine/ec.rb000066400000000000000000000045701170760342400202220ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## require 'erubis/engine' require 'erubis/enhancer' module Erubis module CGenerator include Generator def self.supported_properties() # :nodoc: return [ [:indent, '', "indent spaces (ex. ' ')"], [:out, 'stdout', "output file pointer name"], ] end def init_generator(properties={}) super @escapefunc ||= "escape" @indent = properties[:indent] || '' @out = properties[:out] || 'stdout' end def add_preamble(src) src << "#line 1 \"#{self.filename}\"\n" if self.filename end def escape_text(text) @@table_ ||= { "\r"=>"\\r", "\n"=>"\\n", "\t"=>"\\t", '"'=>'\\"', "\\"=>"\\\\" } text.gsub!(/[\r\n\t"\\]/) { |m| @@table_[m] } return text end def escaped_expr(code) return "#{@escapefunc}(#{code.strip}, #{@out})" end def add_text(src, text) return if text.empty? src << (src.empty? || src[-1] == ?\n ? @indent : ' ') src << "fputs(" i = 0 text.each_line do |line| src << "\n" << @indent << ' ' if i > 0 i += 1 src << '"' << escape_text(line) << '"' end src << ", #{@out});" #<< (text[-1] == ?\n ? "\n" : "") src << "\n" if text[-1] == ?\n end def add_stmt(src, code) src << code end def add_expr_literal(src, code) src << @indent if src.empty? || src[-1] == ?\n src << " fprintf(#{@out}, " << code.strip << ');' end def add_expr_escaped(src, code) src << @indent if src.empty? || src[-1] == ?\n src << ' ' << escaped_expr(code) << ';' end def add_expr_debug(src, code) code.strip! s = nil if code =~ /\A\".*?\"\s*,\s*(.*)/ s = $1.gsub(/[%"]/, '\\\1') + '=' end src << @indent if src.empty? || src[-1] == ?\n src << " fprintf(stderr, \"*** debug: #{s}\" #{code});" end def add_postamble(src) # empty end end ## ## engine for C ## class Ec < Basic::Engine include CGenerator end class EscapedEc < Ec include EscapeEnhancer end #class XmlEc < Ec # include EscapeEnhancer #end class PI::Ec < PI::Engine include CGenerator def init_converter(properties={}) @pi = 'c' super(properties) end end end ruby-erubis-2.7.0/lib/erubis/engine/ecpp.rb000066400000000000000000000044441170760342400205620ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## require 'erubis/engine' require 'erubis/enhancer' module Erubis module CppGenerator include Generator def self.supported_properties() # :nodoc: return [ [:indent, '', "indent spaces (ex. ' ')"], [:bufvar, '_buf', "buffer variable name"], ] end def init_generator(properties={}) super @escapefunc ||= "escape" @indent = properties[:indent] || '' @bufvar = properties[:bufvar] || '_buf' end def add_preamble(src) src << "#line 1 \"#{self.filename}\"\n" if self.filename end def escape_text(text) @@table_ ||= { "\r"=>"\\r", "\n"=>"\\n", "\t"=>"\\t", '"'=>'\\"', "\\"=>"\\\\" } text.gsub!(/[\r\n\t"\\]/) { |m| @@table_[m] } return text end def escaped_expr(code) return "#{@escapefunc}(#{code.strip})" end def add_text(src, text) return if text.empty? src << (src.empty? || src[-1] == ?\n ? @indent : ' ') src << "_buf << " i = 0 text.each_line do |line| src << "\n" << @indent << " " if i > 0 i += 1 src << '"' << escape_text(line) << '"' end src << ";" #<< (text[-1] == ?\n ? "\n" : "") src << "\n" if text[-1] == ?\n end def add_stmt(src, code) src << code end def add_expr_literal(src, code) src << @indent if src.empty? || src[-1] == ?\n src << " _buf << (" << code.strip << ");" end def add_expr_escaped(src, code) src << @indent if src.empty? || src[-1] == ?\n src << ' ' << escaped_expr(code) << ';' end def add_expr_debug(src, code) code.strip! src << @indent if src.empty? || src[-1] == ?\n src << " std::cerr << \"*** debug: #{code.gsub(/(")/, '\\\&')}=\" << (#{code});" end def add_postamble(src) # empty end end ## ## engine for C ## class Ecpp < Basic::Engine include CppGenerator end class EscapedEcpp < Ecpp include EscapeEnhancer end #class XmlEcpp < Ecpp # include EscapeEnhancer #end class PI::Ecpp < PI::Engine include CppGenerator def init_converter(properties={}) @pi = 'cpp' super(properties) end end end ruby-erubis-2.7.0/lib/erubis/engine/ejava.rb000066400000000000000000000047301170760342400207170ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## require 'erubis/engine' require 'erubis/enhancer' module Erubis module JavaGenerator include Generator def self.supported_properties() # :nodoc: return [ [:indent, '', "indent spaces (ex. ' ')"], [:bufvar, '_buf', "output buffer variable name"], [:bufclass, 'StringBuffer', "output buffer class (ex. 'StringBuilder')"], ] end def init_generator(properties={}) super @escapefunc ||= 'escape' @indent = properties[:indent] || '' @bufvar = properties[:bufvar] || '_buf' @bufclass = properties[:bufclass] || 'StringBuffer' end def add_preamble(src) src << "#{@indent}#{@bufclass} #{@bufvar} = new #{@bufclass}();" end def escape_text(text) @@table_ ||= { "\r"=>"\\r", "\n"=>"\\n", "\t"=>"\\t", '"'=>'\\"', "\\"=>"\\\\" } return text.gsub!(/[\r\n\t"\\]/) { |m| @@table_[m] } || text end def add_text(src, text) return if text.empty? src << (src.empty? || src[-1] == ?\n ? @indent : ' ') src << @bufvar << ".append(" i = 0 text.each_line do |line| src << "\n" << @indent << ' + ' if i > 0 i += 1 src << '"' << escape_text(line) << '"' end src << ");" << (text[-1] == ?\n ? "\n" : "") end def add_stmt(src, code) src << code end def add_expr_literal(src, code) src << @indent if src.empty? || src[-1] == ?\n code.strip! src << " #{@bufvar}.append(#{code});" end def add_expr_escaped(src, code) add_expr_literal(src, escaped_expr(code)) end def add_expr_debug(src, code) code.strip! src << @indent if src.empty? || src[-1] == ?\n src << " System.err.println(\"*** debug: #{code}=\"+(#{code}));" end def add_postamble(src) src << "\n" if src[-1] == ?; src << @indent << "return " << @bufvar << ".toString();\n" #src << @indent << "System.out.print(" << @bufvar << ".toString());\n" end end ## ## engine for Java ## class Ejava < Basic::Engine include JavaGenerator end class EscapedEjava < Ejava include EscapeEnhancer end #class XmlEjava < Ejava # include EscapeEnhancer #end class PI::Ejava < PI::Engine include JavaGenerator def init_converter(properties={}) @pi = 'java' super(properties) end end end ruby-erubis-2.7.0/lib/erubis/engine/ejavascript.rb000066400000000000000000000047721170760342400221520ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## require 'erubis/engine' require 'erubis/enhancer' module Erubis module JavascriptGenerator include Generator def self.supported_properties() # :nodoc: list = [] #list << [:indent, '', "indent spaces (ex. ' ')"] #list << [:bufvar, '_buf', "output buffer variable name"] list << [:docwrite, true, "use 'document.write()' when true"] return list end def init_generator(properties={}) super @escapefunc ||= 'escape' @indent = properties[:indent] || '' @bufvar = properties[:bufvar] || '_buf' @docwrite = properties[:docwrite] != false # '!= false' will be removed in the next release end def add_preamble(src) src << "#{@indent}var #{@bufvar} = [];" end def escape_text(text) @@table_ ||= { "\r"=>"\\r", "\n"=>"\\n\\\n", "\t"=>"\\t", '"'=>'\\"', "\\"=>"\\\\" } return text.gsub!(/[\r\n\t"\\]/) { |m| @@table_[m] } || text end def add_indent(src, indent) src << (src.empty? || src[-1] == ?\n ? indent : ' ') end def add_text(src, text) return if text.empty? add_indent(src, @indent) src << @bufvar << '.push("' s = escape_text(text) if s[-1] == ?\n s[-2, 2] = '' src << s << "\");\n" else src << s << "\");" end end def add_stmt(src, code) src << code end def add_expr_literal(src, code) add_indent(src, @indent) code.strip! src << "#{@bufvar}.push(#{code});" end def add_expr_escaped(src, code) add_expr_literal(src, escaped_expr(code)) end def add_expr_debug(src, code) add_indent(src, @indent) code.strip! src << "alert(\"*** debug: #{code}=\"+(#{code}));" end def add_postamble(src) src << "\n" if src[-1] == ?; if @docwrite src << @indent << 'document.write(' << @bufvar << ".join(\"\"));\n" else src << @indent << @bufvar << ".join(\"\");\n" end end end ## ## engine for JavaScript ## class Ejavascript < Basic::Engine include JavascriptGenerator end class EscapedEjavascript < Ejavascript include EscapeEnhancer end #class XmlEjavascript < Ejavascript # include EscapeEnhancer #end class PI::Ejavascript < PI::Engine include JavascriptGenerator def init_converter(properties={}) @pi = 'js' super(properties) end end end ruby-erubis-2.7.0/lib/erubis/engine/enhanced.rb000066400000000000000000000033361170760342400213770ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## require 'erubis/enhancer' require 'erubis/engine/eruby' module Erubis #-- ## moved to engine/ruby.rb #class EscapedEruby < Eruby # include EscapeEnhancer #end #++ #-- ### (obsolete) #class FastEruby < Eruby # include FastEnhancer #end #++ class StdoutEruby < Eruby include StdoutEnhancer end class PrintOutEruby < Eruby include PrintOutEnhancer end class PrintEnabledEruby < Eruby include PrintEnabledEnhancer end class ArrayEruby < Eruby include ArrayEnhancer end class ArrayBufferEruby < Eruby include ArrayBufferEnhancer end class StringBufferEruby < Eruby include StringBufferEnhancer end class StringIOEruby < Eruby include StringIOEnhancer end class ErboutEruby < Eruby include ErboutEnhancer end class NoTextEruby < Eruby include NoTextEnhancer end class NoCodeEruby < Eruby include NoCodeEnhancer end class SimplifiedEruby < Eruby include SimplifyEnhancer end class StdoutSimplifiedEruby < Eruby include StdoutEnhancer include SimplifyEnhancer end class PrintOutSimplifiedEruby < Eruby include PrintOutEnhancer include SimplifyEnhancer end class BiPatternEruby < Eruby include BiPatternEnhancer end class PercentLineEruby < Eruby include PercentLineEnhancer end class PrefixedLineEruby < Eruby include PrefixedLineEnhancer end class HeaderFooterEruby < Eruby include HeaderFooterEnhancer end class DeleteIndentEruby < Eruby include DeleteIndentEnhancer end class InterpolationEruby < Eruby include InterpolationEnhancer end end ruby-erubis-2.7.0/lib/erubis/engine/eperl.rb000066400000000000000000000031431170760342400207350ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## require 'erubis/engine' require 'erubis/enhancer' module Erubis module PerlGenerator include Generator def self.supported_properties() # :nodoc: return [ [:func, 'print', "function name"], ] end def init_generator(properties={}) super @escapefunc ||= 'encode_entities' @func = properties[:func] || 'print' end def add_preamble(src) src << "use HTML::Entities; "; end def escape_text(text) return text.gsub!(/['\\]/, '\\\\\&') || text end def add_text(src, text) src << @func << "('" << escape_text(text) << "'); " unless text.empty? end def add_expr_literal(src, code) code.strip! src << @func << "(" << code << "); " end def add_expr_escaped(src, code) add_expr_literal(src, escaped_expr(code)) end def add_expr_debug(src, code) code.strip! s = code.gsub(/\'/, "\\'") src << @func << "('*** debug: #{code}=', #{code}, \"\\n\");" end def add_stmt(src, code) src << code end def add_postamble(src) src << "\n" unless src[-1] == ?\n end end ## ## engine for Perl ## class Eperl < Basic::Engine include PerlGenerator end class EscapedEperl < Eperl include EscapeEnhancer end #class XmlEperl < Eperl # include EscapeEnhancer #end class PI::Eperl < PI::Engine include PerlGenerator def init_converter(properties={}) @pi = 'perl' super(properties) end end end ruby-erubis-2.7.0/lib/erubis/engine/ephp.rb000066400000000000000000000030701170760342400205610ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## require 'erubis/engine' require 'erubis/enhancer' module Erubis module PhpGenerator include Generator def self.supported_properties() # :nodoc: return [] end def init_generator(properties={}) super @escapefunc ||= 'htmlspecialchars' end def add_preamble(src) # empty end def escape_text(text) return text.gsub!(/<\?xml\b/, '<?xml') || text end def add_text(src, text) src << escape_text(text) end def add_expr_literal(src, code) code.strip! src << "" end def add_expr_escaped(src, code) add_expr_literal(src, escaped_expr(code)) end def add_expr_debug(src, code) code.strip! s = code.gsub(/\'/, "\\'") src << "" end def add_stmt(src, code) src << "\n" else src << code << "?>" end end def add_postamble(src) # empty end end ## ## engine for PHP ## class Ephp < Basic::Engine include PhpGenerator end class EscapedEphp < Ephp include EscapeEnhancer end #class XmlEphp < Ephp # include EscapeEnhancer #end class PI::Ephp < PI::Engine include PhpGenerator def init_converter(properties={}) @pi = 'php' super(properties) end end end ruby-erubis-2.7.0/lib/erubis/engine/eruby.rb000066400000000000000000000043541170760342400207610ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## require 'erubis/engine' require 'erubis/enhancer' module Erubis ## ## code generator for Ruby ## module RubyGenerator include Generator #include ArrayBufferEnhancer include StringBufferEnhancer def init_generator(properties={}) super @escapefunc ||= "Erubis::XmlHelper.escape_xml" @bufvar = properties[:bufvar] || "_buf" end def self.supported_properties() # :nodoc: return [] end def escape_text(text) text.gsub(/['\\]/, '\\\\\&') # "'" => "\\'", '\\' => '\\\\' end def escaped_expr(code) return "#{@escapefunc}(#{code})" end #-- #def add_preamble(src) # src << "#{@bufvar} = [];" #end #++ def add_text(src, text) src << " #{@bufvar} << '" << escape_text(text) << "';" unless text.empty? end def add_stmt(src, code) #src << code << ';' src << code src << ';' unless code[-1] == ?\n end def add_expr_literal(src, code) src << " #{@bufvar} << (" << code << ').to_s;' end def add_expr_escaped(src, code) src << " #{@bufvar} << " << escaped_expr(code) << ';' end def add_expr_debug(src, code) code.strip! s = (code.dump =~ /\A"(.*)"\z/) && $1 src << ' $stderr.puts("*** debug: ' << s << '=#{(' << code << ').inspect}");' end #-- #def add_postamble(src) # src << "\n#{@bufvar}.join\n" #end #++ end ## ## engine for Ruby ## class Eruby < Basic::Engine include RubyEvaluator include RubyGenerator end ## ## fast engine for Ruby ## class FastEruby < Eruby include InterpolationEnhancer end ## ## swtich '<%= %>' to escaped and '<%== %>' to not escaped ## class EscapedEruby < Eruby include EscapeEnhancer end ## ## sanitize expression (<%= ... %>) by default ## ## this is equivalent to EscapedEruby and is prepared only for compatibility. ## class XmlEruby < Eruby include EscapeEnhancer end class PI::Eruby < PI::Engine include RubyEvaluator include RubyGenerator def init_converter(properties={}) @pi = 'rb' super(properties) end end end ruby-erubis-2.7.0/lib/erubis/engine/escheme.rb000066400000000000000000000043231170760342400212400ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## require 'erubis/engine' require 'erubis/enhancer' module Erubis module SchemeGenerator include Generator def self.supported_properties() # :nodoc: return [ [:func, '_add', "function name (ex. 'display')"], ] end def init_generator(properties={}) super @escapefunc ||= 'escape' @func = properties[:func] || '_add' # or 'display' end def add_preamble(src) return unless @func == '_add' src << "(let ((_buf '())) " + \ "(define (_add x) (set! _buf (cons x _buf))) " #src << "(let* ((_buf '())" + \ # " (_add (lambda (x) (set! _buf (cons x _buf))))) " end def escape_text(text) @table_ ||= { '"'=>'\\"', '\\'=>'\\\\' } text.gsub!(/["\\]/) { |m| @table_[m] } return text end def escaped_expr(code) code.strip! return "(#{@escapefunc} #{code})" end def add_text(src, text) return if text.empty? t = escape_text(text) if t[-1] == ?\n t[-1, 1] = '' src << "(#{@func} \"" << t << "\\n\")\n" else src << "(#{@func} \"" << t << '")' end end def add_stmt(src, code) src << code end def add_expr_literal(src, code) code.strip! src << "(#{@func} #{code})" end def add_expr_escaped(src, code) add_expr_literal(src, escaped_expr(code)) end def add_expr_debug(src, code) s = (code.strip! || code).gsub(/\"/, '\\"') src << "(display \"*** debug: #{s}=\")(display #{code.strip})(display \"\\n\")" end def add_postamble(src) return unless @func == '_add' src << "\n" unless src[-1] == ?\n src << " (reverse _buf))\n" end end ## ## engine for Scheme ## class Escheme < Basic::Engine include SchemeGenerator end class EscapedEscheme < Escheme include EscapeEnhancer end #class XmlEscheme < Escheme # include EscapeEnhancer #end class PI::Escheme < PI::Engine include SchemeGenerator def init_converter(properties={}) @pi = 'scheme' super(properties) end end end ruby-erubis-2.7.0/lib/erubis/engine/optimized.rb000066400000000000000000000052021170760342400216300ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## require 'erubis/engine/eruby' module Erubis module OptimizedGenerator include Generator def self.supported_properties() # :nodoc: return [] end def init_generator(properties={}) super @escapefunc ||= "Erubis::XmlHelper.escape_xml" @initialized = false @prev_is_expr = false end protected def escape_text(text) text.gsub(/['\\]/, '\\\\\&') # "'" => "\\'", '\\' => '\\\\' end def escaped_expr(code) @escapefunc ||= 'Erubis::XmlHelper.escape_xml' return "#{@escapefunc}(#{code})" end def switch_to_expr(src) return if @prev_is_expr @prev_is_expr = true src << ' _buf' end def switch_to_stmt(src) return unless @prev_is_expr @prev_is_expr = false src << ';' end def add_preamble(src) #@initialized = false #@prev_is_expr = false end def add_text(src, text) return if text.empty? if @initialized switch_to_expr(src) src << " << '" << escape_text(text) << "'" else src << "_buf = '" << escape_text(text) << "';" @initialized = true end end def add_stmt(src, code) switch_to_stmt(src) if @initialized #super src << code src << ';' unless code[-1] == ?\n end def add_expr_literal(src, code) unless @initialized; src << "_buf = ''"; @initialized = true; end switch_to_expr(src) src << " << (" << code << ").to_s" end def add_expr_escaped(src, code) unless @initialized; src << "_buf = ''"; @initialized = true; end switch_to_expr(src) src << " << " << escaped_expr(code) end def add_expr_debug(src, code) code.strip! s = (code.dump =~ /\A"(.*)"\z/) && $1 src << ' $stderr.puts("*** debug: ' << s << '=#{(' << code << ').inspect}");' end def add_postamble(src) #super if @initialized src << "\n_buf\n" if @initialized end end # end of class OptimizedEruby ## ## Eruby class which generates optimized ruby code ## class OptimizedEruby < Basic::Engine # Eruby include RubyEvaluator include OptimizedGenerator def init_converter(properties={}) @pi = 'rb' super(properties) end end ## ## XmlEruby class which generates optimized ruby code ## class OptimizedXmlEruby < OptimizedEruby include EscapeEnhancer def add_expr_debug(src, code) switch_to_stmt(src) if indicator == '===' && !@initialized super end end # end of class OptimizedXmlEruby end ruby-erubis-2.7.0/lib/erubis/enhancer.rb000066400000000000000000000370771170760342400201610ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## module Erubis ## ## switch '<%= ... %>' to escaped and '<%== ... %>' to unescaped ## ## ex. ## class XmlEruby < Eruby ## include EscapeEnhancer ## end ## ## this is language-indenedent. ## module EscapeEnhancer def self.desc # :nodoc: "switch '<%= %>' to escaped and '<%== %>' to unescaped" end #-- #def self.included(klass) # klass.class_eval <<-END # alias _add_expr_literal add_expr_literal # alias _add_expr_escaped add_expr_escaped # alias add_expr_literal _add_expr_escaped # alias add_expr_escaped _add_expr_literal # END #end #++ def add_expr(src, code, indicator) case indicator when '=' @escape ? add_expr_literal(src, code) : add_expr_escaped(src, code) when '==' @escape ? add_expr_escaped(src, code) : add_expr_literal(src, code) when '===' add_expr_debug(src, code) end end end #-- ## (obsolete) #module FastEnhancer #end #++ ## ## use $stdout instead of string ## ## this is only for Eruby. ## module StdoutEnhancer def self.desc # :nodoc: "use $stdout instead of array buffer or string buffer" end def add_preamble(src) src << "#{@bufvar} = $stdout;" end def add_postamble(src) src << "\n''\n" end end ## ## use print statement instead of '_buf << ...' ## ## this is only for Eruby. ## module PrintOutEnhancer def self.desc # :nodoc: "use print statement instead of '_buf << ...'" end def add_preamble(src) end def add_text(src, text) src << " print '#{escape_text(text)}';" unless text.empty? end def add_expr_literal(src, code) src << " print((#{code}).to_s);" end def add_expr_escaped(src, code) src << " print #{escaped_expr(code)};" end def add_postamble(src) src << "\n" unless src[-1] == ?\n end end ## ## enable print function ## ## Notice: use Eruby#evaluate() and don't use Eruby#result() ## to be enable print function. ## ## this is only for Eruby. ## module PrintEnabledEnhancer def self.desc # :nodoc: "enable to use print function in '<% %>'" end def add_preamble(src) src << "@_buf = " super end def print(*args) args.each do |arg| @_buf << arg.to_s end end def evaluate(context=nil) _src = @src if context.is_a?(Hash) context.each do |key, val| instance_variable_set("@#{key}", val) end elsif context context.instance_variables.each do |name| instance_variable_set(name, context.instance_variable_get(name)) end end return instance_eval(_src, (@filename || '(erubis)')) end end ## ## return array instead of string ## ## this is only for Eruby. ## module ArrayEnhancer def self.desc # :nodoc: "return array instead of string" end def add_preamble(src) src << "#{@bufvar} = [];" end def add_postamble(src) src << "\n" unless src[-1] == ?\n src << "#{@bufvar}\n" end end ## ## use an Array object as buffer (included in Eruby by default) ## ## this is only for Eruby. ## module ArrayBufferEnhancer def self.desc # :nodoc: "use an Array object for buffering (included in Eruby class)" end def add_preamble(src) src << "_buf = [];" end def add_postamble(src) src << "\n" unless src[-1] == ?\n src << "_buf.join\n" end end ## ## use String class for buffering ## ## this is only for Eruby. ## module StringBufferEnhancer def self.desc # :nodoc: "use a String object for buffering" end def add_preamble(src) src << "#{@bufvar} = '';" end def add_postamble(src) src << "\n" unless src[-1] == ?\n src << "#{@bufvar}.to_s\n" end end ## ## use StringIO class for buffering ## ## this is only for Eruby. ## module StringIOEnhancer # :nodoc: def self.desc # :nodoc: "use a StringIO object for buffering" end def add_preamble(src) src << "#{@bufvar} = StringIO.new;" end def add_postamble(src) src << "\n" unless src[-1] == ?\n src << "#{@bufvar}.string\n" end end ## ## set buffer variable name to '_erbout' as well as '_buf' ## ## this is only for Eruby. ## module ErboutEnhancer def self.desc # :nodoc: "set '_erbout = _buf = \"\";' to be compatible with ERB." end def add_preamble(src) src << "_erbout = #{@bufvar} = '';" end def add_postamble(src) src << "\n" unless src[-1] == ?\n src << "#{@bufvar}.to_s\n" end end ## ## remove text and leave code, especially useful when debugging. ## ## ex. ## $ erubis -s -E NoText file.eruby | more ## ## this is language independent. ## module NoTextEnhancer def self.desc # :nodoc: "remove text and leave code (useful when debugging)" end def add_text(src, text) src << ("\n" * text.count("\n")) if text[-1] != ?\n text =~ /^(.*?)\z/ src << (' ' * $1.length) end end end ## ## remove code and leave text, especially useful when validating HTML tags. ## ## ex. ## $ erubis -s -E NoCode file.eruby | tidy -errors ## ## this is language independent. ## module NoCodeEnhancer def self.desc # :nodoc: "remove code and leave text (useful when validating HTML)" end def add_preamble(src) end def add_postamble(src) end def add_text(src, text) src << text end def add_expr(src, code, indicator) src << "\n" * code.count("\n") end def add_stmt(src, code) src << "\n" * code.count("\n") end end ## ## get convert faster, but spaces around '<%...%>' are not trimmed. ## ## this is language-independent. ## module SimplifyEnhancer def self.desc # :nodoc: "get convert faster but leave spaces around '<% %>'" end #DEFAULT_REGEXP = /(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m SIMPLE_REGEXP = /<%(=+|\#)?(.*?)-?%>/m def convert(input) src = "" add_preamble(src) #regexp = pattern_regexp(@pattern) pos = 0 input.scan(SIMPLE_REGEXP) do |indicator, code| match = Regexp.last_match index = match.begin(0) text = input[pos, index - pos] pos = match.end(0) add_text(src, text) if !indicator # <% %> add_stmt(src, code) elsif indicator[0] == ?\# # <%# %> n = code.count("\n") add_stmt(src, "\n" * n) else # <%= %> add_expr(src, code, indicator) end end #rest = $' || input # ruby1.8 rest = pos == 0 ? input : input[pos..-1] # ruby1.9 add_text(src, rest) add_postamble(src) return src end end ## ## enable to use other embedded expression pattern (default is '\[= =\]'). ## ## notice! this is an experimental. spec may change in the future. ## ## ex. ## input = < ## <%= item %> : <%== item %> ## [= item =] : [== item =] ## <% end %> ## END ## ## class BiPatternEruby ## include BiPatternEnhancer ## end ## eruby = BiPatternEruby.new(input, :bipattern=>'\[= =\]') ## list = ['', 'b&b', '"c"'] ## print eruby.result(binding()) ## ## ## output ## : <a> ## : <a> ## b&b : b&b ## b&b : b&b ## "c" : "c" ## "c" : "c" ## ## this is language independent. ## module BiPatternEnhancer def self.desc # :nodoc: "another embedded expression pattern (default '\[= =\]')." end def initialize(input, properties={}) self.bipattern = properties[:bipattern] # or '\$\{ \}' super end ## when pat is nil then '\[= =\]' is used def bipattern=(pat) # :nodoc: @bipattern = pat || '\[= =\]' pre, post = @bipattern.split() @bipattern_regexp = /(.*?)#{pre}(=*)(.*?)#{post}/m end def add_text(src, text) return unless text m = nil text.scan(@bipattern_regexp) do |txt, indicator, code| m = Regexp.last_match super(src, txt) add_expr(src, code, '=' + indicator) end #rest = $' || text # ruby1.8 rest = m ? text[m.end(0)..-1] : text # ruby1.9 super(src, rest) end end ## ## regards lines starting with '^[ \t]*%' as program code ## ## in addition you can specify prefix character (default '%') ## ## this is language-independent. ## module PrefixedLineEnhancer def self.desc # :nodoc: "regard lines matched to '^[ \t]*%' as program code" end def init_generator(properties={}) super @prefixchar = properties[:prefixchar] end def add_text(src, text) unless @prefixrexp @prefixchar ||= '%' @prefixrexp = Regexp.compile("^([ \\t]*)\\#{@prefixchar}(.*?\\r?\\n)") end pos = 0 text2 = '' text.scan(@prefixrexp) do space = $1 line = $2 space, line = '', $1 unless $2 match = Regexp.last_match len = match.begin(0) - pos str = text[pos, len] pos = match.end(0) if text2.empty? text2 = str else text2 << str end if line[0, 1] == @prefixchar text2 << space << line else super(src, text2) text2 = '' add_stmt(src, space + line) end end #rest = pos == 0 ? text : $' # ruby1.8 rest = pos == 0 ? text : text[pos..-1] # ruby1.9 unless text2.empty? text2 << rest if rest rest = text2 end super(src, rest) end end ## ## regards lines starting with '%' as program code ## ## this is for compatibility to eruby and ERB. ## ## this is language-independent. ## module PercentLineEnhancer include PrefixedLineEnhancer def self.desc # :nodoc: "regard lines starting with '%' as program code" end #-- #def init_generator(properties={}) # super # @prefixchar = '%' # @prefixrexp = /^\%(.*?\r?\n)/ #end #++ def add_text(src, text) unless @prefixrexp @prefixchar = '%' @prefixrexp = /^\%(.*?\r?\n)/ end super(src, text) end end ## ## [experimental] allow header and footer in eRuby script ## ## ex. ## ==================== ## ## without header and footer ## $ cat ex1.eruby ## <% def list_items(list) %> ## <% for item in list %> ##
  • <%= item %>
  • ## <% end %> ## <% end %> ## ## $ erubis -s ex1.eruby ## _buf = []; def list_items(list) ## ; for item in list ## ; _buf << '
  • '; _buf << ( item ).to_s; _buf << '
  • ## '; end ## ; end ## ; ## _buf.join ## ## ## with header and footer ## $ cat ex2.eruby ## ## <% for item in list %> ##
  • <%= item %>
  • ## <% end %> ## ## ## $ erubis -s -c HeaderFooterEruby ex4.eruby ## ## def list_items(list) ## _buf = []; _buf << ' ## '; for item in list ## ; _buf << '
  • '; _buf << ( item ).to_s; _buf << '
  • ## '; end ## ; _buf << ' ## '; ## _buf.join ## end ## ## ==================== ## ## this is language-independent. ## module HeaderFooterEnhancer def self.desc # :nodoc: "allow header/footer in document (ex. '')" end HEADER_FOOTER_PATTERN = /(.*?)(^[ \t]*)?([ \t]*\r?\n)?/m def add_text(src, text) m = nil text.scan(HEADER_FOOTER_PATTERN) do |txt, lspace, word, content, rspace| m = Regexp.last_match flag_trim = @trim && lspace && rspace super(src, txt) content = "#{lspace}#{content}#{rspace}" if flag_trim super(src, lspace) if !flag_trim && lspace instance_variable_set("@#{word}", content) super(src, rspace) if !flag_trim && rspace end #rest = $' || text # ruby1.8 rest = m ? text[m.end(0)..-1] : text # ruby1.9 super(src, rest) end attr_accessor :header, :footer def convert(input) source = super return @src = "#{@header}#{source}#{@footer}" end end ## ## delete indentation of HTML. ## ## this is language-independent. ## module DeleteIndentEnhancer def self.desc # :nodoc: "delete indentation of HTML." end def convert_input(src, input) input = input.gsub(/^[ \t]+<%=title%>" into "_buf << %Q`

    #{title}

    `" ## ## this is only for Eruby. ## module InterpolationEnhancer def self.desc # :nodoc: "convert '

    <%=text%>

    ' into '_buf << %Q`

    \#{text}

    `'" end def convert_input(src, input) pat = @pattern regexp = pat.nil? || pat == '<% %>' ? Basic::Converter::DEFAULT_REGEXP : pattern_regexp(pat) pos = 0 is_bol = true # is beginning of line str = '' input.scan(regexp) do |indicator, code, tailch, rspace| match = Regexp.last_match() len = match.begin(0) - pos text = input[pos, len] pos = match.end(0) ch = indicator ? indicator[0] : nil lspace = ch == ?= ? nil : detect_spaces_at_bol(text, is_bol) is_bol = rspace ? true : false _add_text_to_str(str, text) ## * when '<%= %>', do nothing ## * when '<% %>' or '<%# %>', delete spaces iff only spaces are around '<% %>' if ch == ?= # <%= %> rspace = nil if tailch && !tailch.empty? str << lspace if lspace add_expr(str, code, indicator) str << rspace if rspace elsif ch == ?\# # <%# %> n = code.count("\n") + (rspace ? 1 : 0) if @trim && lspace && rspace add_text(src, str) str = '' add_stmt(src, "\n" * n) else str << lspace if lspace add_text(src, str) str = '' add_stmt(src, "\n" * n) str << rspace if rspace end else # <% %> if @trim && lspace && rspace add_text(src, str) str = '' add_stmt(src, "#{lspace}#{code}#{rspace}") else str << lspace if lspace add_text(src, str) str = '' add_stmt(src, code) str << rspace if rspace end end end #rest = $' || input # ruby1.8 rest = pos == 0 ? input : input[pos..-1] # ruby1.9 _add_text_to_str(str, rest) add_text(src, str) end def add_text(src, text) return if !text || text.empty? #src << " _buf << %Q`" << text << "`;" if text[-1] == ?\n text[-1] = "\\n" src << " #{@bufvar} << %Q`#{text}`\n" else src << " #{@bufvar} << %Q`#{text}`;" end end def _add_text_to_str(str, text) return if !text || text.empty? str << text.gsub(/[`\#\\]/, '\\\\\&') end def add_expr_escaped(str, code) str << "\#{#{escaped_expr(code)}}" end def add_expr_literal(str, code) str << "\#{#{code}}" end end end ruby-erubis-2.7.0/lib/erubis/error.rb000066400000000000000000000004511170760342400175110ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## module Erubis ## ## base error class ## class ErubisError < StandardError end ## ## raised when method or function is not supported ## class NotSupportedError < ErubisError end end ruby-erubis-2.7.0/lib/erubis/evaluator.rb000066400000000000000000000042431170760342400203650ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## require 'erubis/error' require 'erubis/context' module Erubis EMPTY_BINDING = binding() ## ## evaluate code ## module Evaluator def self.supported_properties # :nodoc: return [] end attr_accessor :src, :filename def init_evaluator(properties) @filename = properties[:filename] end def result(*args) raise NotSupportedError.new("evaluation of code except Ruby is not supported.") end def evaluate(*args) raise NotSupportedError.new("evaluation of code except Ruby is not supported.") end end ## ## evaluator for Ruby ## module RubyEvaluator include Evaluator def self.supported_properties # :nodoc: list = Evaluator.supported_properties return list end ## eval(@src) with binding object def result(_binding_or_hash=TOPLEVEL_BINDING) _arg = _binding_or_hash if _arg.is_a?(Hash) _b = binding() eval _arg.collect{|k,v| "#{k} = _arg[#{k.inspect}]; "}.join, _b elsif _arg.is_a?(Binding) _b = _arg elsif _arg.nil? _b = binding() else raise ArgumentError.new("#{self.class.name}#result(): argument should be Binding or Hash but passed #{_arg.class.name} object.") end return eval(@src, _b, (@filename || '(erubis')) end ## invoke context.instance_eval(@src) def evaluate(_context=Context.new) _context = Context.new(_context) if _context.is_a?(Hash) #return _context.instance_eval(@src, @filename || '(erubis)') #@_proc ||= eval("proc { #{@src} }", Erubis::EMPTY_BINDING, @filename || '(erubis)') @_proc ||= eval("proc { #{@src} }", binding(), @filename || '(erubis)') return _context.instance_eval(&@_proc) end ## if object is an Class or Module then define instance method to it, ## else define singleton method to it. def def_method(object, method_name, filename=nil) m = object.is_a?(Module) ? :module_eval : :instance_eval object.__send__(m, "def #{method_name}; #{@src}; end", filename || @filename || '(erubis)') end end end ruby-erubis-2.7.0/lib/erubis/generator.rb000066400000000000000000000033431170760342400203510ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## require 'erubis/util' module Erubis ## ## code generator, called by Converter module ## module Generator def self.supported_properties() # :nodoc: return [ [:escapefunc, nil, "escape function name"], ] end attr_accessor :escapefunc def init_generator(properties={}) @escapefunc = properties[:escapefunc] end ## (abstract) escape text string ## ## ex. ## def escape_text(text) ## return text.dump ## # or return "'" + text.gsub(/['\\]/, '\\\\\&') + "'" ## end def escape_text(text) not_implemented end ## return escaped expression code (ex. 'h(...)' or 'htmlspecialchars(...)') def escaped_expr(code) code.strip! return "#{@escapefunc}(#{code})" end ## (abstract) add @preamble to src def add_preamble(src) not_implemented end ## (abstract) add text string to src def add_text(src, text) not_implemented end ## (abstract) add statement code to src def add_stmt(src, code) not_implemented end ## (abstract) add expression literal code to src. this is called by add_expr(). def add_expr_literal(src, code) not_implemented end ## (abstract) add escaped expression code to src. this is called by add_expr(). def add_expr_escaped(src, code) not_implemented end ## (abstract) add expression code to src for debug. this is called by add_expr(). def add_expr_debug(src, code) not_implemented end ## (abstract) add @postamble to src def add_postamble(src) not_implemented end end end ruby-erubis-2.7.0/lib/erubis/helper.rb000066400000000000000000000015201170760342400176350ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## module Erubis ## ## helper for xml ## module XmlHelper module_function ESCAPE_TABLE = { '&' => '&', '<' => '<', '>' => '>', '"' => '"', "'" => ''', } def escape_xml(value) value.to_s.gsub(/[&<>"]/) { |s| ESCAPE_TABLE[s] } # or /[&<>"']/ #value.to_s.gsub(/[&<>"]/) { ESCAPE_TABLE[$&] } end def escape_xml2(value) return value.to_s.gsub(/\&/,'&').gsub(//,'>').gsub(/"/,'"') end alias h escape_xml alias html_escape escape_xml def url_encode(str) return str.gsub(/[^-_.a-zA-Z0-9]+/) { |s| s.unpack('C*').collect { |i| "%%%02X" % i }.join } end alias u url_encode end end ruby-erubis-2.7.0/lib/erubis/helpers/000077500000000000000000000000001170760342400174755ustar00rootroot00000000000000ruby-erubis-2.7.0/lib/erubis/helpers/rails_form_helper.rb000066400000000000000000000153321170760342400235220ustar00rootroot00000000000000### ### $Release: 2.7.0 $ ### copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ### module Erubis module Helpers module RailsFormHelper end end end module Erubis::Helpers::RailsFormHelper if ActionPack::VERSION::MAJOR == 1 ### Rails 1.X def pp_template_filename(basename) return "#{RAILS_ROOT}/app/views/#{controller.controller_name}/#{basename}.rhtml" end else ### Rails 2.X def pp_template_filename(basename) fname = "#{RAILS_ROOT}/app/views/#{controller.controller_name}/#{basename}.html.erb" return fname if test(?f, fname) return "#{RAILS_ROOT}/app/views/#{controller.controller_name}/#{basename}.rhtml" end end def pp_render_partial(basename) basename = "_#{basename}" unless basename[0] == ?_ filename = pp_template_filename(basename) preprocessor = _create_preprocessor(File.read(filename)) return preprocessor.evaluate(_preprocessing_context_object()) end def pp_error_on(object_name, method) s = '' s << "<% _stag, _etag = _pp_error_tags(@#{object_name}.errors.on('#{method}')) %>" s << "<%= _stag %>" s << yield(object_name, method) s << "<%= _etag %>" return s end def _pp_error_tags(value) return value ? ['
    ', '
    '] : ['', ''] end def _pp_remove_error_div(s) s.sub!(/\A
    (.*)<\/div>\z/, '\1') return s end def pp_tag_helper(helper, object_name, method, options={}) if object_name.is_a?(ActionView::Helpers::FormHelper) object_name = object_name.object_name end unless options.key?(:value) || options.key?('value') options['value'] = _?("h @#{object_name}.#{method}") end #$stderr.puts "*** debug: pp_tag_helper(): options=#{options.inspect}" return pp_error_on(object_name, method) { s = __send__(helper, object_name, method, options) _pp_remove_error_div(s) } end def pp_form_tag(url_for_options={}, options={}, *parameters_for_url, &block) return form_tag(url_for_options, options, *parameters_for_url, &block) end #-- #def pp_form_for(object_name, *args, &block) # return form_for(object_name, *args, &block) #end #++ def pp_text_field(object_name, method, options={}) return pp_tag_helper(:text_field, object_name, method, options) end def pp_password_field(object_name, method, options={}) return pp_tag_helper(:password_field, object_name, method, options) end def pp_hidden_field(object_name, method, options={}) return pp_tag_helper(:hidden_field, object_name, method, options) end def pp_file_field(object_name, method, options={}) return pp_tag_helper(:file_field, object_name, method, options) end def pp_text_area(object_name, method, options={}) return pp_tag_helper(:text_area, object_name, method, options) end def pp_check_box(object_name, method, options={}, checked_value="1", unchecked_value="0") s = check_box(object_name, method, options, checked_value, unchecked_value) s.sub!(/\schecked=\"checked\"/, '') s.sub!(/type="checkbox"/, "\\&<%= _pp_check_box_checked?(@#{object_name}.#{method}, #{checked_value.inspect}) ? ' checked=\"checked\"' : '' %>") return pp_error_on(object_name, method) { _pp_remove_error_div(s) } end def _pp_check_box_checked?(value, checked_value) return ActionView::Helpers::InstanceTag::check_box_checked?(value, checked_value) end def pp_radio_button(object_name, method, tag_value, options={}) s = radio_button(object_name, method, tag_value, options) s.sub!(/\schecked=\"checked\"/, '') s.sub!(/type="radio"/, "\\&<%= _pp_radio_button_checked?(@#{object_name}.#{method}, #{tag_value.inspect}) ? ' checked=\"checked\"' : '' %>") return pp_error_on(object_name, method) { _pp_remove_error_div(s) } end def _pp_radio_button_checked?(value, tag_value) return ActionView::Helpers::InstanceTag::radio_button_checked?(value, tag_value) end def _pp_select(object, method, collection, priority_collection, options={}, html_options={}) return pp_error_on(object, method) do s = "" ## start tag s << "" s end end def _pp_select_options(s, collection, selected, operator) for item in collection value, text = item.is_a?(Array) ? item : [item, item] if !selected t = '' elsif operator == 'delete' t = "<%= _table.delete(#{value.inspect}) %>" else t = "<%= _table[#{value.inspect}] %>" end s << "\n" end end def pp_select(object, method, collection, options={}, html_options={}) return _pp_select(object, method, collection, nil, options, html_options) end def pp_collection_select(object, method, collection, value_method, text_method, options={}, html_options={}) collection2 = collection.collect { |e| [e.__send__(value_method), e.__send__(text_method)] } return _pp_select(object, method, collection2, nil, options, html_options) end def pp_country_select(object, method, priority_countries=nil, options={}, html_options={}) collection = ActionView::Helpers::FormOptionsHelper::COUNTRIES return _pp_select(object, method, collection, priority_countries, options, html_options) end def pp_time_zone_select(object, method, priority_zones=nil, options={}, html_options={}) model = options[:model] || options['model'] || TimeZone collection = model.all.collect { |e| [e.name, e.to_s] } return _pp_select(object, method, collection, priority_zones, options, html_options) end def pp_submit_tag(value="Save changes", options={}) return submit_tag(value, options) end def pp_image_submit_tag(source, options={}) return image_submit_tag(source, options) end end ruby-erubis-2.7.0/lib/erubis/helpers/rails_helper.rb000066400000000000000000000266341170760342400225060ustar00rootroot00000000000000### ### $Release: 2.7.0 $ ### copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ### require 'erubis' require 'erubis/preprocessing' module Erubis class Eruby include ErboutEnhancer # will generate '_erbout = _buf = ""; ' end class FastEruby include ErboutEnhancer # will generate '_erbout = _buf = ""; ' end module Helpers ## ## helper module for Ruby on Rails ## ## howto: ## ## 1. add the folliwng code in your 'config/environment.rb' ## ## require 'erubis/helpers/rails_helper' ## #Erubis::Helpers::RailsHelper.engine_class = Erubis::Eruby # or Erubis::FastEruby ## #Erubis::Helpers::RailsHelper.init_properties = {} ## #Erubis::Helpers::RailsHelper.show_src = false # set true for debugging ## #Erubis::Helpers::RailsHelper.preprocessing = true # set true to enable preprocessing ## ## 2. restart web server. ## ## if Erubis::Helper::Rails.show_src is true, Erubis prints converted Ruby code ## into log file ('log/development.log' or so). if false, it doesn't. ## if nil, Erubis prints converted Ruby code if ENV['RAILS_ENV'] == 'development'. ## module RailsHelper #cattr_accessor :init_properties @@engine_class = ::Erubis::Eruby #@@engine_class = ::Erubis::FastEruby def self.engine_class @@engine_class end def self.engine_class=(klass) @@engine_class = klass end #cattr_accessor :init_properties @@init_properties = {} def self.init_properties @@init_properties end def self.init_properties=(hash) @@init_properties = hash end #cattr_accessor :show_src @@show_src = nil def self.show_src @@show_src end def self.show_src=(flag) @@show_src = flag end #cattr_accessor :preprocessing @@preprocessing = false def self.preprocessing @@preprocessing end def self.preprocessing=(flag) @@preprocessing = flag end ## define class for backward-compatibility class PreprocessingEruby < Erubis::PreprocessingEruby # :nodoc: end module TemplateConverter ## covert eRuby string into ruby code def _convert_template(template) # :nodoc: #src = ::Erubis::Eruby.new(template).src klass = ::Erubis::Helpers::RailsHelper.engine_class properties = ::Erubis::Helpers::RailsHelper.init_properties show_src = ::Erubis::Helpers::RailsHelper.show_src show_src = ENV['RAILS_ENV'] == 'development' if show_src.nil? ## preprocessing if ::Erubis::Helpers::RailsHelper.preprocessing preprocessor = _create_preprocessor(template) template = preprocessor.evaluate(_preprocessing_context_object()) _logger_info "** Erubis: preprocessed==<<'END'\n#{template}END\n" if show_src end ## convert into ruby code src = klass.new(template, properties).src #src.insert(0, '_erbout = ') _logger_info "** Erubis: src==<<'END'\n#{src}END\n" if show_src return src end def _create_preprocessor(template) return PreprocessingEruby.new(template, :escape=>true) end def _preprocessing_context_object return self end def _logger_info(message) logger.info message end end end end end class ActionView::Base # :nodoc: include ::Erubis::Helpers::RailsHelper::TemplateConverter include ::Erubis::PreprocessingHelper private # convert template into ruby code def convert_template_into_ruby_code(template) #ERB.new(template, nil, @@erb_trim_mode).src return _convert_template(template) end end require 'action_pack/version' rails22 = false if ActionPack::VERSION::MAJOR >= 2 ### Rails 2.X if ActionPack::VERSION::MINOR >=2 ### Rails 2.2, 2.3 or higher rails22 = true module ActionView module TemplateHandlers class ErubisHandler < TemplateHandler include Compilable include ::Erubis::Helpers::RailsHelper::TemplateConverter include ::Erubis::PreprocessingHelper def compile(template) #src = ::ERB.new("<% __in_erb_template=true %>#{template.source}", nil, erb_trim_mode, '@output_buffer').src return _convert_template("<% __in_erb_template=true %>#{template.source}") end end end handler_klass = TemplateHandlers::ErubisHandler Template.register_default_template_handler :erb, handler_klass Template.register_template_handler :rhtml, handler_klass end module Erubis::Helpers::RailsHelper::TemplateConverter def _logger_info(message) #logger.info message # logger.info seems not available in Rails 2.2 ActionController::Base.new.logger.info message end end elsif ActionPack::VERSION::MINOR >=1 ### Rails 2.1 module ActionView module TemplateHandlers # :nodoc: class ErubisHandler < TemplateHandler include Compilable include Erubis::Helpers::RailsHelper::TemplateConverter include Erubis::PreprocessingHelper # def compile(template) return _convert_template(template.source) # template.is_a?(ActionView::Template) end def logger #:nodoc: return @view.controller.logger end def _preprocessing_context_object #:nodoc: return @view.controller.instance_variable_get('@template') end # def cache_fragment(block, name = {}, options = nil) #:nodoc: @view.fragment_for(block, name, options) do #eval(ActionView::Base.erb_variable, block.binding) eval('_buf', block.binding) end end end end handler_klass = TemplateHandlers::ErubisHandler Template.register_default_template_handler :erb, handler_klass Template.register_template_handler :rhtml, handler_klass end elsif ActionPack::VERSION::TINY >= 2 ### Rails 2.0.X (X >= 2) module ActionView module TemplateHandlers # :nodoc: class ErubisHandler < TemplateHandler include Erubis::Helpers::RailsHelper::TemplateConverter include Erubis::PreprocessingHelper def compile(template) return _convert_template(template) # template.is_a?(String) end def logger #:nodoc: return @view.controller.logger end def _preprocessing_context_object #:nodoc: return @view.controller.instance_variable_get('@template') end end end Base.class_eval do handler_klass = TemplateHandlers::ErubisHandler register_default_template_handler :erb, handler_klass register_template_handler :rhtml, handler_klass end end else ### Rails 2.0.0 or 2.0.1 class ActionView::Base # :nodoc: private # Method to create the source code for a given template. def create_template_source(extension, template, render_symbol, locals) if template_requires_setup?(extension) body = case extension.to_sym when :rxml, :builder content_type_handler = (controller.respond_to?(:response) ? "controller.response" : "controller") "#{content_type_handler}.content_type ||= Mime::XML\n" + "xml = Builder::XmlMarkup.new(:indent => 2)\n" + template + "\nxml.target!\n" when :rjs "controller.response.content_type ||= Mime::JS\n" + "update_page do |page|\n#{template}\nend" end else #body = ERB.new(template, nil, @@erb_trim_mode).src body = convert_template_into_ruby_code(template) end # @@template_args[render_symbol] ||= {} locals_keys = @@template_args[render_symbol].keys | locals @@template_args[render_symbol] = locals_keys.inject({}) { |h, k| h[k] = true; h } # locals_code = "" locals_keys.each do |key| locals_code << "#{key} = local_assigns[:#{key}]\n" end # "def #{render_symbol}(local_assigns)\n#{locals_code}#{body}\nend" end end end #if else ### Rails 1.X if ActionPack::VERSION::MINOR > 12 ### Rails 1.2 class ActionView::Base # :nodoc: private # Create source code for given template def create_template_source(extension, template, render_symbol, locals) if template_requires_setup?(extension) body = case extension.to_sym when :rxml "controller.response.content_type ||= 'application/xml'\n" + "xml = Builder::XmlMarkup.new(:indent => 2)\n" + template when :rjs "controller.response.content_type ||= 'text/javascript'\n" + "update_page do |page|\n#{template}\nend" end else #body = ERB.new(template, nil, @@erb_trim_mode).src body = convert_template_into_ruby_code(template) end # @@template_args[render_symbol] ||= {} locals_keys = @@template_args[render_symbol].keys | locals @@template_args[render_symbol] = locals_keys.inject({}) { |h, k| h[k] = true; h } # locals_code = "" locals_keys.each do |key| locals_code << "#{key} = local_assigns[:#{key}]\n" end # "def #{render_symbol}(local_assigns)\n#{locals_code}#{body}\nend" end end else ### Rails 1.1 class ActionView::Base # :nodoc: private # Create source code for given template def create_template_source(extension, template, render_symbol, locals) if template_requires_setup?(extension) body = case extension.to_sym when :rxml "xml = Builder::XmlMarkup.new(:indent => 2)\n" + "@controller.headers['Content-Type'] ||= 'application/xml'\n" + template when :rjs "@controller.headers['Content-Type'] ||= 'text/javascript'\n" + "update_page do |page|\n#{template}\nend" end else #body = ERB.new(template, nil, @@erb_trim_mode).src body = convert_template_into_ruby_code(template) end # @@template_args[render_symbol] ||= {} locals_keys = @@template_args[render_symbol].keys | locals @@template_args[render_symbol] = locals_keys.inject({}) { |h, k| h[k] = true; h } # locals_code = "" locals_keys.each do |key| locals_code << "#{key} = local_assigns[:#{key}] if local_assigns.has_key?(:#{key})\n" end # "def #{render_symbol}(local_assigns)\n#{locals_code}#{body}\nend" end end end #if ## make h() method faster (only for Rails 1.X) module ERB::Util # :nodoc: ESCAPE_TABLE = { '&'=>'&', '<'=>'<', '>'=>'>', '"'=>'"', "'"=>''', } def h(value) value.to_s.gsub(/[&<>"]/) {|s| ESCAPE_TABLE[s] } end module_function :h end end ### ## finish ActionController::Base.new.logger.info "** Erubis #{::Erubis::VERSION}" $stdout.puts "** Erubis #{::Erubis::VERSION}" if rails22 ruby-erubis-2.7.0/lib/erubis/local-setting.rb000066400000000000000000000002601170760342400211230ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## ## ## you can add site-local settings here. ## this files is required by erubis.rb ## ruby-erubis-2.7.0/lib/erubis/main.rb000066400000000000000000000374161170760342400173170ustar00rootroot00000000000000### ### $Release: 2.7.0 $ ### copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ### require 'yaml' require 'erubis' require 'erubis/tiny' require 'erubis/engine/enhanced' require 'erubis/engine/optimized' require 'erubis/engine/eruby' require 'erubis/engine/ephp' require 'erubis/engine/ec' require 'erubis/engine/ecpp' require 'erubis/engine/ejava' require 'erubis/engine/escheme' require 'erubis/engine/eperl' require 'erubis/engine/ejavascript' module Erubis Ejs = Ejavascript EscapedEjs = EscapedEjavascript class CommandOptionError < ErubisError end ## ## main class of command ## ## ex. ## Main.main(ARGV) ## class Main def self.main(argv=ARGV) status = 0 begin Main.new.execute(ARGV) rescue CommandOptionError => ex $stderr.puts ex.message status = 1 end exit(status) end def initialize @single_options = "hvxztTSbeBXNUC" @arg_options = "pcrfKIlaE" #C @option_names = { 'h' => :help, 'v' => :version, 'x' => :source, 'z' => :syntax, 'T' => :unexpand, 't' => :untabify, # obsolete 'S' => :intern, 'b' => :bodyonly, 'B' => :binding, 'p' => :pattern, 'c' => :context, #'C' => :class, 'e' => :escape, 'r' => :requires, 'f' => :datafiles, 'K' => :kanji, 'I' => :includes, 'l' => :lang, 'a' => :action, 'E' => :enhancers, 'X' => :notext, 'N' => :linenum, 'U' => :unique, 'C' => :compact, } assert unless @single_options.length + @arg_options.length == @option_names.length (@single_options + @arg_options).each_byte do |ch| assert unless @option_names.key?(ch.chr) end end def execute(argv=ARGV) ## parse command-line options options, properties = parse_argv(argv, @single_options, @arg_options) filenames = argv options['h'] = true if properties[:help] opts = Object.new arr = @option_names.collect {|ch, name| "def #{name}; @#{name}; end\n" } opts.instance_eval arr.join options.each do |ch, val| name = @option_names[ch] opts.instance_variable_set("@#{name}", val) end ## help, version, enhancer list if opts.help || opts.version puts version() if opts.version puts usage() if opts.help puts show_properties() if opts.help puts show_enhancers() if opts.help return end ## include path opts.includes.split(/,/).each do |path| $: << path end if opts.includes ## require library opts.requires.split(/,/).each do |library| require library end if opts.requires ## action action = opts.action action ||= 'syntax' if opts.syntax action ||= 'convert' if opts.source || opts.notext ## lang lang = opts.lang || 'ruby' action ||= 'convert' if opts.lang ## class name of Eruby #classname = opts.class classname = nil klass = get_classobj(classname, lang, properties[:pi]) ## kanji code $KCODE = opts.kanji if opts.kanji ## read context values from yaml file datafiles = opts.datafiles context = load_datafiles(datafiles, opts) ## parse context data if opts.context context = parse_context_data(opts.context, opts) end ## properties for engine properties[:escape] = true if opts.escape && !properties.key?(:escape) properties[:pattern] = opts.pattern if opts.pattern #properties[:trim] = false if opts.notrim properties[:preamble] = properties[:postamble] = false if opts.bodyonly properties[:pi] = nil if properties[:pi] == true ## create engine and extend enhancers engine = klass.new(nil, properties) enhancers = get_enhancers(opts.enhancers) #enhancers.push(Erubis::EscapeEnhancer) if opts.escape enhancers.each do |enhancer| engine.extend(enhancer) engine.bipattern = properties[:bipattern] if enhancer == Erubis::BiPatternEnhancer end ## no-text engine.extend(Erubis::NoTextEnhancer) if opts.notext ## convert and execute val = nil msg = "Syntax OK\n" if filenames && !filenames.empty? filenames.each do |filename| File.file?(filename) or raise CommandOptionError.new("#{filename}: file not found.") engine.filename = filename engine.convert!(File.read(filename)) val = do_action(action, engine, context, filename, opts) msg = nil if val end else engine.filename = filename = '(stdin)' engine.convert!($stdin.read()) val = do_action(action, engine, context, filename, opts) msg = nil if val end print msg if action == 'syntax' && msg end private def do_action(action, engine, context, filename, opts) case action when 'convert' s = manipulate_src(engine.src, opts) when nil, 'exec', 'execute' s = opts.binding ? engine.result(context.to_hash) : engine.evaluate(context) when 'syntax' s = check_syntax(filename, engine.src) else raise "*** internal error" end print s if s return s end def manipulate_src(source, opts) flag_linenum = opts.linenum flag_unique = opts.unique flag_compact = opts.compact if flag_linenum n = 0 source.gsub!(/^/) { n += 1; "%5d: " % n } source.gsub!(/^ *\d+:\s+?\n/, '') if flag_compact source.gsub!(/(^ *\d+:\s+?\n)+/, "\n") if flag_unique else source.gsub!(/^\s*?\n/, '') if flag_compact source.gsub!(/(^\s*?\n)+/, "\n") if flag_unique end return source end def usage(command=nil) command ||= File.basename($0) buf = [] buf << "erubis - embedded program converter for multi-language" buf << "Usage: #{command} [..options..] [file ...]" buf << " -h, --help : help" buf << " -v : version" buf << " -x : show converted code" buf << " -X : show converted code, only ruby code and no text part" buf << " -N : numbering: add line numbers (for '-x/-X')" buf << " -U : unique: compress empty lines to a line (for '-x/-X')" buf << " -C : compact: remove empty lines (for '-x/-X')" buf << " -b : body only: no preamble nor postamble (for '-x/-X')" buf << " -z : syntax checking" buf << " -e : escape (equal to '--E Escape')" buf << " -p pattern : embedded pattern (default '<% %>')" buf << " -l lang : convert but no execute (ruby/php/c/cpp/java/scheme/perl/js)" buf << " -E e1,e2,... : enhancer names (Escape, PercentLine, BiPattern, ...)" buf << " -I path : library include path" buf << " -K kanji : kanji code (euc/sjis/utf8) (default none)" buf << " -c context : context data string (yaml inline style or ruby code)" buf << " -f datafile : context data file ('*.yaml', '*.yml', or '*.rb')" #buf << " -t : expand tab characters in YAML file" buf << " -T : don't expand tab characters in YAML file" buf << " -S : convert mapping key from string to symbol in YAML file" buf << " -B : invoke 'result(binding)' instead of 'evaluate(context)'" buf << " --pi=name : parse '' instead of '<% ... %>'" #' # -T : don't trim spaces around '<% %>' # -c class : class name (XmlEruby/PercentLineEruby/...) (default Eruby) # -r library : require library # -a : action (convert/execute) return buf.join("\n") end def collect_supported_properties(erubis_klass) list = [] erubis_klass.ancestors.each do |klass| if klass.respond_to?(:supported_properties) list.concat(klass.supported_properties) end end return list end def show_properties s = "supported properties:\n" basic_props = collect_supported_properties(Erubis::Basic::Engine) pi_props = collect_supported_properties(Erubis::PI::Engine) list = [] common_props = basic_props & pi_props list << ['(common)', common_props] list << ['(basic)', basic_props - common_props] list << ['(pi)', pi_props - common_props] %w[ruby php c cpp java scheme perl javascript].each do |lang| klass = Erubis.const_get("E#{lang}") list << [lang, collect_supported_properties(klass) - basic_props] end list.each do |lang, props| s << " * #{lang}\n" props.each do |name, default_val, desc| s << (" --%-23s : %s\n" % ["#{name}=#{default_val.inspect}", desc]) end end s << "\n" return s end def show_enhancers dict = {} ObjectSpace.each_object(Module) do |mod| dict[$1] = mod if mod.name =~ /\AErubis::(.*)Enhancer\z/ end s = "enhancers:\n" dict.sort_by {|name, mod| name }.each do |name, mod| s << (" %-13s : %s\n" % [name, mod.desc]) end return s end def version return Erubis::VERSION end def parse_argv(argv, arg_none='', arg_required='', arg_optional='') options = {} context = {} while argv[0] && argv[0][0] == ?- optstr = argv.shift optstr = optstr[1, optstr.length-1] # if optstr[0] == ?- # context optstr =~ /\A\-([-\w]+)(?:=(.*))?/ or raise CommandOptionError.new("-#{optstr}: invalid context value.") name, value = $1, $2 name = name.gsub(/-/, '_').intern #value = value.nil? ? true : YAML.load(value) # error, why? value = value.nil? ? true : YAML.load("---\n#{value}\n") context[name] = value # else # options while optstr && !optstr.empty? optchar = optstr[0].chr optstr = optstr[1..-1] if arg_none.include?(optchar) options[optchar] = true elsif arg_required.include?(optchar) arg = optstr.empty? ? argv.shift : optstr or raise CommandOptionError.new("-#{optchar}: #{@option_names[optchar]} required.") options[optchar] = arg optstr = nil elsif arg_optional.include?(optchar) arg = optstr.empty? ? true : optstr options[optchar] = arg optstr = nil else raise CommandOptionError.new("-#{optchar}: unknown option.") end end end # end # end of while return options, context end def untabify(str, width=8) list = str.split(/\t/) last = list.pop sb = '' list.each do |s| column = (n = s.rindex(?\n)) ? s.length - n - 1 : s.length n = width - (column % width) sb << s << (' ' * n) end sb << last return sb end #-- #def untabify(str, width=8) # sb = '' # str.scan(/(.*?)\t/m) do |s, | # len = (n = s.rindex(?\n)) ? s.length - n - 1 : s.length # sb << s << (" " * (width - len % width)) # end # return $' ? (sb << $') : str #end #++ def get_classobj(classname, lang, pi) classname ||= "E#{lang}" base_module = pi ? Erubis::PI : Erubis begin klass = base_module.const_get(classname) rescue NameError klass = nil end unless klass if lang msg = "-l #{lang}: invalid language name (class #{base_module.name}::#{classname} not found)." else msg = "-c #{classname}: invalid class name." end raise CommandOptionError.new(msg) end return klass end def get_enhancers(enhancer_names) return [] unless enhancer_names enhancers = [] shortname = nil begin enhancer_names.split(/,/).each do |name| shortname = name enhancers << Erubis.const_get("#{shortname}Enhancer") end rescue NameError raise CommandOptionError.new("#{shortname}: no such Enhancer (try '-h' to show all enhancers).") end return enhancers end def load_datafiles(filenames, opts) context = Erubis::Context.new return context unless filenames filenames.split(/,/).each do |filename| filename.strip! test(?f, filename) or raise CommandOptionError.new("#{filename}: file not found.") if filename =~ /\.ya?ml$/ if opts.unexpand ydoc = YAML.load_file(filename) else ydoc = YAML.load(untabify(File.read(filename))) end ydoc.is_a?(Hash) or raise CommandOptionError.new("#{filename}: root object is not a mapping.") intern_hash_keys(ydoc) if opts.intern context.update(ydoc) elsif filename =~ /\.rb$/ str = File.read(filename) context2 = Erubis::Context.new _instance_eval(context2, str) context.update(context2) else CommandOptionError.new("#{filename}: '*.yaml', '*.yml', or '*.rb' required.") end end return context end def _instance_eval(_context, _str) _context.instance_eval(_str) end def parse_context_data(context_str, opts) if context_str[0] == ?{ require 'yaml' ydoc = YAML.load(context_str) unless ydoc.is_a?(Hash) raise CommandOptionError.new("-c: root object is not a mapping.") end intern_hash_keys(ydoc) if opts.intern return ydoc else context = Erubis::Context.new context.instance_eval(context_str, '-c') return context end end def intern_hash_keys(obj, done={}) return if done.key?(obj.__id__) case obj when Hash done[obj.__id__] = obj obj.keys.each do |key| obj[key.intern] = obj.delete(key) if key.is_a?(String) end obj.values.each do |val| intern_hash_keys(val, done) if val.is_a?(Hash) || val.is_a?(Array) end when Array done[obj.__id__] = obj obj.each do |val| intern_hash_keys(val, done) if val.is_a?(Hash) || val.is_a?(Array) end end end def check_syntax(filename, src) require 'open3' #command = (ENV['_'] || 'ruby') + ' -wc' # ENV['_'] stores command name bin = ENV['_'] && File.basename(ENV['_']) =~ /^ruby/ ? ENV['_'] : 'ruby' command = bin + ' -wc' stdin, stdout, stderr = Open3.popen3(command) stdin.write(src) stdin.close result = stdout.read() stdout.close() errmsg = stderr.read() stderr.close() return nil unless errmsg && !errmsg.empty? errmsg =~ /\A-:(\d+): / linenum, message = $1, $' return "#{filename}:#{linenum}: #{message}" end if defined?(RUBY_ENGINE) && RUBY_ENGINE == "rbx" def check_syntax(filename, src) require 'compiler' verbose = $VERBOSE msg = nil begin $VERBOSE = true Rubinius::Compiler.compile_string(src, filename) rescue SyntaxError => ex ex_linenum = ex.line linenum = 0 srcline = src.each_line do |line| linenum += 1 break line if linenum == ex_linenum end msg = "#{ex.message}\n" msg << srcline msg << "\n" unless srcline =~ /\n\z/ msg << (" " * (ex.column-1)) << "^\n" ensure $VERBOSE = verbose end return msg end end end end ruby-erubis-2.7.0/lib/erubis/preprocessing.rb000066400000000000000000000017401170760342400212450ustar00rootroot00000000000000### ### $Release: 2.7.0 $ ### copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ### require 'cgi' module Erubis ## ## for preprocessing ## class PreprocessingEruby < Erubis::Eruby def initialize(input, params={}) params = params.dup params[:pattern] ||= '\[% %\]' # use '[%= %]' instead of '<%= %>' #params[:escape] = true # transport '[%= %]' and '[%== %]' super end def add_expr_escaped(src, code) add_expr_literal(src, "_decode((#{code}))") end end ## ## helper methods for preprocessing ## module PreprocessingHelper module_function def _p(arg) return "<%=#{arg}%>" end def _P(arg) return "<%=h(#{arg})%>" end alias _? _p def _decode(arg) arg = arg.to_s arg.gsub!(/%3C%25(?:=|%3D)(.*?)%25%3E/) { "<%=#{CGI.unescape($1)}%>" } arg.gsub!(/<%=(.*?)%>/) { "<%=#{CGI.unescapeHTML($1)}%>" } return arg end end end ruby-erubis-2.7.0/lib/erubis/tiny.rb000066400000000000000000000100431170760342400173410ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## module Erubis ## ## tiny and the simplest implementation of eRuby ## ## ex. ## eruby = TinyEruby.new(File.read('example.rhtml')) ## print eruby.src # print ruby code ## print eruby.result(binding()) # eval ruby code with Binding object ## print eruby.evalute(context) # eval ruby code with context object ## class TinyEruby def initialize(input=nil) @src = convert(input) if input end attr_reader :src EMBEDDED_PATTERN = /<%(=+|\#)?(.*?)-?%>/m def convert(input) src = "_buf = '';" # preamble pos = 0 input.scan(EMBEDDED_PATTERN) do |indicator, code| m = Regexp.last_match text = input[pos...m.begin(0)] pos = m.end(0) #src << " _buf << '" << escape_text(text) << "';" text.gsub!(/['\\]/, '\\\\\&') src << " _buf << '" << text << "';" unless text.empty? if !indicator # <% %> src << code << ";" elsif indicator == '#' # <%# %> src << ("\n" * code.count("\n")) else # <%= %> src << " _buf << (" << code << ").to_s;" end end #rest = $' || input # ruby1.8 rest = pos == 0 ? input : input[pos..-1] # ruby1.9 #src << " _buf << '" << escape_text(rest) << "';" rest.gsub!(/['\\]/, '\\\\\&') src << " _buf << '" << rest << "';" unless rest.empty? src << "\n_buf.to_s\n" # postamble return src end #def escape_text(text) # return text.gsub!(/['\\]/, '\\\\\&') || text #end def result(_binding=TOPLEVEL_BINDING) eval @src, _binding end def evaluate(_context=Object.new) if _context.is_a?(Hash) _obj = Object.new _context.each do |k, v| _obj.instance_variable_set("@#{k}", v) end _context = _obj end _context.instance_eval @src end end module PI end class PI::TinyEruby def initialize(input=nil, options={}) @escape = options[:escape] || 'Erubis::XmlHelper.escape_xml' @src = convert(input) if input end attr_reader :src EMBEDDED_PATTERN = /(^[ \t]*)?<\?rb(\s.*?)\?>([ \t]*\r?\n)?|@(!+)?\{(.*?)\}@/m def convert(input) src = "_buf = '';" # preamble pos = 0 input.scan(EMBEDDED_PATTERN) do |lspace, stmt, rspace, indicator, expr| match = Regexp.last_match len = match.begin(0) - pos text = input[pos, len] pos = match.end(0) #src << " _buf << '" << escape_text(text) << "';" text.gsub!(/['\\]/, '\\\\\&') src << " _buf << '" << text << "';" unless text.empty? if stmt # if lspace && rspace src << "#{lspace}#{stmt}#{rspace}" else src << " _buf << '" << lspace << "';" if lspace src << stmt << ";" src << " _buf << '" << rspace << "';" if rspace end else # ${...}, $!{...} if !indicator src << " _buf << " << @escape << "(" << expr << ");" elsif indicator == '!' src << " _buf << (" << expr << ").to_s;" end end end #rest = $' || input # ruby1.8 rest = pos == 0 ? input : input[pos..-1] # ruby1.9 #src << " _buf << '" << escape_text(rest) << "';" rest.gsub!(/['\\]/, '\\\\\&') src << " _buf << '" << rest << "';" unless rest.empty? src << "\n_buf.to_s\n" # postamble return src end #def escape_text(text) # return text.gsub!(/['\\]/, '\\\\\&') || text #end def result(_binding=TOPLEVEL_BINDING) eval @src, _binding end def evaluate(_context=Object.new) if _context.is_a?(Hash) _obj = Object.new _context.each do |k, v| _obj.instance_variable_set("@#{k}", v) end _context = _obj end _context.instance_eval @src end end end ruby-erubis-2.7.0/lib/erubis/util.rb000066400000000000000000000010361170760342400173350ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## module Kernel ## ## raise NotImplementedError ## def not_implemented #:doc: backtrace = caller() method_name = (backtrace.shift =~ /`(\w+)'$/) && $1 mesg = "class #{self.class.name} must implement abstract method '#{method_name}()'." #mesg = "#{self.class.name}##{method_name}() is not implemented." err = NotImplementedError.new mesg err.set_backtrace backtrace raise err end private :not_implemented end ruby-erubis-2.7.0/metadata.yml000066400000000000000000000336031170760342400163040ustar00rootroot00000000000000--- !ruby/object:Gem::Specification name: erubis version: !ruby/object:Gem::Version hash: 19 prerelease: segments: - 2 - 7 - 0 version: 2.7.0 platform: ruby authors: - makoto kuwata autorequire: bindir: bin cert_chain: [] date: 2011-04-02 00:00:00 +09:00 default_executable: dependencies: [] description: " Erubis is an implementation of eRuby and has the following features:\n\n * Very fast, almost three times faster than ERB and about 10% faster than eruby.\n * Multi-language support (Ruby/PHP/C/Java/Scheme/Perl/Javascript)\n * Auto escaping support\n * Auto trimming spaces around '<% %>'\n * Embedded pattern changeable (default '<% %>')\n * Enable to handle Processing Instructions (PI) as embedded pattern (ex. '')\n * Context object available and easy to combine eRuby template with YAML datafile\n * Print statement available\n * Easy to extend and customize in subclass\n * Ruby on Rails support\n" email: kwa(at)kuwata-lab.com executables: - erubis extensions: [] extra_rdoc_files: [] files: - lib/erubis/context.rb - lib/erubis/converter.rb - lib/erubis/engine/ec.rb - lib/erubis/engine/ecpp.rb - lib/erubis/engine/ejava.rb - lib/erubis/engine/ejavascript.rb - lib/erubis/engine/enhanced.rb - lib/erubis/engine/eperl.rb - lib/erubis/engine/ephp.rb - lib/erubis/engine/eruby.rb - lib/erubis/engine/escheme.rb - lib/erubis/engine/optimized.rb - lib/erubis/engine.rb - lib/erubis/enhancer.rb - lib/erubis/error.rb - lib/erubis/evaluator.rb - lib/erubis/generator.rb - lib/erubis/helper.rb - lib/erubis/helpers/rails_form_helper.rb - lib/erubis/helpers/rails_helper.rb - lib/erubis/local-setting.rb - lib/erubis/main.rb - lib/erubis/preprocessing.rb - lib/erubis/tiny.rb - lib/erubis/util.rb - lib/erubis.rb - bin/erubis - examples/basic/example.ec - examples/basic/example.ecpp - examples/basic/example.ejava - examples/basic/example.ejs - examples/basic/example.eperl - examples/basic/example.ephp - examples/basic/example.eruby - examples/basic/example.escheme - examples/basic/Makefile - examples/pi/example.ec - examples/pi/example.ejava - examples/pi/example.ejs - examples/pi/example.eperl - examples/pi/example.ephp - examples/pi/example.eruby - examples/pi/example.escheme - examples/pi/Makefile - test/assert-text-equal.rb - test/data/users-guide/array_example.result - test/data/users-guide/arraybuffer_example.result - test/data/users-guide/bipattern-example.rhtml - test/data/users-guide/bipattern_example.result - test/data/users-guide/bufvar-example.rb - test/data/users-guide/bufvar-example.result - test/data/users-guide/context.rb - test/data/users-guide/context.yaml - test/data/users-guide/def_method.rb - test/data/users-guide/def_method.result - test/data/users-guide/escape_example.result - test/data/users-guide/example.ec - test/data/users-guide/example.ecpp - test/data/users-guide/Example.ejava - test/data/users-guide/example.ejs - test/data/users-guide/example.eperl - test/data/users-guide/example.ephp - test/data/users-guide/example.eruby - test/data/users-guide/example.escheme - test/data/users-guide/example1.eruby - test/data/users-guide/example1.rb - test/data/users-guide/example1.result - test/data/users-guide/example10.rb - test/data/users-guide/example10.result - test/data/users-guide/example10.xhtml - test/data/users-guide/example10_x.result - test/data/users-guide/example11.php - test/data/users-guide/example11.result - test/data/users-guide/example11.rhtml - test/data/users-guide/example11_C.result - test/data/users-guide/example11_N.result - test/data/users-guide/example11_php.result - test/data/users-guide/example11_U.result - test/data/users-guide/example1_x.result - test/data/users-guide/example2.eruby - test/data/users-guide/example2.rb - test/data/users-guide/example2.result - test/data/users-guide/example2_trim.result - test/data/users-guide/example2_x.result - test/data/users-guide/example3.eruby - test/data/users-guide/example3.rb - test/data/users-guide/example31.result - test/data/users-guide/example32.result - test/data/users-guide/example3_e.result - test/data/users-guide/example4.eruby - test/data/users-guide/example4.rb - test/data/users-guide/example4.result - test/data/users-guide/example4_x.result - test/data/users-guide/example5.eruby - test/data/users-guide/example5.rb - test/data/users-guide/example5.result - test/data/users-guide/example6.rb - test/data/users-guide/example6.result - test/data/users-guide/example7.eruby - test/data/users-guide/example71.result - test/data/users-guide/example72.result - test/data/users-guide/example8.eruby - test/data/users-guide/example8_ruby.result - test/data/users-guide/example8_yaml.result - test/data/users-guide/example9.eruby - test/data/users-guide/example9.rb - test/data/users-guide/example9.result - test/data/users-guide/example91.result - test/data/users-guide/example92.result - test/data/users-guide/example_c.result - test/data/users-guide/example_java.result - test/data/users-guide/example_js.result - test/data/users-guide/example_perl.result - test/data/users-guide/example_php.result - test/data/users-guide/example_scheme.result - test/data/users-guide/example_scheme_display.result - test/data/users-guide/fasteruby-example.rb - test/data/users-guide/fasteruby-example.result - test/data/users-guide/fasteruby.rb - test/data/users-guide/fasteruby.result - test/data/users-guide/fasteruby.rhtml - test/data/users-guide/headerfooter-example.eruby - test/data/users-guide/headerfooter-example2.rb - test/data/users-guide/headerfooter-example2.rhtml - test/data/users-guide/headerfooter_example.result - test/data/users-guide/headerfooter_example2.result - test/data/users-guide/interpolation_example.result - test/data/users-guide/main_program1.rb - test/data/users-guide/main_program1.result - test/data/users-guide/main_program2.rb - test/data/users-guide/main_program2.result - test/data/users-guide/nocode-example.eruby - test/data/users-guide/nocode-php.result - test/data/users-guide/nocode_example.result - test/data/users-guide/normal-eruby-test.eruby - test/data/users-guide/normal_eruby_test.result - test/data/users-guide/notext-example.eruby - test/data/users-guide/notext-example.php - test/data/users-guide/notext-php.result - test/data/users-guide/notext_example.result - test/data/users-guide/percentline-example.rhtml - test/data/users-guide/percentline_example.result - test/data/users-guide/prefixedline-example.rb - test/data/users-guide/prefixedline-example.rhtml - test/data/users-guide/prefixedline_example.result - test/data/users-guide/printenable_example.result - test/data/users-guide/printenabled-example.eruby - test/data/users-guide/printenabled-example.rb - test/data/users-guide/printstatement_example.result - test/data/users-guide/simplify_example.result - test/data/users-guide/stderr.log - test/data/users-guide/stdout_exmple.result - test/data/users-guide/stringbuffer_example.result - test/data/users-guide/tail_260.result - test/data/users-guide/tailnewline.rhtml - test/data/users-guide/template1.rhtml - test/data/users-guide/template2.rhtml - test/test-engines.rb - test/test-enhancers.rb - test/test-erubis.rb - test/test-index-cgi.rb - test/test-main.rb - test/test-users-guide.rb - test/test.rb - test/testutil.rb - doc/docstyle.css - doc/users-guide.html - README.txt - CHANGES.txt - MIT-LICENSE - setup.rb - contrib/erubis - contrib/erubis-run.rb - contrib/inline-require - benchmark/bench.rb - benchmark/bench_context.yaml - benchmark/Makefile - benchmark/templates/_footer.html - benchmark/templates/_header.html - benchmark/templates/bench_erb.rhtml - benchmark/templates/bench_erubis.rhtml - benchmark/templates/bench_eruby.rhtml - doc-api/classes/ActionView/TemplateHandlers/ErubisHandler.html - doc-api/classes/ActionView.html - doc-api/classes/ERB.html - doc-api/classes/Erubis/ArrayBufferEnhancer.html - doc-api/classes/Erubis/ArrayBufferEruby.html - doc-api/classes/Erubis/ArrayEnhancer.html - doc-api/classes/Erubis/ArrayEruby.html - doc-api/classes/Erubis/Basic/Converter.html - doc-api/classes/Erubis/Basic/Engine.html - doc-api/classes/Erubis/Basic.html - doc-api/classes/Erubis/BiPatternEnhancer.html - doc-api/classes/Erubis/BiPatternEruby.html - doc-api/classes/Erubis/CGenerator.html - doc-api/classes/Erubis/CommandOptionError.html - doc-api/classes/Erubis/Context.html - doc-api/classes/Erubis/Converter.html - doc-api/classes/Erubis/CppGenerator.html - doc-api/classes/Erubis/DeleteIndentEnhancer.html - doc-api/classes/Erubis/DeleteIndentEruby.html - doc-api/classes/Erubis/Ec.html - doc-api/classes/Erubis/Ecpp.html - doc-api/classes/Erubis/Ejava.html - doc-api/classes/Erubis/Ejavascript.html - doc-api/classes/Erubis/Engine.html - doc-api/classes/Erubis/Eperl.html - doc-api/classes/Erubis/Ephp.html - doc-api/classes/Erubis/ErboutEnhancer.html - doc-api/classes/Erubis/ErboutEruby.html - doc-api/classes/Erubis/ErubisError.html - doc-api/classes/Erubis/Eruby.html - doc-api/classes/Erubis/EscapedEc.html - doc-api/classes/Erubis/EscapedEcpp.html - doc-api/classes/Erubis/EscapedEjava.html - doc-api/classes/Erubis/EscapedEjavascript.html - doc-api/classes/Erubis/EscapedEperl.html - doc-api/classes/Erubis/EscapedEphp.html - doc-api/classes/Erubis/EscapedEruby.html - doc-api/classes/Erubis/EscapedEscheme.html - doc-api/classes/Erubis/EscapeEnhancer.html - doc-api/classes/Erubis/Escheme.html - doc-api/classes/Erubis/Evaluator.html - doc-api/classes/Erubis/FastEruby.html - doc-api/classes/Erubis/Generator.html - doc-api/classes/Erubis/HeaderFooterEnhancer.html - doc-api/classes/Erubis/HeaderFooterEruby.html - doc-api/classes/Erubis/Helpers/RailsFormHelper.html - doc-api/classes/Erubis/Helpers/RailsHelper/TemplateConverter.html - doc-api/classes/Erubis/Helpers/RailsHelper.html - doc-api/classes/Erubis/Helpers.html - doc-api/classes/Erubis/InterpolationEnhancer.html - doc-api/classes/Erubis/InterpolationEruby.html - doc-api/classes/Erubis/JavaGenerator.html - doc-api/classes/Erubis/JavascriptGenerator.html - doc-api/classes/Erubis/Main.html - doc-api/classes/Erubis/NoCodeEnhancer.html - doc-api/classes/Erubis/NoCodeEruby.html - doc-api/classes/Erubis/NoTextEnhancer.html - doc-api/classes/Erubis/NoTextEruby.html - doc-api/classes/Erubis/NotSupportedError.html - doc-api/classes/Erubis/OptimizedEruby.html - doc-api/classes/Erubis/OptimizedGenerator.html - doc-api/classes/Erubis/OptimizedXmlEruby.html - doc-api/classes/Erubis/PercentLineEnhancer.html - doc-api/classes/Erubis/PercentLineEruby.html - doc-api/classes/Erubis/PerlGenerator.html - doc-api/classes/Erubis/PhpGenerator.html - doc-api/classes/Erubis/PI/Converter.html - doc-api/classes/Erubis/PI/Ec.html - doc-api/classes/Erubis/PI/Ecpp.html - doc-api/classes/Erubis/PI/Ejava.html - doc-api/classes/Erubis/PI/Ejavascript.html - doc-api/classes/Erubis/PI/Engine.html - doc-api/classes/Erubis/PI/Eperl.html - doc-api/classes/Erubis/PI/Ephp.html - doc-api/classes/Erubis/PI/Eruby.html - doc-api/classes/Erubis/PI/Escheme.html - doc-api/classes/Erubis/PI/TinyEruby.html - doc-api/classes/Erubis/PI.html - doc-api/classes/Erubis/PrefixedLineEnhancer.html - doc-api/classes/Erubis/PrefixedLineEruby.html - doc-api/classes/Erubis/PreprocessingEruby.html - doc-api/classes/Erubis/PreprocessingHelper.html - doc-api/classes/Erubis/PrintEnabledEnhancer.html - doc-api/classes/Erubis/PrintEnabledEruby.html - doc-api/classes/Erubis/PrintOutEnhancer.html - doc-api/classes/Erubis/PrintOutEruby.html - doc-api/classes/Erubis/PrintOutSimplifiedEruby.html - doc-api/classes/Erubis/RubyEvaluator.html - doc-api/classes/Erubis/RubyGenerator.html - doc-api/classes/Erubis/SchemeGenerator.html - doc-api/classes/Erubis/SimplifiedEruby.html - doc-api/classes/Erubis/SimplifyEnhancer.html - doc-api/classes/Erubis/StdoutEnhancer.html - doc-api/classes/Erubis/StdoutEruby.html - doc-api/classes/Erubis/StdoutSimplifiedEruby.html - doc-api/classes/Erubis/StringBufferEnhancer.html - doc-api/classes/Erubis/StringBufferEruby.html - doc-api/classes/Erubis/StringIOEruby.html - doc-api/classes/Erubis/TinyEruby.html - doc-api/classes/Erubis/XmlEruby.html - doc-api/classes/Erubis/XmlHelper.html - doc-api/classes/Erubis.html - doc-api/classes/Kernel.html - doc-api/created.rid - doc-api/files/erubis/context_rb.html - doc-api/files/erubis/converter_rb.html - doc-api/files/erubis/engine/ec_rb.html - doc-api/files/erubis/engine/ecpp_rb.html - doc-api/files/erubis/engine/ejava_rb.html - doc-api/files/erubis/engine/ejavascript_rb.html - doc-api/files/erubis/engine/enhanced_rb.html - doc-api/files/erubis/engine/eperl_rb.html - doc-api/files/erubis/engine/ephp_rb.html - doc-api/files/erubis/engine/eruby_rb.html - doc-api/files/erubis/engine/escheme_rb.html - doc-api/files/erubis/engine/optimized_rb.html - doc-api/files/erubis/engine_rb.html - doc-api/files/erubis/enhancer_rb.html - doc-api/files/erubis/error_rb.html - doc-api/files/erubis/evaluator_rb.html - doc-api/files/erubis/generator_rb.html - doc-api/files/erubis/helper_rb.html - doc-api/files/erubis/helpers/rails_form_helper_rb.html - doc-api/files/erubis/helpers/rails_helper_rb.html - doc-api/files/erubis/local-setting_rb.html - doc-api/files/erubis/main_rb.html - doc-api/files/erubis/preprocessing_rb.html - doc-api/files/erubis/tiny_rb.html - doc-api/files/erubis/util_rb.html - doc-api/files/erubis_rb.html - doc-api/files/README_txt.html - doc-api/fr_class_index.html - doc-api/fr_file_index.html - doc-api/fr_method_index.html - doc-api/index.html - doc-api/rdoc-style.css has_rdoc: true homepage: http://www.kuwata-lab.com/erubis/ licenses: [] post_install_message: rdoc_options: [] require_paths: - lib required_ruby_version: !ruby/object:Gem::Requirement none: false requirements: - - ">=" - !ruby/object:Gem::Version hash: 3 segments: - 0 version: "0" required_rubygems_version: !ruby/object:Gem::Requirement none: false requirements: - - ">=" - !ruby/object:Gem::Version hash: 3 segments: - 0 version: "0" requirements: [] rubyforge_project: erubis rubygems_version: 1.6.0 signing_key: specification_version: 3 summary: a fast and extensible eRuby implementation which supports multi-language test_files: - test/test.rb ruby-erubis-2.7.0/setup.rb000066400000000000000000000672121170760342400154710ustar00rootroot00000000000000# # setup.rb # # Copyright (c) 2000-2004 Minero Aoki # # This program is free software. # You can distribute/modify this program under the terms of # the GNU Lesser General Public License version 2.1. # # # For backward compatibility # unless Enumerable.method_defined?(:map) module Enumerable alias map collect end end unless Enumerable.method_defined?(:detect) module Enumerable alias detect find end end unless Enumerable.method_defined?(:select) module Enumerable alias select find_all end end unless Enumerable.method_defined?(:reject) module Enumerable def reject result = [] each do |i| result.push i unless yield(i) end result end end end unless Enumerable.method_defined?(:inject) module Enumerable def inject(result) each do |i| result = yield(result, i) end result end end end unless Enumerable.method_defined?(:any?) module Enumerable def any? each do |i| return true if yield(i) end false end end end unless File.respond_to?(:read) def File.read(fname) open(fname) {|f| return f.read } end end # # Application independent utilities # def File.binread(fname) open(fname, 'rb') {|f| return f.read } end # for corrupted windows stat(2) def File.dir?(path) File.directory?((path[-1,1] == '/') ? path : path + '/') end # # Config # if arg = ARGV.detect{|arg| /\A--rbconfig=/ =~ arg } ARGV.delete(arg) require arg.split(/=/, 2)[1] $".push 'rbconfig.rb' else require 'rbconfig' end def multipackage_install? FileTest.directory?(File.dirname($0) + '/packages') end class ConfigTable c = ::Config::CONFIG rubypath = c['bindir'] + '/' + c['ruby_install_name'] major = c['MAJOR'].to_i minor = c['MINOR'].to_i teeny = c['TEENY'].to_i version = "#{major}.#{minor}" # ruby ver. >= 1.4.4? newpath_p = ((major >= 2) or ((major == 1) and ((minor >= 5) or ((minor == 4) and (teeny >= 4))))) subprefix = lambda {|path| path.sub(/\A#{Regexp.quote(c['prefix'])}/o, '$prefix') } if c['rubylibdir'] # V < 1.6.3 stdruby = subprefix.call(c['rubylibdir']) siteruby = subprefix.call(c['sitedir']) versite = subprefix.call(c['sitelibdir']) sodir = subprefix.call(c['sitearchdir']) elsif newpath_p # 1.4.4 <= V <= 1.6.3 stdruby = "$prefix/lib/ruby/#{version}" siteruby = subprefix.call(c['sitedir']) versite = siteruby + '/' + version sodir = "$site-ruby/#{c['arch']}" else # V < 1.4.4 stdruby = "$prefix/lib/ruby/#{version}" siteruby = "$prefix/lib/ruby/#{version}/site_ruby" versite = siteruby sodir = "$site-ruby/#{c['arch']}" end if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg } makeprog = arg.sub(/'/, '').split(/=/, 2)[1] else makeprog = 'make' end common_descripters = [ [ 'prefix', [ c['prefix'], 'path', 'path prefix of target environment' ] ], [ 'std-ruby', [ stdruby, 'path', 'the directory for standard ruby libraries' ] ], [ 'site-ruby-common', [ siteruby, 'path', 'the directory for version-independent non-standard ruby libraries' ] ], [ 'site-ruby', [ versite, 'path', 'the directory for non-standard ruby libraries' ] ], [ 'bin-dir', [ '$prefix/bin', 'path', 'the directory for commands' ] ], [ 'rb-dir', [ '$site-ruby', 'path', 'the directory for ruby scripts' ] ], [ 'so-dir', [ sodir, 'path', 'the directory for ruby extentions' ] ], [ 'data-dir', [ '$prefix/share', 'path', 'the directory for shared data' ] ], [ 'ruby-path', [ rubypath, 'path', 'path to set to #! line' ] ], [ 'ruby-prog', [ rubypath, 'name', 'the ruby program using for installation' ] ], [ 'make-prog', [ makeprog, 'name', 'the make program to compile ruby extentions' ] ], [ 'without-ext', [ 'no', 'yes/no', 'does not compile/install ruby extentions' ] ] ] multipackage_descripters = [ [ 'with', [ '', 'name,name...', 'package names that you want to install', 'ALL' ] ], [ 'without', [ '', 'name,name...', 'package names that you do not want to install', 'NONE' ] ] ] if multipackage_install? DESCRIPTER = common_descripters + multipackage_descripters else DESCRIPTER = common_descripters end SAVE_FILE = 'config.save' def ConfigTable.each_name(&block) keys().each(&block) end def ConfigTable.keys DESCRIPTER.map {|name, *dummy| name } end def ConfigTable.each_definition(&block) DESCRIPTER.each(&block) end def ConfigTable.get_entry(name) name, ent = DESCRIPTER.assoc(name) ent end def ConfigTable.get_entry!(name) get_entry(name) or raise ArgumentError, "no such config: #{name}" end def ConfigTable.add_entry(name, vals) ConfigTable::DESCRIPTER.push [name,vals] end def ConfigTable.remove_entry(name) get_entry(name) or raise ArgumentError, "no such config: #{name}" DESCRIPTER.delete_if {|n, arr| n == name } end def ConfigTable.config_key?(name) get_entry(name) ? true : false end def ConfigTable.bool_config?(name) ent = get_entry(name) or return false ent[1] == 'yes/no' end def ConfigTable.value_config?(name) ent = get_entry(name) or return false ent[1] != 'yes/no' end def ConfigTable.path_config?(name) ent = get_entry(name) or return false ent[1] == 'path' end class << self alias newobj new end def ConfigTable.new c = newobj() c.initialize_from_table c end def ConfigTable.load c = newobj() c.initialize_from_file c end def initialize_from_table @table = {} DESCRIPTER.each do |k, (default, vname, desc, default2)| @table[k] = default end end def initialize_from_file raise InstallError, "#{File.basename $0} config first"\ unless File.file?(SAVE_FILE) @table = {} File.foreach(SAVE_FILE) do |line| k, v = line.split(/=/, 2) @table[k] = v.strip end end def save File.open(SAVE_FILE, 'w') {|f| @table.each do |k, v| f.printf "%s=%s\n", k, v if v end } end def []=(k, v) raise InstallError, "unknown config option #{k}"\ unless ConfigTable.config_key?(k) @table[k] = v end def [](key) return nil unless @table[key] @table[key].gsub(%r<\$([^/]+)>) { self[$1] } end def set_raw(key, val) @table[key] = val end def get_raw(key) @table[key] end end module MetaConfigAPI def eval_file_ifexist(fname) instance_eval File.read(fname), fname, 1 if File.file?(fname) end def config_names ConfigTable.keys end def config?(name) ConfigTable.config_key?(name) end def bool_config?(name) ConfigTable.bool_config?(name) end def value_config?(name) ConfigTable.value_config?(name) end def path_config?(name) ConfigTable.path_config?(name) end def add_config(name, argname, default, desc) ConfigTable.add_entry name,[default,argname,desc] end def add_path_config(name, default, desc) add_config name, 'path', default, desc end def add_bool_config(name, default, desc) add_config name, 'yes/no', default ? 'yes' : 'no', desc end def set_config_default(name, default) if bool_config?(name) ConfigTable.get_entry!(name)[0] = (default ? 'yes' : 'no') else ConfigTable.get_entry!(name)[0] = default end end def remove_config(name) ent = ConfigTable.get_entry(name) ConfigTable.remove_entry name ent end end # # File Operations # module FileOperations def mkdir_p(dirname, prefix = nil) dirname = prefix + dirname if prefix $stderr.puts "mkdir -p #{dirname}" if verbose? return if no_harm? # does not check '/'... it's too abnormal case dirs = dirname.split(%r<(?=/)>) if /\A[a-z]:\z/i =~ dirs[0] disk = dirs.shift dirs[0] = disk + dirs[0] end dirs.each_index do |idx| path = dirs[0..idx].join('') Dir.mkdir path unless File.dir?(path) end end def rm_f(fname) $stderr.puts "rm -f #{fname}" if verbose? return if no_harm? if File.exist?(fname) or File.symlink?(fname) File.chmod 0777, fname File.unlink fname end end def rm_rf(dn) $stderr.puts "rm -rf #{dn}" if verbose? return if no_harm? Dir.chdir dn Dir.foreach('.') do |fn| next if fn == '.' next if fn == '..' if File.dir?(fn) verbose_off { rm_rf fn } else verbose_off { rm_f fn } end end Dir.chdir '..' Dir.rmdir dn end def move_file(src, dest) File.unlink dest if File.exist?(dest) begin File.rename src, dest rescue File.open(dest, 'wb') {|f| f.write File.binread(src) } File.chmod File.stat(src).mode, dest File.unlink src end end def install(from, dest, mode, prefix = nil) $stderr.puts "install #{from} #{dest}" if verbose? return if no_harm? realdest = prefix + dest if prefix realdest = File.join(realdest, File.basename(from)) if File.dir?(realdest) str = File.binread(from) if diff?(str, realdest) verbose_off { rm_f realdest if File.exist?(realdest) } File.open(realdest, 'wb') {|f| f.write str } File.chmod mode, realdest File.open("#{objdir_root()}/InstalledFiles", 'a') {|f| if prefix f.puts realdest.sub(prefix, '') else f.puts realdest end } end end def diff?(new_content, path) return true unless File.exist?(path) new_content != File.binread(path) end def command(str) $stderr.puts str if verbose? system str or raise RuntimeError, "'system #{str}' failed" end def ruby(str) command config('ruby-prog') + ' ' + str end def make(task = '') command config('make-prog') + ' ' + task end def extdir?(dir) File.exist?(dir + '/MANIFEST') end def all_files_in(dirname) Dir.open(dirname) {|d| return d.select {|ent| File.file?("#{dirname}/#{ent}") } } end REJECT_DIRS = %w( CVS SCCS RCS CVS.adm ) def all_dirs_in(dirname) Dir.open(dirname) {|d| return d.select {|n| File.dir?("#{dirname}/#{n}") } - %w(. ..) - REJECT_DIRS } end end # # Main Installer # class InstallError < StandardError; end module HookUtils def run_hook(name) try_run_hook "#{curr_srcdir()}/#{name}" or try_run_hook "#{curr_srcdir()}/#{name}.rb" end def try_run_hook(fname) return false unless File.file?(fname) begin instance_eval File.read(fname), fname, 1 rescue raise InstallError, "hook #{fname} failed:\n" + $!.message end true end end module HookScriptAPI def get_config(key) @config[key] end alias config get_config def set_config(key, val) @config[key] = val end # # srcdir/objdir (works only in the package directory) # #abstract srcdir_root #abstract objdir_root #abstract relpath def curr_srcdir "#{srcdir_root()}/#{relpath()}" end def curr_objdir "#{objdir_root()}/#{relpath()}" end def srcfile(path) "#{curr_srcdir()}/#{path}" end def srcexist?(path) File.exist?(srcfile(path)) end def srcdirectory?(path) File.dir?(srcfile(path)) end def srcfile?(path) File.file? srcfile(path) end def srcentries(path = '.') Dir.open("#{curr_srcdir()}/#{path}") {|d| return d.to_a - %w(. ..) } end def srcfiles(path = '.') srcentries(path).select {|fname| File.file?(File.join(curr_srcdir(), path, fname)) } end def srcdirectories(path = '.') srcentries(path).select {|fname| File.dir?(File.join(curr_srcdir(), path, fname)) } end end class ToplevelInstaller Version = '3.2.4' Copyright = 'Copyright (c) 2000-2004 Minero Aoki' TASKS = [ [ 'config', 'saves your configurations' ], [ 'show', 'shows current configuration' ], [ 'setup', 'compiles ruby extentions and others' ], [ 'install', 'installs files' ], [ 'clean', "does `make clean' for each extention" ], [ 'distclean',"does `make distclean' for each extention" ] ] def ToplevelInstaller.invoke instance().invoke end @singleton = nil def ToplevelInstaller.instance @singleton ||= new(File.dirname($0)) @singleton end include MetaConfigAPI def initialize(ardir_root) @config = nil @options = { 'verbose' => true } @ardir = File.expand_path(ardir_root) end def inspect "#<#{self.class} #{__id__()}>" end def invoke run_metaconfigs task = parsearg_global() @config = load_config(task) __send__ "parsearg_#{task}" init_installers __send__ "exec_#{task}" end def run_metaconfigs eval_file_ifexist "#{@ardir}/metaconfig" end def load_config(task) case task when 'config' ConfigTable.new when 'clean', 'distclean' if File.exist?('config.save') then ConfigTable.load else ConfigTable.new end else ConfigTable.load end end def init_installers @installer = Installer.new(@config, @options, @ardir, File.expand_path('.')) end # # Hook Script API bases # def srcdir_root @ardir end def objdir_root '.' end def relpath '.' end # # Option Parsing # def parsearg_global valid_task = /\A(?:#{TASKS.map {|task,desc| task }.join '|'})\z/ while arg = ARGV.shift case arg when /\A\w+\z/ raise InstallError, "invalid task: #{arg}" unless valid_task =~ arg return arg when '-q', '--quiet' @options['verbose'] = false when '--verbose' @options['verbose'] = true when '-h', '--help' print_usage $stdout exit 0 when '-v', '--version' puts "#{File.basename($0)} version #{Version}" exit 0 when '--copyright' puts Copyright exit 0 else raise InstallError, "unknown global option '#{arg}'" end end raise InstallError, <" out.puts " ruby #{File.basename $0} [] []" fmt = " %-20s %s\n" out.puts out.puts 'Global options:' out.printf fmt, '-q,--quiet', 'suppress message outputs' out.printf fmt, ' --verbose', 'output messages verbosely' out.printf fmt, '-h,--help', 'print this message' out.printf fmt, '-v,--version', 'print version and quit' out.printf fmt, ' --copyright', 'print copyright and quit' out.puts out.puts 'Tasks:' TASKS.each do |name, desc| out.printf " %-10s %s\n", name, desc end out.puts out.puts 'Options for config:' ConfigTable.each_definition do |name, (default, arg, desc, default2)| out.printf " %-20s %s [%s]\n", '--'+ name + (ConfigTable.bool_config?(name) ? '' : '='+arg), desc, default2 || default end out.printf " %-20s %s [%s]\n", '--rbconfig=path', 'your rbconfig.rb to load', "running ruby's" out.puts out.puts 'Options for install:' out.printf " %-20s %s [%s]\n", '--no-harm', 'only display what to do if given', 'off' out.printf " %-20s %s [%s]\n", '--prefix', 'install path prefix', '$prefix' out.puts end # # Task Handlers # def exec_config @installer.exec_config @config.save # must be final end def exec_setup @installer.exec_setup end def exec_install @installer.exec_install end def exec_show ConfigTable.each_name do |k| v = @config.get_raw(k) if not v or v.empty? v = '(not specified)' end printf "%-10s %s\n", k, v end end def exec_clean @installer.exec_clean end def exec_distclean @installer.exec_distclean end end class ToplevelInstallerMulti < ToplevelInstaller include HookUtils include HookScriptAPI include FileOperations def initialize(ardir) super @packages = all_dirs_in("#{@ardir}/packages") raise 'no package exists' if @packages.empty? end def run_metaconfigs eval_file_ifexist "#{@ardir}/metaconfig" @packages.each do |name| eval_file_ifexist "#{@ardir}/packages/#{name}/metaconfig" end end def init_installers @installers = {} @packages.each do |pack| @installers[pack] = Installer.new(@config, @options, "#{@ardir}/packages/#{pack}", "packages/#{pack}") end with = extract_selection(config('with')) without = extract_selection(config('without')) @selected = @installers.keys.select {|name| (with.empty? or with.include?(name)) \ and not without.include?(name) } end def extract_selection(list) a = list.split(/,/) a.each do |name| raise InstallError, "no such package: #{name}" \ unless @installers.key?(name) end a end def print_usage(f) super f.puts 'Inluded packages:' f.puts ' ' + @packages.sort.join(' ') f.puts end # # multi-package metaconfig API # attr_reader :packages def declare_packages(list) raise 'package list is empty' if list.empty? list.each do |name| raise "directory packages/#{name} does not exist"\ unless File.dir?("#{@ardir}/packages/#{name}") end @packages = list end # # Task Handlers # def exec_config run_hook 'pre-config' each_selected_installers {|inst| inst.exec_config } run_hook 'post-config' @config.save # must be final end def exec_setup run_hook 'pre-setup' each_selected_installers {|inst| inst.exec_setup } run_hook 'post-setup' end def exec_install run_hook 'pre-install' each_selected_installers {|inst| inst.exec_install } run_hook 'post-install' end def exec_clean rm_f 'config.save' run_hook 'pre-clean' each_selected_installers {|inst| inst.exec_clean } run_hook 'post-clean' end def exec_distclean rm_f 'config.save' run_hook 'pre-distclean' each_selected_installers {|inst| inst.exec_distclean } run_hook 'post-distclean' end # # lib # def each_selected_installers Dir.mkdir 'packages' unless File.dir?('packages') @selected.each do |pack| $stderr.puts "Processing the package `#{pack}' ..." if @options['verbose'] Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}") Dir.chdir "packages/#{pack}" yield @installers[pack] Dir.chdir '../..' end end def verbose? @options['verbose'] end def no_harm? @options['no-harm'] end end class Installer FILETYPES = %w( bin lib ext data ) include HookScriptAPI include HookUtils include FileOperations def initialize(config, opt, srcroot, objroot) @config = config @options = opt @srcdir = File.expand_path(srcroot) @objdir = File.expand_path(objroot) @currdir = '.' end def inspect "#<#{self.class} #{File.basename(@srcdir)}>" end # # Hook Script API bases # def srcdir_root @srcdir end def objdir_root @objdir end def relpath @currdir end # # configs/options # def no_harm? @options['no-harm'] end def verbose? @options['verbose'] end def verbose_off begin save, @options['verbose'] = @options['verbose'], false yield ensure @options['verbose'] = save end end # # TASK config # def exec_config exec_task_traverse 'config' end def config_dir_bin(rel) end def config_dir_lib(rel) end def config_dir_ext(rel) extconf if extdir?(curr_srcdir()) end def extconf opt = @options['config-opt'].join(' ') command "#{config('ruby-prog')} #{curr_srcdir()}/extconf.rb #{opt}" end def config_dir_data(rel) end # # TASK setup # def exec_setup exec_task_traverse 'setup' end def setup_dir_bin(rel) all_files_in(curr_srcdir()).each do |fname| adjust_shebang "#{curr_srcdir()}/#{fname}" end end # modify: #!/usr/bin/ruby # modify: #! /usr/bin/ruby # modify: #!ruby # not modify: #!/usr/bin/env ruby SHEBANG_RE = /\A\#!\s*\S*ruby\S*/ def adjust_shebang(path) return if no_harm? tmpfile = File.basename(path) + '.tmp' begin File.open(path, 'rb') {|r| File.open(tmpfile, 'wb') {|w| first = r.gets return unless SHEBANG_RE =~ first $stderr.puts "adjusting shebang: #{File.basename path}" if verbose? w.print first.sub(SHEBANG_RE, '#!' + config('ruby-path')) w.write r.read } } move_file tmpfile, File.basename(path) ensure File.unlink tmpfile if File.exist?(tmpfile) end end def setup_dir_lib(rel) end def setup_dir_ext(rel) make if extdir?(curr_srcdir()) end def setup_dir_data(rel) end # # TASK install # def exec_install exec_task_traverse 'install' end def install_dir_bin(rel) install_files collect_filenames_auto(), "#{config('bin-dir')}/#{rel}", 0755 end def install_dir_lib(rel) install_files ruby_scripts(), "#{config('rb-dir')}/#{rel}", 0644 end def install_dir_ext(rel) return unless extdir?(curr_srcdir()) install_files ruby_extentions('.'), "#{config('so-dir')}/#{File.dirname(rel)}", 0555 end def install_dir_data(rel) install_files collect_filenames_auto(), "#{config('data-dir')}/#{rel}", 0644 end def install_files(list, dest, mode) mkdir_p dest, @options['install-prefix'] list.each do |fname| install fname, dest, mode, @options['install-prefix'] end end def ruby_scripts collect_filenames_auto().select {|n| /\.rb\z/ =~ n } end # picked up many entries from cvs-1.11.1/src/ignore.c reject_patterns = %w( core RCSLOG tags TAGS .make.state .nse_depinfo #* .#* cvslog.* ,* .del-* *.olb *~ *.old *.bak *.BAK *.orig *.rej _$* *$ *.org *.in .* ) mapping = { '.' => '\.', '$' => '\$', '#' => '\#', '*' => '.*' } REJECT_PATTERNS = Regexp.new('\A(?:' + reject_patterns.map {|pat| pat.gsub(/[\.\$\#\*]/) {|ch| mapping[ch] } }.join('|') + ')\z') def collect_filenames_auto mapdir((existfiles() - hookfiles()).reject {|fname| REJECT_PATTERNS =~ fname }) end def existfiles all_files_in(curr_srcdir()) | all_files_in('.') end def hookfiles %w( pre-%s post-%s pre-%s.rb post-%s.rb ).map {|fmt| %w( config setup install clean ).map {|t| sprintf(fmt, t) } }.flatten end def mapdir(filelist) filelist.map {|fname| if File.exist?(fname) # objdir fname else # srcdir File.join(curr_srcdir(), fname) end } end def ruby_extentions(dir) _ruby_extentions(dir) or raise InstallError, "no ruby extention exists: 'ruby #{$0} setup' first" end DLEXT = /\.#{ ::Config::CONFIG['DLEXT'] }\z/ def _ruby_extentions(dir) Dir.open(dir) {|d| return d.select {|fname| DLEXT =~ fname } } end # # TASK clean # def exec_clean exec_task_traverse 'clean' rm_f 'config.save' rm_f 'InstalledFiles' end def clean_dir_bin(rel) end def clean_dir_lib(rel) end def clean_dir_ext(rel) return unless extdir?(curr_srcdir()) make 'clean' if File.file?('Makefile') end def clean_dir_data(rel) end # # TASK distclean # def exec_distclean exec_task_traverse 'distclean' rm_f 'config.save' rm_f 'InstalledFiles' end def distclean_dir_bin(rel) end def distclean_dir_lib(rel) end def distclean_dir_ext(rel) return unless extdir?(curr_srcdir()) make 'distclean' if File.file?('Makefile') end # # lib # def exec_task_traverse(task) run_hook "pre-#{task}" FILETYPES.each do |type| if config('without-ext') == 'yes' and type == 'ext' $stderr.puts 'skipping ext/* by user option' if verbose? next end traverse task, type, "#{task}_dir_#{type}" end run_hook "post-#{task}" end def traverse(task, rel, mid) dive_into(rel) { run_hook "pre-#{task}" __send__ mid, rel.sub(%r[\A.*?(?:/|\z)], '') all_dirs_in(curr_srcdir()).each do |d| traverse task, "#{rel}/#{d}", mid end run_hook "post-#{task}" } end def dive_into(rel) return unless File.dir?("#{@srcdir}/#{rel}") dir = File.basename(rel) Dir.mkdir dir unless File.dir?(dir) prevdir = Dir.pwd Dir.chdir dir $stderr.puts '---> ' + rel if verbose? @currdir = rel yield Dir.chdir prevdir $stderr.puts '<--- ' + rel if verbose? @currdir = File.dirname(rel) end end if $0 == __FILE__ begin if multipackage_install? ToplevelInstallerMulti.invoke else ToplevelInstaller.invoke end rescue raise if $DEBUG $stderr.puts $!.message $stderr.puts "Try 'ruby #{$0} --help' for detailed usage." exit 1 end end ruby-erubis-2.7.0/test/000077500000000000000000000000001170760342400147535ustar00rootroot00000000000000ruby-erubis-2.7.0/test/assert-text-equal.rb000066400000000000000000000023631170760342400206740ustar00rootroot00000000000000### ### $Release: 2.7.0 $ ### copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ### require 'test/unit' require 'tempfile' module Test module Unit class TestCase def assert_text_equal(expected, actual, message=nil, diffopt='-u', flag_cut=true) if expected == actual assert(true) return end if expected[-1] != ?\n || actual[-1] != ?\n expected += "\n" actual += "\n" end begin expfile = Tempfile.new(".expected.") expfile.write(expected); expfile.flush() actfile = Tempfile.new(".actual.") actfile.write(actual); actfile.flush() diff = `diff #{diffopt} #{expfile.path} #{actfile.path}` ensure expfile.close(true) if expfile actfile.close(true) if actfile end # cut 1st & 2nd lines message = (flag_cut ? diff.gsub(/\A.*\n.*\n/, '') : diff) unless message #raise Test::Unit::AssertionFailedError.new(message) assert_block(message) { false } # or assert(false, message) end alias assert_equal_with_diff assert_text_equal # for compatibility alias assert_text_equals assert_text_equal # for typo end end end ruby-erubis-2.7.0/test/data/000077500000000000000000000000001170760342400156645ustar00rootroot00000000000000ruby-erubis-2.7.0/test/data/users-guide/000077500000000000000000000000001170760342400201205ustar00rootroot00000000000000ruby-erubis-2.7.0/test/data/users-guide/Example.ejava000066400000000000000000000022671170760342400225320ustar00rootroot00000000000000<% import java.util.*; public class Example { private String user; private String[] list; public example(String user, String[] list) { this.user = user; this.list = list; } public String view() { StringBuffer _buf = new StringBuffer(); %>

    Hello <%= user %>!

    <% for (int i = 0; i < list.length; i++) { %> "> <% } %>
    <%= i + 1 %> <%== list[i] %>
    <% return _buf.toString(); } public static void main(String[] args) { String[] list = { "", "b&b", "\"ccc\"" }; Example ex = Example.new("Erubis", list); System.out.print(ex.view()); } public static String escape(String s) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); switch (ch) { case '<': sb.append("<"); break; case '>': sb.append(">"); break; case '&': sb.append("&"); break; case '"': sb.append("""); break; default: sb.append(ch); } } return sb.toString(); } } %> ruby-erubis-2.7.0/test/data/users-guide/array_example.result000066400000000000000000000003541170760342400242130ustar00rootroot00000000000000$ erubis -xE Array example.eruby _buf = []; _buf << '
    '; for item in list _buf << '

    '; _buf << ( item ).to_s; _buf << '

    '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '

    '; end _buf << '
    '; _buf ruby-erubis-2.7.0/test/data/users-guide/arraybuffer_example.result000066400000000000000000000003671170760342400254110ustar00rootroot00000000000000$ erubis -xE ArrayBuffer example.eruby _buf = []; _buf << '
    '; for item in list _buf << '

    '; _buf << ( item ).to_s; _buf << '

    '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '

    '; end _buf << '
    '; _buf.join ruby-erubis-2.7.0/test/data/users-guide/bipattern-example.rhtml000066400000000000000000000001121170760342400246030ustar00rootroot00000000000000<% for item in list %> [= item =] [== item =] <% end %> ruby-erubis-2.7.0/test/data/users-guide/bipattern_example.result000066400000000000000000000003311170760342400250600ustar00rootroot00000000000000$ erubis -xE BiPattern bipattern-example.rhtml _buf = ''; for item in list _buf << ' '; _buf << ( item ).to_s; _buf << ' '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << ' '; end _buf.to_s ruby-erubis-2.7.0/test/data/users-guide/bufvar-example.rb000066400000000000000000000003671170760342400233710ustar00rootroot00000000000000require 'erubis' input = File.read('example.eruby') puts "----- default -----" eruby = Erubis::FastEruby.new(input) puts eruby.src puts "----- with :bufvar option -----" eruby = Erubis::FastEruby.new(input, :bufvar=>'@_out_buf') print eruby.src ruby-erubis-2.7.0/test/data/users-guide/bufvar-example.result000066400000000000000000000006741170760342400243050ustar00rootroot00000000000000$ ruby bufvar-example.rb ----- default ----- _buf = ''; _buf << %Q`
    \n` for item in list _buf << %Q`

    #{ item }

    #{Erubis::XmlHelper.escape_xml( item )}

    \n` end _buf << %Q`
    \n` _buf.to_s ----- with :bufvar option ----- @_out_buf = ''; @_out_buf << %Q`
    \n` for item in list @_out_buf << %Q`

    #{ item }

    #{Erubis::XmlHelper.escape_xml( item )}

    \n` end @_out_buf << %Q`
    \n` @_out_buf.to_s ruby-erubis-2.7.0/test/data/users-guide/context.rb000066400000000000000000000002551170760342400221330ustar00rootroot00000000000000@title = 'Users List' @users = [ { 'name'=>'foo', 'mail'=>'foo@mail.com' }, { 'name'=>'bar', 'mail'=>'bar@mail.net' }, { 'name'=>'baz', 'mail'=>'baz@mail.org' }, ] ruby-erubis-2.7.0/test/data/users-guide/context.yaml000066400000000000000000000002161170760342400224670ustar00rootroot00000000000000title: Users List users: - name: foo mail: foo@mail.com - name: bar mail: bar@mail.net - name: baz mail: baz@mail.org ruby-erubis-2.7.0/test/data/users-guide/def_method.rb000066400000000000000000000007311170760342400225440ustar00rootroot00000000000000require 'erubis' s = "hello <%= name %>" eruby = Erubis::Eruby.new(s) filename = 'hello.rhtml' ## define instance method to Dummy class (or module) class Dummy; end eruby.def_method(Dummy, 'render(name)', filename) # filename is optional p Dummy.new.render('world') #=> "hello world" ## define singleton method to dummy object obj = Object.new eruby.def_method(obj, 'render(name)', filename) # filename is optional p obj.render('world') #=> "hello world" ruby-erubis-2.7.0/test/data/users-guide/def_method.result000066400000000000000000000000611170760342400234530ustar00rootroot00000000000000$ ruby def_method.rb "hello world" "hello world" ruby-erubis-2.7.0/test/data/users-guide/escape_example.result000066400000000000000000000003621170760342400243340ustar00rootroot00000000000000$ erubis -xE Escape example.eruby _buf = ''; _buf << '
    '; for item in list _buf << '

    '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '

    '; _buf << ( item ).to_s; _buf << '

    '; end _buf << '
    '; _buf.to_s ruby-erubis-2.7.0/test/data/users-guide/example.ec000066400000000000000000000006151170760342400220660ustar00rootroot00000000000000<% #include int main(int argc, char *argv[]) { int i; %>

    Hello <%= "%s", argv[0] %>!

    <% for (i = 1; i < argc; i++) { %> "> <% } %>
    <%= "%d", i %> <%= "%s", argv[i] %>
    <% return 0; } %> ruby-erubis-2.7.0/test/data/users-guide/example.ecpp000066400000000000000000000007631170760342400224320ustar00rootroot00000000000000<% #include #include #include int main(int argc, char *argv[]) { std::stringstream _buf; %>

    Hello <%= argv[0] %>!

    <% for (int i = 1; i < argc; i++) { %> "> <% } %>
    <%= i %> <%= argv[i] %>
    <% std::string output = _buf.str(); std::cout << output; return 0; } %> ruby-erubis-2.7.0/test/data/users-guide/example.ejs000066400000000000000000000005721170760342400222620ustar00rootroot00000000000000<% var user = 'Erubis'; var list = ['', 'b&b', '"ccc"']; %>

    Hello <%= user %>!

    <% var i; %> <% for (i = 0; i < list.length; i++) { %> <% } %>
    <%= i + 1 %> <%= list[i] %>
    ruby-erubis-2.7.0/test/data/users-guide/example.eperl000066400000000000000000000005121170760342400226020ustar00rootroot00000000000000<% my $user = 'Erubis'; my @list = ('', 'b&b', '"ccc"'); %>

    Hello <%= $user %>!

    <% $i = 0; %> <% for $item (@list) { %> "> <% } %>
    <%= $i %> <%= $item %>
    ruby-erubis-2.7.0/test/data/users-guide/example.ephp000066400000000000000000000005201170760342400224260ustar00rootroot00000000000000

    Hello <%= $user %>!

    <% $i = 0; %> <% foreach ($list as $item) { %> <% $i++; %> <% } %>
    <%= $i %> <%== $item %>
    ruby-erubis-2.7.0/test/data/users-guide/example.eruby000066400000000000000000000001311170760342400226160ustar00rootroot00000000000000
    <% for item in list %>

    <%= item %>

    <%== item %>

    <% end %>
    ruby-erubis-2.7.0/test/data/users-guide/example.escheme000066400000000000000000000006401170760342400231060ustar00rootroot00000000000000 <% (let ((user "Erubis") (items '("" "b&b" "\"ccc\"")) (i 0)) %>

    Hello <%= user %>!

    <% (for-each (lambda (item) (set! i (+ i 1)) %> "> <% ) ; lambda end items) ; for-each end %>
    <%= i %> <%= item %>
    <% ) ; let end %> ruby-erubis-2.7.0/test/data/users-guide/example1.eruby000066400000000000000000000001721170760342400227040ustar00rootroot00000000000000
      <% for item in list %>
    • <%= item %>
    • <% end %> <%# here is ignored because starting with '#' %>
    ruby-erubis-2.7.0/test/data/users-guide/example1.rb000066400000000000000000000010001170760342400221500ustar00rootroot00000000000000require 'erubis' input = File.read('example1.eruby') eruby = Erubis::Eruby.new(input) # create Eruby object puts "---------- script source ---" puts eruby.src # print script source puts "---------- result ----------" list = ['aaa', 'bbb', 'ccc'] puts eruby.result(binding()) # get result ## or puts eruby.result(:list=>list) # or pass Hash instead of Binding ## # or ## eruby = Erubis::Eruby.new ## input = File.read('example1.eruby') ## src = eruby.convert(input) ## eval src ruby-erubis-2.7.0/test/data/users-guide/example1.result000066400000000000000000000004261170760342400230760ustar00rootroot00000000000000$ ruby example1.rb ---------- script source --- _buf = ''; _buf << '
      '; for item in list _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • '; end _buf << '
    '; _buf.to_s ---------- result ----------
    • aaa
    • bbb
    • ccc
    ruby-erubis-2.7.0/test/data/users-guide/example10.rb000066400000000000000000000001531170760342400222400ustar00rootroot00000000000000require 'erubis' input = File.read('example10.xhtml') eruby = Erubis::PI::Eruby.new(input) print eruby.src ruby-erubis-2.7.0/test/data/users-guide/example10.result000066400000000000000000000005351170760342400231570ustar00rootroot00000000000000$ ruby example10.rb _buf = ''; _buf << ' '; lang = 'en' list = ['', 'b&b', '"ccc"'] _buf << '
      '; for item in list _buf << '
    • '; _buf << Erubis::XmlHelper.escape_xml(item); _buf << '
    • '; end _buf << '
    '; _buf.to_s ruby-erubis-2.7.0/test/data/users-guide/example10.xhtml000066400000000000000000000003161170760342400227720ustar00rootroot00000000000000 ', 'b&b', '"ccc"'] ?>
    • @{item}@
    ruby-erubis-2.7.0/test/data/users-guide/example10_x.result000066400000000000000000000005521170760342400235050ustar00rootroot00000000000000$ erubis -x --pi example10.xhtml _buf = ''; _buf << ' '; lang = 'en' list = ['', 'b&b', '"ccc"'] _buf << '
      '; for item in list _buf << '
    • '; _buf << Erubis::XmlHelper.escape_xml(item); _buf << '
    • '; end _buf << '
    '; _buf.to_s ruby-erubis-2.7.0/test/data/users-guide/example11.php000066400000000000000000000006521170760342400224310ustar00rootroot00000000000000

    List

    not found.

    ruby-erubis-2.7.0/test/data/users-guide/example11.result000066400000000000000000000004351170760342400231570ustar00rootroot00000000000000$ erubis -X example11.rhtml _buf = ''; if @list.nil? || @list.empty? else @list.each_with_index do |item, i| _buf << ( i % 2 == 0 ? '#FCC' : '#CCF' ).to_s; _buf << ( item ).to_s; end end _buf.to_s ruby-erubis-2.7.0/test/data/users-guide/example11.rhtml000066400000000000000000000011221170760342400227610ustar00rootroot00000000000000

    List

    <% if @list.nil? || @list.empty? %>

    not found.

    <% else %> <% @list.each_with_index do |item, i| %> <% end %>
    <%= item %>
    <% end %> ruby-erubis-2.7.0/test/data/users-guide/example11_C.result000066400000000000000000000004211170760342400234140ustar00rootroot00000000000000$ erubis -XC example11.rhtml _buf = ''; if @list.nil? || @list.empty? else @list.each_with_index do |item, i| _buf << ( i % 2 == 0 ? '#FCC' : '#CCF' ).to_s; _buf << ( item ).to_s; end end _buf.to_s ruby-erubis-2.7.0/test/data/users-guide/example11_N.result000066400000000000000000000005401170760342400234310ustar00rootroot00000000000000$ erubis -XNU example11.rhtml 1: _buf = ''; 7: if @list.nil? || @list.empty? 9: else 12: @list.each_with_index do |item, i| 13: _buf << ( i % 2 == 0 ? '#FCC' : '#CCF' ).to_s; 14: _buf << ( item ).to_s; 16: end 19: end 22: _buf.to_s ruby-erubis-2.7.0/test/data/users-guide/example11_U.result000066400000000000000000000004271170760342400234440ustar00rootroot00000000000000$ erubis -XU example11.rhtml _buf = ''; if @list.nil? || @list.empty? else @list.each_with_index do |item, i| _buf << ( i % 2 == 0 ? '#FCC' : '#CCF' ).to_s; _buf << ( item ).to_s; end end _buf.to_s ruby-erubis-2.7.0/test/data/users-guide/example11_php.result000066400000000000000000000005761170760342400240340ustar00rootroot00000000000000$ erubis -XNU -l php --pi=php --trim=false example11.php 5: 7: 10: 11: 12: 13: 15: 18: ruby-erubis-2.7.0/test/data/users-guide/example1_x.result000066400000000000000000000002541170760342400234240ustar00rootroot00000000000000$ erubis -x example1.eruby _buf = ''; _buf << '
      '; for item in list _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • '; end _buf << '
    '; _buf.to_s ruby-erubis-2.7.0/test/data/users-guide/example2.eruby000066400000000000000000000001171170760342400227040ustar00rootroot00000000000000
      <% for item in list %>
    • <%= item %>
    • <% end %>
    ruby-erubis-2.7.0/test/data/users-guide/example2.rb000066400000000000000000000004701170760342400221630ustar00rootroot00000000000000require 'erubis' input = File.read('example2.eruby') eruby = Erubis::Eruby.new(input, :trim=>false) puts "----- script source ---" puts eruby.src # print script source puts "----- result ----------" list = ['aaa', 'bbb', 'ccc'] puts eruby.result(binding()) # get result ruby-erubis-2.7.0/test/data/users-guide/example2.result000066400000000000000000000005651170760342400231030ustar00rootroot00000000000000$ ruby example2.rb ----- script source --- _buf = ''; _buf << '
      '; _buf << ' '; for item in list ; _buf << ' '; _buf << '
    • '; _buf << ( item ).to_s; _buf << ' '; _buf << '
    • '; _buf << ' '; end ; _buf << ' '; _buf << '
    '; _buf.to_s ----- result ----------
    • aaa
    • bbb
    • ccc
    ruby-erubis-2.7.0/test/data/users-guide/example2_trim.result000066400000000000000000000003761170760342400241360ustar00rootroot00000000000000$ erubis -x --trim=false example2.eruby _buf = ''; _buf << '
      '; _buf << ' '; for item in list ; _buf << ' '; _buf << '
    • '; _buf << ( item ).to_s; _buf << ' '; _buf << '
    • '; _buf << ' '; end ; _buf << ' '; _buf << '
    '; _buf.to_s ruby-erubis-2.7.0/test/data/users-guide/example2_x.result000066400000000000000000000002771170760342400234320ustar00rootroot00000000000000$ erubis -x example2.eruby _buf = ''; _buf << '
      '; for item in list _buf << '
    • '; _buf << ( item ).to_s; _buf << ' '; _buf << '
    • '; end _buf << '
    '; _buf.to_s ruby-erubis-2.7.0/test/data/users-guide/example3.eruby000066400000000000000000000001441170760342400227050ustar00rootroot00000000000000<% for item in list %>

    <%= item %>

    <%== item %>

    <%=== item %>

    <% end %> ruby-erubis-2.7.0/test/data/users-guide/example3.rb000066400000000000000000000005201170760342400221600ustar00rootroot00000000000000require 'erubis' input = File.read('example3.eruby') eruby = Erubis::EscapedEruby.new(input) # or Erubis::XmlEruby puts "----- script source ---" puts eruby.src # print script source puts "----- result ----------" list = ['', 'b&b', '"ccc"'] puts eruby.result(binding()) # get result ruby-erubis-2.7.0/test/data/users-guide/example31.result000066400000000000000000000007201170760342400231560ustar00rootroot00000000000000$ ruby example3.rb 2> stderr.log ----- script source --- _buf = ''; for item in list _buf << '

    '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '

    '; _buf << ( item ).to_s; _buf << '

    '; $stderr.puts("*** debug: item=#{(item).inspect}"); _buf << '

    '; end _buf.to_s ----- result ----------

    <aaa>

    b&b

    b&b

    "ccc"

    "ccc"

    ruby-erubis-2.7.0/test/data/users-guide/example32.result000066400000000000000000000001311170760342400231530ustar00rootroot00000000000000$ cat stderr.log *** debug: item="" *** debug: item="b&b" *** debug: item="\"ccc\"" ruby-erubis-2.7.0/test/data/users-guide/example3_e.result000066400000000000000000000004271170760342400234050ustar00rootroot00000000000000$ erubis -l ruby -e example3.eruby _buf = ''; for item in list _buf << '

    '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '

    '; _buf << ( item ).to_s; _buf << '

    '; $stderr.puts("*** debug: item=#{(item).inspect}"); _buf << '

    '; end _buf.to_s ruby-erubis-2.7.0/test/data/users-guide/example4.eruby000066400000000000000000000001051170760342400227030ustar00rootroot00000000000000

    ruby-erubis-2.7.0/test/data/users-guide/example4.rb000066400000000000000000000006161170760342400221670ustar00rootroot00000000000000require 'erubis' input = File.read('example4.eruby') eruby = Erubis::Eruby.new(input, :pattern=>'') # or '<(?:!--)?% %(?:--)?>' puts "---------- script source ---" puts eruby.src # print script source puts "---------- result ----------" list = ['aaa', 'bbb', 'ccc'] puts eruby.result(binding()) # get result ruby-erubis-2.7.0/test/data/users-guide/example4.result000066400000000000000000000003321170760342400230750ustar00rootroot00000000000000$ ruby example4.rb ---------- script source --- _buf = ''; for item in list _buf << '

    '; _buf << ( item ).to_s; _buf << '

    '; end _buf.to_s ---------- result ----------

    aaa

    bbb

    ccc

    ruby-erubis-2.7.0/test/data/users-guide/example4_x.result000066400000000000000000000002211170760342400234210ustar00rootroot00000000000000$ erubis -x -p '' example4.eruby _buf = ''; for item in list _buf << '

    '; _buf << ( item ).to_s; _buf << '

    '; end _buf.to_s ruby-erubis-2.7.0/test/data/users-guide/example5.eruby000066400000000000000000000001371170760342400227110ustar00rootroot00000000000000<%= @val %>
      <% for item in @list %>
    • <%= item %>
    • <% end %>
    ruby-erubis-2.7.0/test/data/users-guide/example5.rb000066400000000000000000000006731170760342400221730ustar00rootroot00000000000000require 'erubis' input = File.read('example5.eruby') eruby = Erubis::Eruby.new(input) # create Eruby object ## create context object ## (key means var name, which may be string or symbol.) context = { :val => 'Erubis Example', 'list' => ['aaa', 'bbb', 'ccc'], } ## or # context = Erubis::Context.new() # context['val'] = 'Erubis Example' # context[:list] = ['aaa', 'bbb', 'ccc'], puts eruby.evaluate(context) # get result ruby-erubis-2.7.0/test/data/users-guide/example5.result000066400000000000000000000001471170760342400231020ustar00rootroot00000000000000$ ruby example5.rb Erubis Example
    • aaa
    • bbb
    • ccc
    ruby-erubis-2.7.0/test/data/users-guide/example6.rb000066400000000000000000000004171170760342400221700ustar00rootroot00000000000000class MyData attr_accessor :val, :list end ## any object can be a context object mydata = MyData.new mydata.val = 'Erubis Example' mydata.list = ['aaa', 'bbb', 'ccc'] require 'erubis' eruby = Erubis::Eruby.new(File.read('example5.eruby')) puts eruby.evaluate(mydata) ruby-erubis-2.7.0/test/data/users-guide/example6.result000066400000000000000000000001471170760342400231030ustar00rootroot00000000000000$ ruby example6.rb Erubis Example
    • aaa
    • bbb
    • ccc
    ruby-erubis-2.7.0/test/data/users-guide/example7.eruby000066400000000000000000000002261170760342400227120ustar00rootroot00000000000000

    <%= @title %>

    ruby-erubis-2.7.0/test/data/users-guide/example71.result000066400000000000000000000003621170760342400231640ustar00rootroot00000000000000$ erubis -f context.yaml example7.eruby

    Users List

    ruby-erubis-2.7.0/test/data/users-guide/example72.result000066400000000000000000000003601170760342400231630ustar00rootroot00000000000000$ erubis -f context.rb example7.eruby

    Users List

    ruby-erubis-2.7.0/test/data/users-guide/example8.eruby000066400000000000000000000001321170760342400227070ustar00rootroot00000000000000

    <%= @title %>

      <% for item in @list %>
    • <%= item %>
    • <% end %>
    ruby-erubis-2.7.0/test/data/users-guide/example8_ruby.result000066400000000000000000000002131170760342400241400ustar00rootroot00000000000000$ erubis -c '@title="Example"; @list=%w[AAA BBB CCC]' example8.eruby

    Example

    • AAA
    • BBB
    • CCC
    ruby-erubis-2.7.0/test/data/users-guide/example8_yaml.result000066400000000000000000000002131170760342400241210ustar00rootroot00000000000000$ erubis -c '{title: Example, list: [AAA, BBB, CCC]}' example8.eruby

    Example

    • AAA
    • BBB
    • CCC
    ruby-erubis-2.7.0/test/data/users-guide/example9.eruby000066400000000000000000000000661170760342400227160ustar00rootroot00000000000000<% for item in @list %> <%= item %> <% end %> ruby-erubis-2.7.0/test/data/users-guide/example9.rb000066400000000000000000000004351170760342400221730ustar00rootroot00000000000000require 'erubis' input = File.read('example9.eruby') eruby1 = Erubis::Eruby.new(input) eruby2 = Erubis::Eruby.new(input, :preamble=>false, :postamble=>false) puts eruby1.src # print preamble and postamble puts "--------------" puts eruby2.src # don't print preamble and postamble ruby-erubis-2.7.0/test/data/users-guide/example9.result000066400000000000000000000003321170760342400231020ustar00rootroot00000000000000$ ruby example9.rb _buf = ''; for item in @list _buf << ' '; _buf << ( item ).to_s; _buf << ' '; end _buf.to_s -------------- for item in @list _buf << ' '; _buf << ( item ).to_s; _buf << ' '; end ruby-erubis-2.7.0/test/data/users-guide/example91.result000066400000000000000000000002011170760342400231560ustar00rootroot00000000000000$ erubis -x example9.eruby _buf = ''; for item in @list _buf << ' '; _buf << ( item ).to_s; _buf << ' '; end _buf.to_s ruby-erubis-2.7.0/test/data/users-guide/example92.result000066400000000000000000000001601170760342400231630ustar00rootroot00000000000000$ erubis -x -b example9.eruby for item in @list _buf << ' '; _buf << ( item ).to_s; _buf << ' '; end ruby-erubis-2.7.0/test/data/users-guide/example_c.result000066400000000000000000000013741170760342400233220ustar00rootroot00000000000000$ erubis -l cpp example.ecpp #line 1 "example.ecpp" #include #include #include int main(int argc, char *argv[]) { std::stringstream _buf; _buf << "\n" " \n" "

    Hello "; _buf << (argv[0]); _buf << "!

    \n" " \n" " \n"; for (int i = 1; i < argc; i++) { _buf << " \n" " \n" " \n" " \n"; } _buf << " \n" "
    "; _buf << (i); _buf << ""; _buf << (argv[i]); _buf << "
    \n" " \n" "\n"; std::string output = _buf.str(); std::cout << output; return 0; } ruby-erubis-2.7.0/test/data/users-guide/example_java.result000066400000000000000000000030141170760342400240120ustar00rootroot00000000000000$ erubis -b -l java example.ejava import java.util.*; public class Example { private String user; private String[] list; public example(String user, String[] list) { this.user = user; this.list = list; } public String view() { StringBuffer _buf = new StringBuffer(); _buf.append("\n" + " \n" + "

    Hello "); _buf.append(user); _buf.append("!

    \n" + " \n" + " \n"); for (int i = 0; i < list.length; i++) { _buf.append(" \n" + " \n" + " \n" + " \n"); } _buf.append(" \n" + "
    "); _buf.append(i + 1); _buf.append(""); _buf.append(escape(list[i])); _buf.append("
    \n" + " \n" + "\n"); return _buf.toString(); } public static void main(String[] args) { String[] list = { "", "b&b", "\"ccc\"" }; Example ex = Example.new("Erubis", list); System.out.print(ex.view()); } public static String escape(String s) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); switch (ch) { case '<': sb.append("<"); break; case '>': sb.append(">"); break; case '&': sb.append("&"); break; case '"': sb.append("""); break; default: sb.append(ch); } } return sb.toString(); } } ruby-erubis-2.7.0/test/data/users-guide/example_js.result000066400000000000000000000011261170760342400235070ustar00rootroot00000000000000$ erubis -l js example.ejs var _buf = []; var user = 'Erubis'; var list = ['', 'b&b', '"ccc"']; _buf.push("\n\ \n\

    Hello "); _buf.push(user); _buf.push("!

    \n\ \n\ \n"); var i; for (i = 0; i < list.length; i++) { _buf.push(" \n\ \n\ \n\ \n"); } _buf.push(" \n\
    "); _buf.push(i + 1); _buf.push(""); _buf.push(list[i]); _buf.push("
    \n\ \n\ \n"); document.write(_buf.join("")); ruby-erubis-2.7.0/test/data/users-guide/example_perl.result000066400000000000000000000007031170760342400240350ustar00rootroot00000000000000$ erubis -l perl example.eperl use HTML::Entities; my $user = 'Erubis'; my @list = ('', 'b&b', '"ccc"'); print('

    Hello '); print($user); print('!

    '); $i = 0; for $item (@list) { print(' '); } print('
    '); print($i); print(' '); print($item); print('
    '); ruby-erubis-2.7.0/test/data/users-guide/example_php.result000066400000000000000000000006621170760342400236660ustar00rootroot00000000000000$ erubis -l php example.ephp <?xml version="1.0"?>

    Hello !

    ruby-erubis-2.7.0/test/data/users-guide/example_scheme.result000066400000000000000000000011401170760342400243330ustar00rootroot00000000000000$ erubis -l scheme example.escheme (let ((_buf '())) (define (_add x) (set! _buf (cons x _buf))) (_add " \n") (let ((user "Erubis") (items '("" "b&b" "\"ccc\"")) (i 0)) (_add "

    Hello ")(_add user)(_add "!

    \n") (for-each (lambda (item) (set! i (+ i 1)) (_add " \n") ) ; lambda end items) ; for-each end (_add "
    ")(_add i)(_add " ")(_add item)(_add "
    \n") ) ; let end (_add " \n") (reverse _buf)) ruby-erubis-2.7.0/test/data/users-guide/example_scheme_display.result000066400000000000000000000011061170760342400260620ustar00rootroot00000000000000$ erubis -l scheme --func=display example.escheme (display " \n") (let ((user "Erubis") (items '("" "b&b" "\"ccc\"")) (i 0)) (display "

    Hello ")(display user)(display "!

    \n") (for-each (lambda (item) (set! i (+ i 1)) (display " \n") ) ; lambda end items) ; for-each end (display "
    ")(display i)(display " ")(display item)(display "
    \n") ) ; let end (display " \n") ruby-erubis-2.7.0/test/data/users-guide/fasteruby-example.rb000066400000000000000000000003061170760342400241010ustar00rootroot00000000000000require 'erubis' input = File.read('example.eruby') puts "----- Erubis::Eruby -----" print Erubis::Eruby.new(input).src puts "----- Erubis::FastEruby -----" print Erubis::FastEruby.new(input).src ruby-erubis-2.7.0/test/data/users-guide/fasteruby-example.result000066400000000000000000000007171170760342400250220ustar00rootroot00000000000000$ ruby fasteruby-example.rb ----- Erubis::Eruby ----- _buf = ''; _buf << '
    '; for item in list _buf << '

    '; _buf << ( item ).to_s; _buf << '

    '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '

    '; end _buf << '
    '; _buf.to_s ----- Erubis::FastEruby ----- _buf = ''; _buf << %Q`
    \n` for item in list _buf << %Q`

    #{ item }

    #{Erubis::XmlHelper.escape_xml( item )}

    \n` end _buf << %Q`
    \n` _buf.to_s ruby-erubis-2.7.0/test/data/users-guide/fasteruby.rb000066400000000000000000000004711170760342400224530ustar00rootroot00000000000000require 'erubis' input = File.read('fasteruby.rhtml') eruby = Erubis::FastEruby.new(input) # create Eruby object puts "---------- script source ---" puts eruby.src puts "---------- result ----------" context = { :title=>'Example', :list=>['aaa', 'bbb', 'ccc'] } output = eruby.evaluate(context) print output ruby-erubis-2.7.0/test/data/users-guide/fasteruby.result000066400000000000000000000012431170760342400233640ustar00rootroot00000000000000$ ruby fasteruby.rb ---------- script source --- _buf = ''; _buf << %Q`

    #{Erubis::XmlHelper.escape_xml( @title )}

    \n` i = 0 for item in @list i += 1 _buf << %Q` \n` end _buf << %Q`
    #{ i } #{Erubis::XmlHelper.escape_xml( item )}
    \n` _buf.to_s ---------- result ----------

    Example

    1 aaa
    2 bbb
    3 ccc
    ruby-erubis-2.7.0/test/data/users-guide/fasteruby.rhtml000066400000000000000000000003431170760342400231740ustar00rootroot00000000000000

    <%== @title %>

    <% i = 0 %> <% for item in @list %> <% i += 1 %> <% end %>
    <%= i %> <%== item %>
    ruby-erubis-2.7.0/test/data/users-guide/headerfooter-example.eruby000066400000000000000000000001651170760342400252720ustar00rootroot00000000000000 <% for item in items %> <%= item %> <% end %> ruby-erubis-2.7.0/test/data/users-guide/headerfooter-example2.rb000066400000000000000000000003131170760342400246240ustar00rootroot00000000000000require 'erubis' class HeaderFooterEruby < Erubis::Eruby include Erubis::HeaderFooterEnhancer end input = File.read('headerfooter-example2.rhtml') eruby = HeaderFooterEruby.new(input) print eruby.src ruby-erubis-2.7.0/test/data/users-guide/headerfooter-example2.rhtml000066400000000000000000000001371170760342400253530ustar00rootroot00000000000000 : ruby-erubis-2.7.0/test/data/users-guide/headerfooter_example.result000066400000000000000000000002721170760342400255430ustar00rootroot00000000000000$ erubis -xE HeaderFooter headerfooter-example.eruby def list_items(items) _buf = ''; for item in items _buf << ' '; _buf << ( item ).to_s; _buf << ' '; end _buf.to_s end ruby-erubis-2.7.0/test/data/users-guide/headerfooter_example2.result000066400000000000000000000002561170760342400256270ustar00rootroot00000000000000$ erubis -xE HeaderFooter headerfooter-example2.rhtml def page(list) _buf = ''; _buf << ' '; _buf << ' : '; _buf << ' '; _buf.to_s end ruby-erubis-2.7.0/test/data/users-guide/interpolation_example.result000066400000000000000000000003641170760342400257650ustar00rootroot00000000000000$ erubis -xE DeleteIndent example.eruby _buf = ''; _buf << '
    '; for item in list _buf << '

    '; _buf << ( item ).to_s; _buf << '

    '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '

    '; end _buf << '
    '; _buf.to_s ruby-erubis-2.7.0/test/data/users-guide/main_program1.rb000066400000000000000000000005301170760342400231770ustar00rootroot00000000000000require 'erubis' eruby = Erubis::Eruby.new(File.read('template1.rhtml')) items = ['foo', 'bar', 'baz'] x = 1 ## local variable 'x' and 'eruby' are passed to template as well as 'items'! print eruby.result(binding()) ## local variable 'x' is changed unintendedly because it is changed in template! puts "** debug: x=#{x.inspect}" #=> "baz" ruby-erubis-2.7.0/test/data/users-guide/main_program1.result000066400000000000000000000002051170760342400241110ustar00rootroot00000000000000$ ruby main_program1.rb item = foo item = bar item = baz ** debug: local variables=["eruby", "items", "x", "_buf"] ** debug: x="baz" ruby-erubis-2.7.0/test/data/users-guide/main_program2.rb000066400000000000000000000004111170760342400231760ustar00rootroot00000000000000require 'erubis' eruby = Erubis::Eruby.new(File.read('template2.rhtml')) items = ['foo', 'bar', 'baz'] x = 1 ## only 'items' are passed to template print eruby.evaluate(:items=>items) ## local variable 'x' is not changed! puts "** debug: x=#{x.inspect}" #=> 1 ruby-erubis-2.7.0/test/data/users-guide/main_program2.result000066400000000000000000000001731170760342400241160ustar00rootroot00000000000000$ ruby main_program2.rb item = foo item = bar item = baz ** debug: local variables=["_context", "x", "_buf"] ** debug: x=1 ruby-erubis-2.7.0/test/data/users-guide/nocode-example.eruby000066400000000000000000000004261170760342400240720ustar00rootroot00000000000000

    List

    <% if !@list || @list.empty? %>

    not found.

    <% else %> <% @list.each_with_index do |item, i| %> <% end %>
    <%= item %>
    <% end %> ruby-erubis-2.7.0/test/data/users-guide/nocode-php.result000066400000000000000000000007021170760342400234130ustar00rootroot00000000000000$ erubis -l php --pi=php -N -E NoCode --trim=false notext-example.php 1: 2: 3:

    List

    4: 5:

    not found.

    6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16:
    17: 18: 19: ruby-erubis-2.7.0/test/data/users-guide/nocode_example.result000066400000000000000000000002421170760342400243400ustar00rootroot00000000000000$ erubis -xE NoCode notext-example.eruby

    List

    not found.

    ruby-erubis-2.7.0/test/data/users-guide/normal-eruby-test.eruby000066400000000000000000000001351170760342400245600ustar00rootroot00000000000000<% def list_items(items) %> <% for item in items %>
  • <%= item %>
  • <% end %> <% end %> ruby-erubis-2.7.0/test/data/users-guide/normal_eruby_test.result000066400000000000000000000002511170760342400251130ustar00rootroot00000000000000$ erubis -x normal-eruby-test.eruby _buf = ''; def list_items(items) for item in items _buf << '
  • '; _buf << ( item ).to_s; _buf << '
  • '; end end _buf.to_s ruby-erubis-2.7.0/test/data/users-guide/notext-example.eruby000066400000000000000000000004261170760342400241440ustar00rootroot00000000000000

    List

    <% if !@list || @list.empty? %>

    not found.

    <% else %> <% @list.each_with_index do |item, i| %> <% end %>
    <%= item %>
    <% end %> ruby-erubis-2.7.0/test/data/users-guide/notext-example.php000066400000000000000000000006571170760342400236130ustar00rootroot00000000000000

    List

    not found.

    ruby-erubis-2.7.0/test/data/users-guide/notext-php.result000066400000000000000000000010031170760342400234600ustar00rootroot00000000000000$ erubis -l php --pi=php -N -E NoText --trim=false notext-example.php 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: ruby-erubis-2.7.0/test/data/users-guide/notext_example.result000066400000000000000000000004071170760342400244150ustar00rootroot00000000000000$ erubis -xE NoText notext-example.eruby _buf = ''; if !@list || @list.empty? else @list.each_with_index do |item, i| _buf << ( i%2 == 0 ? '#FFCCCC' : '#CCCCFF' ).to_s; _buf << ( item ).to_s; end end _buf.to_s ruby-erubis-2.7.0/test/data/users-guide/percentline-example.rhtml000066400000000000000000000001161170760342400251270ustar00rootroot00000000000000
      % for item in list
    • <%= item %>
    • % end
    %% lines with '%%' ruby-erubis-2.7.0/test/data/users-guide/percentline_example.result000066400000000000000000000003211170760342400253770ustar00rootroot00000000000000$ erubis -xE PercentLine percentline-example.rhtml _buf = ''; _buf << '
      '; for item in list _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • '; end _buf << '
    % lines with \'%%\' '; _buf.to_s ruby-erubis-2.7.0/test/data/users-guide/prefixedline-example.rb000066400000000000000000000003541170760342400245560ustar00rootroot00000000000000require 'erubis' class PrefixedLineEruby < Erubis::Eruby include Erubis::PrefixedLineEnhancer end input = File.read('prefixedline-example.rhtml') eruby = PrefixedLineEruby.new(input, :prefixchar=>'!') # default '%' print eruby.src ruby-erubis-2.7.0/test/data/users-guide/prefixedline-example.rhtml000066400000000000000000000001241170760342400252740ustar00rootroot00000000000000
      ! for item in list
    • <%= item %>
    • ! end
    !! lines with '!!' ruby-erubis-2.7.0/test/data/users-guide/prefixedline_example.result000066400000000000000000000003031170760342400255450ustar00rootroot00000000000000$ ruby prefixedline-example.rb _buf = ''; _buf << '
      '; for item in list _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • '; end _buf << '
    ! lines with \'!!\' '; _buf.to_s ruby-erubis-2.7.0/test/data/users-guide/printenable_example.result000066400000000000000000000001061170760342400253730ustar00rootroot00000000000000$ ruby printenabled-example.rb aaa bbb ccc ruby-erubis-2.7.0/test/data/users-guide/printenabled-example.eruby000066400000000000000000000000741170760342400252710ustar00rootroot00000000000000<% for item in @list %> <% print item %> <% end %> ruby-erubis-2.7.0/test/data/users-guide/printenabled-example.rb000066400000000000000000000003701170760342400245450ustar00rootroot00000000000000require 'erubis' class PrintEnabledEruby < Erubis::Eruby include Erubis::PrintEnabledEnhancer end input = File.read('printenabled-example.eruby') eruby = PrintEnabledEruby.new(input) list = ['aaa', 'bbb', 'ccc'] print eruby.evaluate(:list=>list) ruby-erubis-2.7.0/test/data/users-guide/printstatement_example.result000066400000000000000000000003231170760342400261520ustar00rootroot00000000000000$ erubis -xE PrintOut example.eruby print '
    '; for item in list print '

    '; print(( item ).to_s); print '

    '; print Erubis::XmlHelper.escape_xml( item ); print '

    '; end print '
    '; ruby-erubis-2.7.0/test/data/users-guide/simplify_example.result000066400000000000000000000003661170760342400247340ustar00rootroot00000000000000$ erubis -xE Simplify example.eruby _buf = ''; _buf << '
    '; for item in list ; _buf << '

    '; _buf << ( item ).to_s; _buf << '

    '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '

    '; end ; _buf << '
    '; _buf.to_s ruby-erubis-2.7.0/test/data/users-guide/stderr.log000066400000000000000000000001101170760342400221160ustar00rootroot00000000000000*** debug: item="" *** debug: item="b&b" *** debug: item="\"ccc\"" ruby-erubis-2.7.0/test/data/users-guide/stdout_exmple.result000066400000000000000000000003601170760342400242530ustar00rootroot00000000000000$ erubis -xE Stdout example.eruby _buf = $stdout; _buf << '
    '; for item in list _buf << '

    '; _buf << ( item ).to_s; _buf << '

    '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '

    '; end _buf << '
    '; '' ruby-erubis-2.7.0/test/data/users-guide/stringbuffer_example.result000066400000000000000000000003701170760342400255730ustar00rootroot00000000000000$ erubis -xE StringBuffer example.eruby _buf = ''; _buf << '
    '; for item in list _buf << '

    '; _buf << ( item ).to_s; _buf << '

    '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '

    '; end _buf << '
    '; _buf.to_s ruby-erubis-2.7.0/test/data/users-guide/tail_260.result000066400000000000000000000001001170760342400226670ustar00rootroot00000000000000$ erubis -c '{var: "AAA\n"}' tailnewline.rhtml
    AAA
    ruby-erubis-2.7.0/test/data/users-guide/tailnewline.rhtml000066400000000000000000000000321170760342400234760ustar00rootroot00000000000000
    <%= @var -%>
    ruby-erubis-2.7.0/test/data/users-guide/template1.rhtml000066400000000000000000000001541170760342400230640ustar00rootroot00000000000000<% for x in items %> item = <%= x %> <% end %> ** debug: local variables=<%= local_variables().inspect() %> ruby-erubis-2.7.0/test/data/users-guide/template2.rhtml000066400000000000000000000001551170760342400230660ustar00rootroot00000000000000<% for x in @items %> item = <%= x %> <% end %> ** debug: local variables=<%= local_variables().inspect() %> ruby-erubis-2.7.0/test/test-engines.rb000066400000000000000000000245211170760342400177110ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## require "#{File.dirname(__FILE__)}/test.rb" require 'erubis' require 'erubis/engine/eruby' require 'erubis/engine/ephp' require 'erubis/engine/ec' require 'erubis/engine/ecpp' require 'erubis/engine/ejava' require 'erubis/engine/escheme' require 'erubis/engine/eperl' require 'erubis/engine/ejavascript' class EnginesTest < Test::Unit::TestCase #load_yaml_documents(__FILE__) testdata_list = load_yaml_datafile(__FILE__) define_testmethods(testdata_list) def _test() klass = Erubis.const_get(@class) engine = klass.new(@input, @options || {}) actual = engine.src assert_text_equal(@expected, actual) end self.post_definition() end __END__ - name: ruby1 lang: ruby class: Eruby options: input: | <% i = 0 list.each_with_index do |item, i| %> <% end %>
    <%= i+1 %> <%== list %>
    <%=== i+1 %> expected: | _buf = ''; _buf << ' '; i = 0 list.each_with_index do |item, i| _buf << ' '; end _buf << '
    '; _buf << ( i+1 ).to_s; _buf << ' '; _buf << Erubis::XmlHelper.escape_xml( list ); _buf << '
    '; $stderr.puts("*** debug: i+1=#{(i+1).inspect}"); _buf << ' '; _buf.to_s ## - name: ruby2_options lang: ruby class: Eruby options: { :bufvar: '@_out_buf' } input: | <% for item in @items %> <% end %>
    <%= i+1 %> <%== list %>
    expected: | @_out_buf = ''; @_out_buf << ' '; for item in @items @_out_buf << ' '; end @_out_buf << '
    '; @_out_buf << ( i+1 ).to_s; @_out_buf << ' '; @_out_buf << Erubis::XmlHelper.escape_xml( list ); @_out_buf << '
    '; @_out_buf.to_s ## - name: php1 lang: php class: Ephp options: input: | <% $i = 0; foreach ($list as $item) { $i++; %> <% } %>
    <%= $i %> <%== $item %>
    <%=== $i %> expected: |
    ## - name: c1 lang: c class: Ec options: { :filename: foo.html, :indent: ' ' } input: |4 <% for (i = 0; i < list; i++) { %> <% } %>
    <%= "%d", i %> <%== list[i] %>
    <%=== "%d", i %> expected: | #line 1 "foo.html" fputs("\n" " \n", stdout); for (i = 0; i < list; i++) { fputs(" \n" " \n" " \n" " \n", stdout); } fputs(" \n" "
    ", stdout); fprintf(stdout, "%d", i); fputs("", stdout); escape(list[i], stdout); fputs("
    \n", stdout); fprintf(stderr, "*** debug: i=" "%d", i); fputs("\n", stdout); ## - name: cpp1 lang: cpp class: Ecpp options: { :filename: foo.html, :indent: ' ' } input: |4 <% for (i = 0; i < n; i++) { %> <% } %>
    <%= i %> <%== list[i] %>
    <%=== i %> expected: | #line 1 "foo.html" _buf << "\n" " \n"; for (i = 0; i < n; i++) { _buf << " \n" " \n" " \n" " \n"; } _buf << " \n" "
    "; _buf << (i); _buf << ""; escape(list[i]); _buf << "
    \n"; std::cerr << "*** debug: i=" << (i); _buf << "\n"; ## - name: java1 lang: java class: Ejava options: { :buf: _buf, :bufclass: StringBuilder, :indent: ' ' } input: | <% int i = 0; for (Iterator it = list.iterator(); it.hasNext(); ) { String s = (String)it.next(); i++; %> "> <% } %>
    <%= i %> <%== s %>
    <%=== i %> expected: |4 StringBuilder _buf = new StringBuilder(); _buf.append("\n" + " \n"); int i = 0; for (Iterator it = list.iterator(); it.hasNext(); ) { String s = (String)it.next(); i++; _buf.append(" \n" + " \n" + " \n" + " \n"); } _buf.append(" \n" + "
    "); _buf.append(i); _buf.append(""); _buf.append(escape(s)); _buf.append("
    \n"); System.err.println("*** debug: i="+(i)); _buf.append("\n"); return _buf.toString(); ## - name: scheme1 lang: scheme class: Escheme options: input: &scheme1_input| <% (let ((i 0)) %> <% (for-each (lambda (item) (set! i (+ i 1)) %> <% ); lambda end list); for-each end %>
    <%= i %> <%== item %>
    <%=== i %> <% ); let end %> expected: |4 (let ((_buf '())) (define (_add x) (set! _buf (cons x _buf))) (let ((i 0)) (_add "\n") (for-each (lambda (item) (set! i (+ i 1)) (_add " \n") ); lambda end list); for-each end (_add "
    ")(_add i)(_add " ")(_add (escape item))(_add "
    \n") (display "*** debug: i=")(display i)(display "\n")(_add "\n") ); let end (reverse _buf)) ## - name: scheme2 lang: scheme class: Escheme options: { :func: 'display' } input: *scheme1_input expected: |4 (let ((i 0)) (display "\n") (for-each (lambda (item) (set! i (+ i 1)) (display " \n") ); lambda end list); for-each end (display "
    ")(display i)(display " ")(display (escape item))(display "
    \n") (display "*** debug: i=")(display i)(display "\n")(display "\n") ); let end ## - name: perl1 lang: perl class: Eperl options: input: | <% my $user = 'Erubis'; my @list = ('', 'b&b', '"ccc"'); %>

    Hello <%= $user %>!

    <% $i = 0; %> <% for $item (@list) { %> "> <% } %>
    <%= $i %> <%== $item %>
    <%=== $i %> expected: |4 use HTML::Entities; my $user = 'Erubis'; my @list = ('', 'b&b', '"ccc"'); print('

    Hello '); print($user); print('!

    '); $i = 0; for $item (@list) { print(' '); } print('
    '); print($i); print(' '); print(encode_entities($item)); print('
    '); print('*** debug: $i=', $i, "\n");print(' '); ## - name: javascript1 lang: javascript class: Ejavascript options: input: &javascript_input | <% var user = 'Erubis'; var list = ['', 'b&b', '"ccc"']; %>

    Hello <%= user %>!

    <% var i; %> <% for (i = 0; i < list.length; i++) { %> "> <% } %>
    <%= i %> <%= list[i] %>
    <%=== i %> expected: |4 var _buf = []; var user = 'Erubis'; var list = ['', 'b&b', '"ccc"']; _buf.push("

    Hello "); _buf.push(user); _buf.push("!

    \n\ \n\ \n"); var i; for (i = 0; i < list.length; i++) { _buf.push(" \n\ \n\ \n\ \n"); } _buf.push(" \n\
    "); _buf.push(i); _buf.push(""); _buf.push(list[i]); _buf.push("
    \n"); alert("*** debug: i="+(i)); _buf.push("\n"); document.write(_buf.join("")); ## - name: javascript2 lang: javascript class: Ejavascript options: { :docwrite: false } input: *javascript_input expected: |4 var _buf = []; var user = 'Erubis'; var list = ['', 'b&b', '"ccc"']; _buf.push("

    Hello "); _buf.push(user); _buf.push("!

    \n\ \n\ \n"); var i; for (i = 0; i < list.length; i++) { _buf.push(" \n\ \n\ \n\ \n"); } _buf.push(" \n\
    "); _buf.push(i); _buf.push(""); _buf.push(list[i]); _buf.push("
    \n"); alert("*** debug: i="+(i)); _buf.push("\n"); _buf.join(""); ## ruby-erubis-2.7.0/test/test-enhancers.rb000066400000000000000000000331171170760342400202300ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## require "#{File.dirname(__FILE__)}/test.rb" require 'stringio' require 'erubis' require 'erubis/engine/enhanced' require 'erubis/engine/optimized' class EnhancersTest < Test::Unit::TestCase testdata_list = load_yaml_datafile(__FILE__) define_testmethods(testdata_list) def _test() @src.gsub!(/\^/, ' ') @output.gsub!(/\^/, ' ') if @output.is_a?(String) if @class k = Erubis @class.split('::').each do |name| k = k.const_get(name) end @klass = k else @klass = Erubis::Eruby end @options ||= {} @chomp.each do |target| case target when 'src' ; @src.chomp! when 'input' ; @input.chomp! when 'expected' ; @expected.chomp! else raise "#{@name}: invalid chomp value: #{@chomp.inspect}" end end if @chomp if @testopt == 'load_file' filename = "tmp.#{@name}.eruby" begin File.open(filename, 'w') { |f| f.write(@input) } eruby = @klass.load_file(filename, @options) ensure cachename = filename + '.cache' File.unlink(cachename) if test(?f, cachename) File.unlink(filename) if test(?f, filename) end else #if @klass == Erubis::TinyEruby # eruby = @klass.new(@input) #else eruby = @klass.new(@input, @options) #end end assert_text_equal(@src, eruby.src) return if @testopt == 'skip_output' list = ['', 'b&b', '"ccc"'] context = @testopt == 'context' ? Erubis::Context.new : {} context[:list] = list case @testopt when /\Aeval\(/ eval eruby.src actual = eval @testopt assert_text_equal(@output, actual) when 'stdout', 'print' begin orig = $stdout $stdout = stringio = StringIO.new #actual = eruby.evaluate(context) actual = eruby.result(context) ensure $stdout = orig end if @testopt == 'stdout' assert_equal("", actual) else assert_nil(actual) end assert_text_equal(@output, stringio.string) when 'evaluate', 'context' actual = eruby.evaluate(context) assert_text_equal(@output, actual) when 'binding' actual = eruby.result(binding()) assert_text_equal(@output, actual) else actual = eruby.result(context) assert_text_equal(@output, actual) end end self.post_definition() end __END__ ## - name: basic1 class: Eruby input: &basic1_input|
      <% for item in list %>
    • <%= item %>
    • <% end %>
    src: &basic1_src| _buf = ''; _buf << '
      '; for item in list _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • '; end _buf << '
    '; _buf.to_s output: &basic1_output|
    • b&b
    • "ccc"
    - name: xml1 class: XmlEruby input: |
           <% for item in list %>
            <%= item %>
            <%== item %>
           <% end %>
          
    src: | _buf = ''; _buf << '
          ';  for item in list 
           _buf << '  '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '
          '; _buf << '  '; _buf << ( item ).to_s; _buf << '
          ';  end 
           _buf << '
    '; _buf.to_s output: |
            <aaa>
            
            b&b
            b&b
            "ccc"
            "ccc"
          
    ## - name: xml2 class: XmlEruby testopt: skip_output input: | <% for item in list %> <%= item["var#{n}"] %> <%== item["var#{n}"] %> <%=== item["var#{n}"] %> <%==== item["var#{n}"] %> <% end %> src: | _buf = ''; for item in list _buf << ' '; _buf << Erubis::XmlHelper.escape_xml( item["var#{n}"] ); _buf << ' '; _buf << ' '; _buf << ( item["var#{n}"] ).to_s; _buf << ' '; _buf << ' '; $stderr.puts("*** debug: item[\"var\#{n}\"]=#{(item["var#{n}"]).inspect}"); _buf << ' '; _buf << ' '; _buf << ' '; end _buf.to_s output: | ## - name: printout1 class: PrintOutEruby testopt: print input: *basic1_input src: |4 print '
      '; for item in list print '
    • '; print(( item ).to_s); print '
    • '; end print '
    '; output: *basic1_output ## - name: printenabled1 class: PrintEnabledEruby input: &printenabled1_input|
      <% for item in list %>
    • <% print item %>
    • <% end %>
    src: | @_buf = _buf = ''; _buf << '
      '; for item in list _buf << '
    • '; print item ; _buf << '
    • '; end _buf << '
    '; _buf.to_s output: *basic1_output #
      #
    • #
    • b&b
    • #
    • "ccc"
    • #
    ## - name: stdout1 class: StdoutEruby testopt: stdout input: *basic1_input #
      # <% for item in list %> #
    • <%= item %>
    • # <% end %> #
    src: | _buf = $stdout; _buf << '
      '; for item in list _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • '; end _buf << '
    '; '' output: *basic1_output #
      #
    • #
    • b&b
    • #
    • "ccc"
    • #
    ## - name: array1 class: ArrayEruby input: |
      <% for item in list %>
    • <%= item %>
    • <% end %>
    src: | _buf = []; _buf << '
      '; for item in list _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • '; end _buf << '
    '; _buf output: - "
      \n" - "
    • " - "" - "
    • \n" - "
    • " - "b&b" - "
    • \n" - "
    • " - "\"ccc\"" - "
    • \n" - "
    \n" ## - name: arraybuffer1 class: ArrayBufferEruby input: *basic1_input src: | _buf = []; _buf << '
      '; for item in list _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • '; end _buf << '
    '; _buf.join output: *basic1_output - name: stringbuffer1 class: StringBufferEruby input: *basic1_input #
      # <% for item in list %> #
    • <%= item %>
    • # <% end %> #
    src: | _buf = ''; _buf << '
      '; for item in list _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • '; end _buf << '
    '; _buf.to_s output: *basic1_output #
      #
    • #
    • b&b
    • #
    • "ccc"
    • #
    ## - name: erbout1 class: ErboutEruby input: *basic1_input src: | _erbout = _buf = ''; _buf << '
      '; for item in list _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • '; end _buf << '
    '; _buf.to_s output: *basic1_output ## - name: stringio1 class: StringIOEruby input: *basic1_input src: | _buf = StringIO.new; _buf << '
      '; for item in list _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • '; end _buf << '
    '; _buf.string output: *basic1_output ## - name: notext1 class: NoTextEruby input: *basic1_input src: | _buf = ''; for item in list _buf << ( item ).to_s; end _buf.to_s output: 'b&b"ccc"' ## - name: nocode1 class: NoCodeEruby testopt: skip_output input: *basic1_input src: |
    output: ## - name: simplified class: SimplifiedEruby input: |
      <% for item in list %>
    • <%= item %>
    • <% end %>
    src: | _buf = ''; _buf << '
      '; for item in list ; _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • '; end ; _buf << '
    '; _buf.to_s output: |
      ^
    • ^
    • b&b
    • ^
    • "ccc"
    • ^
    ## - name: bipattern1 class: BiPatternEruby #options: { :bipattern : '\[= =\]' } input: | <% for item in list %> <%= item %> % <%== item %> [= item =] = [== item =] <% end %> src: | _buf = ''; for item in list _buf << ' '; _buf << ( item ).to_s; _buf << ' % '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << ' '; _buf << ' '; _buf << ( item ).to_s; _buf << ' = '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << ' '; end _buf.to_s output: |4 % <aaa> = <aaa> b&b % b&b b&b = b&b "ccc" % "ccc" "ccc" = "ccc" ## - name: bipattern2 class: BiPatternEruby options: { :bipattern: '\$\{ \}' } input: | <% for item in list %> <%=item%> % <%==item%> ${item} = ${=item} <% end %> src: | _buf = ''; for item in list _buf << ' '; _buf << (item).to_s; _buf << ' % '; _buf << Erubis::XmlHelper.escape_xml(item); _buf << ' '; _buf << ' '; _buf << (item).to_s; _buf << ' = '; _buf << Erubis::XmlHelper.escape_xml(item); _buf << ' '; end _buf.to_s output: |4 % <aaa> = <aaa> b&b % b&b b&b = b&b "ccc" % "ccc" "ccc" = "ccc" ## - name: percentline1 class: PercentLineEruby options: input: | % for item in list % end
    <%= item %> <%== item %>
          %% double percent
           % spaced percent
          
    src: | _buf = ''; _buf << ' '; for item in list _buf << ' '; end _buf << '
    '; _buf << ( item ).to_s; _buf << ' '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '
          % double percent
           % spaced percent
          
    '; _buf.to_s output: |
    <aaa>
    b&b b&b
    "ccc" "ccc"
          % double percent
           % spaced percent
          
    ## - name: prefixedline1 class: PrefixedLineEruby options: { :prefixchar: '!' } input: | ! for item in list ! end
    <%= item %> <%== item %>
            !! doubled characters
          
    src: | _buf = ''; _buf << ' '; for item in list _buf << ' '; end _buf << '
    '; _buf << ( item ).to_s; _buf << ' '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '
            ! doubled characters
          
    '; _buf.to_s output: |
    <aaa>
    b&b b&b
    "ccc" "ccc"
            ! doubled characters
          
    ## - name: headerfooter1 class: HeaderFooterEruby options: testopt: eval('ordered_list(list)') input: |
      <% for item in list %>
    1. <%==item%>
    2. <% end %>
    src: |4 def ordered_list(list) _buf = ''; _buf << '
      '; for item in list _buf << '
    1. '; _buf << Erubis::XmlHelper.escape_xml(item); _buf << '
    2. '; end _buf << '
    '; _buf.to_s end output: |
    1. <aaa>
    2. b&b
    3. "ccc"
    ## - name: deleteindent1 class: DeleteIndentEruby options: testopt: input: *basic1_input src: | _buf = ''; _buf << '
      '; for item in list _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • '; end _buf << '
    '; _buf.to_s output: |
    • b&b
    • "ccc"
    ## - name: interpolation1 class: InterpolationEruby options: testopt: input: *basic1_input src: | _buf = ''; _buf << %Q`
      \n` for item in list _buf << %Q`
    • #{ item }
    • \n` end _buf << %Q`
    \n` _buf.to_s output: *basic1_output - name: interpolation2 desc: sharp, back-quote, and backslash should be escaped, but other quotes should not be escaped (reported by andrewj) class: InterpolationEruby options: testopt: input: |

    `back-quote`

    <%= `echo back-tick operator` %>

    #{sharp}

    'single quote'

    "double quote"

    backslash\n\t

    src: | _buf = ''; _buf << %Q`

    \`back-quote\`

    #{ `echo back-tick operator` }

    \#{sharp}

    'single quote'

    "double quote"

    backslash\\n\\t

    \n` _buf.to_s output: |

    `back-quote`

    back-tick operator

    #{sharp}

    'single quote'

    "double quote"

    backslash\n\t

    ruby-erubis-2.7.0/test/test-erubis.rb000066400000000000000000000473641170760342400175640ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## require "#{File.dirname(__FILE__)}/test.rb" require 'stringio' require 'erubis' require 'erubis/engine/enhanced' require 'erubis/engine/optimized' require 'erubis/tiny' class ErubisTest < Test::Unit::TestCase testdata_list = load_yaml_datafile(__FILE__) define_testmethods(testdata_list) def _test() @src.gsub!(/\^/, ' ') @output.gsub!(/\^/, ' ') if @output.is_a?(String) if @class k = Erubis @class.split('::').each do |name| k = k.const_get(name) end @klass = k else @klass = Erubis::Eruby end @options ||= {} @chomp.each do |target| case target when 'src' ; @src.chomp! when 'input' ; @input.chomp! when 'expected' ; @expected.chomp! else raise "#{@name}: invalid chomp value: #{@chomp.inspect}" end end if @chomp if @testopt == 'load_file' filename = "tmp.#{@name}.eruby" begin File.open(filename, 'w') { |f| f.write(@input) } eruby = @klass.load_file(filename, @options) ensure cachename = filename + '.cache' File.unlink(cachename) if test(?f, cachename) File.unlink(filename) if test(?f, filename) end else if @klass == Erubis::TinyEruby eruby = @klass.new(@input) else eruby = @klass.new(@input, @options) end end assert_text_equal(@src, eruby.src) return if @testopt == 'skip_output' list = ['', 'b&b', '"ccc"'] context = @testopt == 'context' ? Erubis::Context.new : {} context[:list] = list case @testopt when /\Aeval\(/ eval eruby.src actual = eval @testopt assert_text_equal(@output, actual) when 'stdout', 'print' begin orig = $stdout $stdout = stringio = StringIO.new #actual = eruby.evaluate(context) actual = eruby.result(context) ensure $stdout = orig end if @testopt == 'stdout' assert_equal("", actual) else assert_nil(actual) end assert_text_equal(@output, stringio.string) when 'evaluate', 'context' actual = eruby.evaluate(context) assert_text_equal(@output, actual) when 'binding' actual = eruby.result(binding()) assert_text_equal(@output, actual) else actual = eruby.result(context) assert_text_equal(@output, actual) end end def test_load_file_cache1 @input = < <% for item in @list %>
  • <%= item %>
  • <% end %> END @src = < '; for item in @list _buf << '
  • '; _buf << ( item ).to_s; _buf << '
  • '; end _buf << ' '; _buf.to_s END @klass = Erubis::Eruby filename = 'tmp.load_file_timestamp1' cachename = filename + '.cache' begin ## when cache doesn't exist then it is created automatically File.open(filename, 'w') { |f| f.write(@input) } mtime = Time.now - 2.0 File.utime(mtime, mtime, filename) !test(?f, cachename) or raise "** failed" engine = @klass.load_file(filename) assert_block() { test(?f, cachename) } assert_block() { File.mtime(filename) <= File.mtime(cachename) } assert_text_equal(@src, engine.src) ## when cache has different timestamp then it is recreated input2 = @input.gsub(/ul>/, 'ol>') src2 = @src.gsub(/ul>/, 'ol>') File.open(filename, 'w') { |f| f.write(input2) } t1 = Time.now() sleep(1) t2 = Time.now() # File.utime(t1, t1, filename) File.utime(t2, t2, cachename) File.mtime(filename) < File.mtime(cachename) or raise "** failed" engine = @klass.load_file(filename) assert_block('cache should have same timestamp') { File.mtime(filename) == File.mtime(cachename) } #assert_text_equal(@src, engine.src) assert_text_equal(src2, engine.src) # File.utime(t2, t2, filename) File.utime(t1, t1, cachename) File.mtime(filename) > File.mtime(cachename) or raise "** failed" engine = @klass.load_file(filename) assert_block('cache should have same timestamp') { File.mtime(filename) == File.mtime(cachename) } assert_text_equal(src2, engine.src) ensure File.unlink(cachename) if File.file?(cachename) File.unlink(filename) if File.file?(filename) end end class Dummy end def _class_has_instance_method(klass, method) return klass.instance_methods.collect{|m| m.to_s}.include?(method.to_s) end def test_def_method1 s = "<%for i in list%>i=<%=i%>\n<%end%>" eruby = Erubis::Eruby.new(s) assert(! _class_has_instance_method(Dummy, 'render')) eruby.def_method(Dummy, 'render(list)', 'foo.rhtml') assert(_class_has_instance_method(Dummy, 'render')) actual = Dummy.new().render(%w[1 2 3]) assert_equal("i=1\ni=2\ni=3\n", actual) end def test_def_method2 s = "<%for i in list%>i=<%=i%>\n<%end%>" eruby = Erubis::Eruby.new(s) assert(! (eruby.respond_to? :render)) eruby.def_method(eruby, 'render(list)', 'foo.rhtml') assert eruby.respond_to?(:render) actual = eruby.render([1, 2, 3]) assert_equal("i=1\ni=2\ni=3\n", actual) assert(! _class_has_instance_method(eruby.class, 'render')) end def test_evaluate_creates_proc s = "hello <%= @name %>" eruby = Erubis::Eruby.new(s) assert_nil(eruby.instance_variable_get('@_proc')) actual1 = eruby.evaluate(:name=>'world') assert_not_nil(eruby.instance_variable_get('@_proc')) assert_instance_of(Proc, eruby.instance_variable_get('@_proc')) actual2 = eruby.evaluate(:name=>'world') assert_equal(actual1, actual2) # convert() must clear @_proc eruby.convert(s) assert_nil(eruby.instance_variable_get('@_proc')) end #def test_toplevel_binding # s = "locals = <%= local_variables().inspect %>\n<% x = 50 %>\n" # eruby = Erubis::Eruby.new(s) # _x = eval 'x', TOPLEVEL_BINDING # _y = eval 'y', TOPLEVEL_BINDING # actual = eruby.evaluate(:x=>_x, :y=>_y) # _x = eval 'x', TOPLEVEL_BINDING # _y = eval 'y', TOPLEVEL_BINDING # puts "*** actual=#{actual.inspect}, x=#{_x.inspect}, y=#{_y.inspect}" #end self.post_definition() end x = 10 y = 20 __END__ - name: basic1 input: &basic1_input|
      <% for item in list %>
    • <%= item %>
    • <% end %>
    src: &basic1_src| _buf = ''; _buf << '
      '; for item in list _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • '; end _buf << '
    '; _buf.to_s output: &basic1_output|
    • b&b
    • "ccc"
    ## - name: basic2 input: |
      <% i = 0 for item in list i += 1 %>
    • <%= item %>
    • <% end %>
    src: | _buf = ''; _buf << '
      '; i = 0 for item in list i += 1 ^^^ _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • '; end _buf << '
    '; _buf.to_s output: *basic1_output #
      #
    • #
    • b&b
    • #
    • "ccc"
    • #
    ## - name: basic3 input: |
      <% i = 0 for item in list i += 1 %>
    • <%= item %>
    • <% end %>
    src: | _buf = ''; _buf << '
      '; i = 0 for item in list i += 1 ; _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • '; end ; _buf << ' '; _buf << '
    '; _buf.to_s output: |
    • b&b
    • "ccc"
    ## - name: context1 testopt: context input: |
      <% for item in @list %>
    • <%= item %>
    • <% end %>
    src: | _buf = ''; _buf << '
      '; for item in @list _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • '; end _buf << '
    '; _buf.to_s output: *basic1_output ## - name: ignore1 input: |
      <%# i = 0 %> <% for item in list %> <%# i += 1 color = i % 2 == 0 ? '#FFCCCC' : '#CCCCFF' %>
    • <%#= i %> : <%= item %>
    • <% end %>
    src: | _buf = ''; _buf << '
      '; for item in list _buf << '
    • ';; _buf << ' : '; _buf << ( item ).to_s; _buf << '
    • '; end _buf << '
    '; _buf.to_s output: |
    • :
    • : b&b
    • : "ccc"
    ## - name: quotation1 desc: single quotation and backslash class: Eruby input: "ation1_input| a = "'" b = "\"" c = '\'' src: | _buf = ''; _buf << 'a = "\'" b = "\\"" c = \'\\\'\' '; _buf.to_s output: *quotation1_input ## - name: minus1 desc: '<%- -%>' class: Eruby input: |
      <%- for item in list -%>
    • <%= item -%>
    • <% end -%>
    src: *basic1_src output: *basic1_output ## - name: pattern1 options: :pattern : '\[@ @\]' input: |
      [@ for item in list @]
    • [@= item @]
    • [@ end @]
    src: | _buf = ''; _buf << '
      '; for item in list _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • '; end _buf << '
    '; _buf.to_s output: *basic1_output #
      #
    • #
    • b&b
    • #
    • "ccc"
    • #
    ## - name: pattern2 options: :pattern : '<(?:!--)?% %(?:--)?>' input: |
    • <%= item %>
    src: | _buf = ''; _buf << '
      '; for item in list _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • '; end _buf << '
    '; _buf.to_s output: *basic1_output #
      #
    • #
    • b&b
    • #
    • "ccc"
    • #
    ## - name: trim1 options: :trim : false input: *basic1_input #
      # <% for item in list %> #
    • <%= item %>
    • # <% end %> #
    src: | _buf = ''; _buf << '
      '; _buf << ' '; for item in list ; _buf << ' '; _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • '; _buf << ' '; end ; _buf << ' '; _buf << '
    '; _buf.to_s output: |
      ^
    • ^
    • b&b
    • ^
    • "ccc"
    • ^
    ## - name: bodyonly1 testopt: skip_output options: { :preamble: no, :postamble: no } input: *basic1_input src: |4 _buf << '
      '; for item in list _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • '; end _buf << '
    '; chomp: [src] expected: null ## - name: loadfile1 testopt: load_file #input: | #
      # <% for item in list %> #
    • <%= item %>
    • # <% end %> #
    input: "
      \r\n <% for item in list %>\r\n
    • <%= item %>
    • \r\n <% end %>\r\n
    \r\n" #src: | # _buf = ''; _buf << "
      \n" # for item in list # _buf << "
    • "; _buf << ( item ).to_s; _buf << "
    • \n" # end # _buf << "
    \n" # _buf src: "_buf = ''; _buf << '
      \r\n'; for item in list \r\n _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • \r\n'; end \r\n _buf << '
    \r\n';\n_buf.to_s\n" #output: | #
      #
    • #
    • b&b
    • #
    • "ccc"
    • #
    output: "
      \n
    • \n
    • b&b
    • \n
    • \"ccc\"
    • \n
    \n" # "
      \r\n
    • \r\n
    • b&b
    • \r\n
    • \"ccc\"
    • \r\n
    \r\n" ## - name: nomatch1 desc: bug input: &nomatch1|
    • foo
    src: | _buf = ''; _buf << '
    • foo
    '; _buf.to_s output: *nomatch1 ## - name: escape1 options: { :escape: true } input: | <% str = '<>&"' %> <%= str %> <%== str %> src: | _buf = ''; str = '<>&"' _buf << Erubis::XmlHelper.escape_xml( str ); _buf << ' '; _buf << ( str ).to_s; _buf << ' '; _buf.to_s output: | <>&" <>&" ## - name: tailch1 options: input: |

    <% str = '<>&"' %> <%= str %> <%= str =%> <%= str -%>

    src: | _buf = ''; _buf << '

    '; str = '<>&"' _buf << ' '; _buf << ( str ).to_s; _buf << ' '; _buf << ' '; _buf << ( str ).to_s; _buf << ' '; _buf << ( str ).to_s; _buf << '

    '; _buf.to_s output: |

    <>&" <>&" <>&"

    ## - name: doublepercent1 options: input: | <% x1 = 10 %> <%% x2 = 20 %> <%= x1 %> <%%= x2 %> src: | _buf = ''; x1 = 10 _buf << '<% x2 = 20 %> '; _buf << ( x1 ).to_s; _buf << ' '; _buf << '<%= x2 %> '; _buf.to_s output: | <% x2 = 20 %> 10 <%= x2 %> ## - name: optimized1 class: OptimizedEruby input: &optimized1_input| <% for item in list %> <% end %>
    <%= item %> <%== item %>
      <% for item in list %>
    • <%= item %>
    • <% end %>
    src: | _buf = ' '; for item in list _buf << ' '; end _buf << '
    ' << ( item ).to_s << ' ' << Erubis::XmlHelper.escape_xml( item ) << '
      '; for item in list ; _buf << '
    • ' << ( item ).to_s << '
    • '; end ; _buf << '
    ' _buf output: |
    <aaa>
    b&b b&b
    "ccc" "ccc"
    • b&b
    • "ccc"
    ## - name: optimized2 class: OptimizedXmlEruby input: *optimized1_input # # <% for item in list %> # # # # # <% end %> #
    <%= item %><%== item %>
    #
      <% for item in list %>
    • <%= item %>
    • <% end %>
    src: | _buf = ' '; for item in list _buf << ' '; end _buf << '
    ' << Erubis::XmlHelper.escape_xml( item ) << ' ' << ( item ).to_s << '
      '; for item in list ; _buf << '
    • ' << Erubis::XmlHelper.escape_xml( item ) << '
    • '; end ; _buf << '
    ' _buf output: |
    <aaa>
    b&b b&b
    "ccc" "ccc"
    • <aaa>
    • b&b
    • "ccc"
    ## - name: optimized3 desc: bug class: OptimizedEruby input: | user = <%= "Foo" %> <% for item in list %> <%= item %> <% end %> src: | _buf = 'user = '; _buf << ( "Foo" ).to_s << ' '; for item in list _buf << ' ' << ( item ).to_s << ' '; end _buf output: | user = Foo b&b "ccc" ## - name: optimized4 desc: single quotation and backslash class: OptimizedEruby input: &optimized4_input| a = "'" b = "\"" c = '\'' src: | _buf = 'a = "\'" b = "\\"" c = \'\\\'\' '; _buf output: *optimized4_input ## - name: tiny1 class: TinyEruby testopt: binding input: |
      <% for item in list %>
    • <%= item %>
    • <% end %>
    src: | _buf = ''; _buf << '
      '; for item in list ; _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • '; end ; _buf << '
    '; _buf.to_s output: |
      ^
    • ^
    • b&b
    • ^
    • "ccc"
    • ^
    ## - name: tiny2 class: TinyEruby testopt: evaluate input: |
      <% for item in @list %>
    • <%= item %>
    • <% end %>
    src: | _buf = ''; _buf << '
      '; for item in @list ; _buf << '
    • '; _buf << ( item ).to_s; _buf << '
    • '; end ; _buf << '
    '; _buf.to_s output: |
      ^
    • ^
    • b&b
    • ^
    • "ccc"
    • ^
    ## - name: pi1 class: PI::Eruby testopt: evaluate input: &input_pi1|
    • @{item}@ / @!{item}@
    • <%= item %> / <%== item %>
    src: &src_pi1| _buf = ''; _buf << '
      '; for item in @list _buf << '
    • '; _buf << Erubis::XmlHelper.escape_xml(item); _buf << ' / '; _buf << (item).to_s; _buf << '
    • '; _buf << ( item ).to_s; _buf << ' / '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '
    • '; end _buf << '
    '; _buf.to_s output: &output_pi1|
    • <aaa> /
    • / <aaa>
    • b&b / b&b
    • b&b / b&b
    • "ccc" / "ccc"
    • "ccc" / "ccc"
    ## - name: pi2 class: PI::Eruby options: { :escape: false } testopt: evaluate input: *input_pi1 src: | _buf = ''; _buf << '
      '; for item in @list _buf << '
    • '; _buf << (item).to_s; _buf << ' / '; _buf << Erubis::XmlHelper.escape_xml(item); _buf << '
    • '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << ' / '; _buf << ( item ).to_s; _buf << '
    • '; end _buf << '
    '; _buf.to_s output: |
    • / <aaa>
    • <aaa> /
    • b&b / b&b
    • b&b / b&b
    • "ccc" / "ccc"
    • "ccc" / "ccc"
    ## - name: pi3 class: PI::Eruby options: { :pi: hoge, :embchar: '$' } testopt: evaluate input: |
    • ${item}$ / $!{item}$
    • <%= item %> / <%== item %>
    src: *src_pi1 output: *output_pi1 - name: pi4 class: PI::Eruby testopt: evaluate input: |
    src: |4 def show(list) _buf = ''; _buf << '
      '; for item in list _buf << ( item ).to_s; end _buf << '
    '; _buf.to_s end show(@list) output: |
      b&b"ccc"
    - name: pitiny1 class: PI::TinyEruby testopt: evaluate input: |
    • @{item}@ / @!{item}@
    src: | _buf = ''; _buf << '
      '; for item in @list _buf << '
    • '; _buf << Erubis::XmlHelper.escape_xml(item); _buf << ' / '; _buf << (item).to_s; _buf << '
    • '; end _buf << '
    '; _buf.to_s output: |
    • <aaa> /
    • b&b / b&b
    • "ccc" / "ccc"
    ruby-erubis-2.7.0/test/test-index-cgi.rb000066400000000000000000000103551170760342400201300ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## require "#{File.dirname(__FILE__)}/test.rb" require 'stringio' load "#{File.dirname(__FILE__)}/../public_html/index.cgi" def spec(desc) yield end def dummy_env(request_method='GET', request_uri='/', opts={}) if request_method.is_a?(Hash) opts = request_method request_method = 'GET' request_uri = '/' elsif request_uri.is_a?(Hash) opts = request_uri request_uri = '/' end env = { 'REQUEST_METHOD' => request_method.to_s, 'REQUEST_URI' => request_uri.to_s, 'DOCUMENT_ROOT' => Dir.pwd, } opts.each {|k, v| env[k.to_s.upcase] = v } env.update(opts) return env end def dummy_template(filename, content) begin File.open(filename, 'wb') {|f| f.write(content) } return yield ensure [filename, filename + '.cache'].each do |fname| File.unlink(fname) if File.exist?(fname) end end end class ErubisHandlerTest < Test::Unit::TestCase def test_initialize spec "sets @encoding and @layout" do encoding_bkup = $ENCODING layout_bkup = $LAYOUT begin $ENCODING = 'cp932' $LAYOUT = 'site.rhtml' obj = ErubisHandler.new assert_equal 'cp932', obj.encoding assert_equal 'site.rhtml', obj.layout ensure $ENCODING = encoding_bkup $LAYOUT = layout_bkup end end end def test_handle spec "renders requested template file." do base = "_test_handle" env = dummy_env('GET', "/#{base}.html") handler = ErubisHandler.new input = <<'END'

    <%= 'SOS' %>

      <% for item in %w[Haruhi Mikuru Yuki] %>
    • <%= item %>
    • <% end %>
    END expected = <<'END'

    SOS

    • Haruhi
    • Mikuru
    • Yuki
    END out = dummy_template("#{base}.rhtml", input) do handler.handle(env) end assert_equal expected, out end spec "raises 404 error when requested file not found." do req_url = "/_test_handle.html" env = dummy_env('GET', req_url) handler = ErubisHandler.new ex = assert_raise HttpError do handler.handle(env) end assert_equal 404, ex.status assert_equal "#{req_url}: not found.", ex.message end end end class ErubisApplicationTest < Test::Unit::TestCase def test_handle_request spec "handles request by handler object and returns response data." do app = ErubisApplication.new() def app.get_handler return Class.new { def handle(env); "

    Hello SOS

    "; end def encoding; "euc_jp"; end }.new end expected = [ 200, [["Content-Type", "text/html;charset=euc_jp"]], ["

    Hello SOS

    "], ] env = dummy_env('GET', '/') ret = app.call(env) assert_equal expected, ret end end def test_handle_http_error spec "renders error page." do req_path = '/HaruhiSuzumiya.html' app = ErubisApplication.new() env = dummy_env('GET', req_path) expected = [ 404, [["Content-Type", "text/html"]], ["

    404 Not Found

    \n

    #{req_path}: not found.

    \n"], ] ret = app.call(env) assert_equal expected, ret end end def test_run spec "prints to $stdout" do input = "

    Hello SOS

    " app = ErubisApplication.new base = "SOS" env = dummy_env("GET", "/#{base}.html") sio = StringIO.new output = dummy_template("#{base}.rhtml", input) do app.run(env, sio) sio.string end expected = "" expected << "Content-Type: text/html\r\n" expected << "\r\n" expected << "

    Hello SOS

    " assert_equal expected, output end spec "prints 'Status:' header if status code is not 200." do req_path = "/SOS.html" env = dummy_env("GET", req_path) app = ErubisApplication.new sio = StringIO.new app.run(env, sio) expected = "Status: 404 Not Found\r\n" expected << "Content-Type: text/html\r\n" expected << "\r\n" expected << "

    404 Not Found

    \n" expected << "

    #{req_path}: not found.

    \n" assert_equal expected, sio.string end end end ruby-erubis-2.7.0/test/test-main.rb000066400000000000000000000373021170760342400172060ustar00rootroot00000000000000## ## $Rev$ ## $Release: 2.7.0 $ ## $Date$ ## require "#{File.dirname(__FILE__)}/test.rb" require 'tempfile' require 'fileutils' require 'erubis/main' $script = File.dirname(TESTDIR) + '/bin/erubis' #if test(?f, 'bin/erubis') # $script = 'bin/erubis' #elsif test(?f, '../bin/erubis') # $script = '../bin/erubis' #end class StringWriter < String def write(arg) self << arg end def flush(*args) # pass end def puts(arg) case arg when Array arg.each do |item| self << item << "\n" end else self << arg.to_s self << "\n" unless arg =~ /\n$/ end end end class Erubis::Main public :usage public :show_properties public :show_enhancers end class MainTest < Test::Unit::TestCase INPUT = <<'END' list: <% list = ['', 'b&b', '"ccc"'] for item in list %> - <%= item %> <% end %> user: <%= defined?(user) ? user : "(none)" %> END INPUT2 = INPUT.gsub(/\blist([^:])/, '@list\1').gsub(/\buser([^:])/, '@user\1') # SRC = <<'END' #_buf = ''; _buf << "list:\n" # list = ['', 'b&b', '"ccc"'] # for item in list #_buf << " - "; _buf << ( item ).to_s; _buf << "\n" # end #_buf << "user: "; _buf << ( defined?(user) ? user : "(none)" ).to_s; _buf << "\n" #_buf #END SRC = <<'END' _buf = ''; _buf << 'list: '; list = ['', 'b&b', '"ccc"'] for item in list _buf << ' - '; _buf << ( item ).to_s; _buf << ' '; end _buf << 'user: '; _buf << ( defined?(user) ? user : "(none)" ).to_s; _buf << ' '; _buf.to_s END # SRC2 = SRC.gsub(/\blist /, '@list ').gsub(/\buser /, '@user ') OUTPUT = <<'END' list: - - b&b - "ccc" user: (none) END ESCAPED_OUTPUT = <<'END' list: - <aaa> - b&b - "ccc" user: (none) END PI_INPUT = <<'END'
      ', 'b&b', '"ccc"'] for item in @list ?>
    • @{item}@ / @!{item}@ <%= item %> / <%== item %>
      • END PI_SRC = <<'END' _buf = ''; _buf << '
          '; @list = ['', 'b&b', '"ccc"'] for item in @list _buf << '
        • '; _buf << Erubis::XmlHelper.escape_xml(item); _buf << ' / '; _buf << (item).to_s; _buf << ' '; _buf << ( item ).to_s; _buf << ' / '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '
        • '; end _buf << '
            '; _buf.to_s END PI_ESCAPED_SRC = <<'END' _buf = ''; _buf << '
              '; @list = ['', 'b&b', '"ccc"'] for item in @list _buf << '
            • '; _buf << (item).to_s; _buf << ' / '; _buf << Erubis::XmlHelper.escape_xml(item); _buf << ' '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << ' / '; _buf << ( item ).to_s; _buf << '
            • '; end _buf << '
                '; _buf.to_s END PI_OUTPUT = <<'END'
                • <aaa> / / <aaa>
                • b&b / b&b b&b / b&b
                • "ccc" / "ccc" "ccc" / "ccc"
                  • END PI_ESCAPED_OUTPUT = <<'END'
                    • / <aaa> <aaa> /
                    • b&b / b&b b&b / b&b
                    • "ccc" / "ccc" "ccc" / "ccc"
                      • END def _test() if @filename.nil? method = (caller[0] =~ /in `(.*)'/) && $1 #' method =~ /block in (.*)/ and method = $1 # for Ruby 1.9 @filename = "tmp.#{method}" end File.open(@filename, 'w') {|f| f.write(@input) } if @filename begin argv = @options.is_a?(Array) ? @options.dup : @options.split argv << @filename if @filename $stdout = output = StringWriter.new Erubis::Main.new.execute(argv) ensure $stdout = STDOUT File.unlink(@filename) if @filename && test(?f, @filename) end assert_text_equal(@expected, output) end def _error_test(errclass, errmsg) ex = assert_raise(errclass) { _test() } assert_equal(errmsg, ex.message) end def test_help # -h @options = '-h' m = Erubis::Main.new @expected = m.usage() + "\n" + m.show_properties() + m.show_enhancers() @filename = false _test() end def test_version # -v @options = '-v' @expected = (("$Release: 2.7.0 $" =~ /[.\d]+/) && $&) + "\n" @filename = false _test() end def test_basic1 @input = INPUT @expected = OUTPUT @options = '' _test() end def test_source1 # -x @input = INPUT @expected = SRC @options = '-x' _test() end def _with_dummy_file bindir = File.join(File.dirname(File.dirname(__FILE__)), 'bin') env_path = ENV['PATH'] env__ = ENV['_'] begin ENV['PATH'] = bindir + File::PATH_SEPARATOR + ENV['PATH'] ENV['_'] = 'erubis' Tempfile.open(self.name.gsub(/[^\w]/,'_')) do |f| f.write(INPUT) f.flush yield(f.path) end ensure ENV['PATH'] = env_path ENV['_'] = env__ if env__ end end def test_syntax1 # -z (syntax ok) @input = INPUT @expected = "Syntax OK\n" @options = '-z' _test() # _with_dummy_file do |filepath| actual = `erubis #{@options} #{filepath}` assert_equal @expected, actual end end def test_syntax2 # -z (syntax error) inputs = [] inputs << <<'END'
                          <% for item in list %>
                        • <%= item[:name]] %>
                        • <% end %>
                        END inputs << <<'END'
                          <% for item in list %>
                        • <%= item[:name] %>
                        • <% edn %>
                        END basename = 'tmp.test_syntax2_%d.rhtml' filenames = [ basename % 0, basename % 1 ] errmsgs = [] if ruby19? errmsgs << <<'END' 3: syntax error, unexpected ']', expecting ')' _buf << '
                      • '; _buf << ( item[:name]] ).to_s; _buf << '
                      • ^ -:4: syntax error, unexpected keyword_end, expecting ')' '; end ^ -:7: syntax error, unexpected $end, expecting ')' END errmsgs << <<'END' 7: syntax error, unexpected $end, expecting keyword_end END elsif rubinius? errmsgs << <<'END' 3: expecting ')' _buf << '
                      • '; _buf << ( item[:name]] ).to_s; _buf << '
                      • ^ END errmsgs << <<'END' 7: missing 'end' for 'for' started on line 2 _buf.to_s ^ END else errmsgs << <<'END' 3: syntax error, unexpected ']', expecting ')' _buf << '
                      • '; _buf << ( item[:name]] ).to_s; _buf << '
                      • ^ -:4: syntax error, unexpected kEND, expecting ')' '; end ^ -:7: syntax error, unexpected $end, expecting ')' END errmsgs << <<'END' 7: syntax error, unexpected $end, expecting kEND END end # max = inputs.length (0...max).each do |i| @input = inputs[i] @expected = "tmp.test_syntax2:#{errmsgs[i]}" @options = '-z' if rubinius? @expected.sub! /unexpected kEND/, 'unexpected keyword_end' @expected.sub! /expecting kEND/, 'expecting keyword_end' end _test() end # begin (0...max).each do |i| File.open(filenames[i], 'w') {|f| f.write(inputs[i]) } end @input = '' @expected = '' @options = '-z' (0...max).each do |i| @expected << "#{filenames[i]}:#{errmsgs[i]}" @options << " #{filenames[i]}" end if rubinius? @expected.sub! /unexpected kEND/, 'unexpected keyword_end' @expected.sub! /expecting kEND/, 'expecting keyword_end' end _test() ensure (0...max).each do |i| File.unlink(filenames[i]) if test(?f, filenames[i]) end end end def test_pattern1 # -p @input = INPUT.gsub(/<%/, '') @expected = OUTPUT #@options = "-p ''" @options = ["-p", ""] _test() end # def test_class1 # -C # @input = INPUT # @expected = OUTPUT.gsub(//, '<aaa>').gsub(/b&b/, 'b&b').gsub(/"ccc"/, '"ccc"') # @options = "-C XmlEruby" # _test() # end def test_notrim1 # --trim=false @input = INPUT @expected = <<'END' list: - - b&b - "ccc" user: (none) END @options = "--trim=false" # -T _test() end def test_notrim2 # --trim=false @input = INPUT # @expected = <<'END' #_buf = ''; _buf << "list:\n" # list = ['', 'b&b', '"ccc"'] # for item in list ; _buf << "\n" #_buf << " - "; _buf << ( item ).to_s; _buf << "\n" # end ; _buf << "\n" #_buf << "user: "; _buf << ( defined?(user) ? user : "(none)" ).to_s; _buf << "\n" #_buf #END @expected = <<'END' _buf = ''; _buf << 'list: '; list = ['', 'b&b', '"ccc"'] for item in list ; _buf << ' '; _buf << ' - '; _buf << ( item ).to_s; _buf << ' '; end ; _buf << ' '; _buf << 'user: '; _buf << ( defined?(user) ? user : "(none)" ).to_s; _buf << ' '; _buf.to_s END @options = "-x --trim=false" # -xT _test() end #-- #def test_context1 # @input = INPUT # @expected = OUTPUT.gsub(/\(none\)/, 'Hello') # @options = '--user=Hello' # _test() #end #++ def test_datafile1 # -f data.yaml datafile = "test.context1.yaml" @input = INPUT2 @expected = OUTPUT.gsub(/\(none\)/, 'Hello') @options = "-f #{datafile}" # str = <<-END user: Hello password: world END File.open(datafile, 'w') {|f| f.write(str) } begin _test() ensure File.unlink(datafile) if test(?f, datafile) end end def test_datafile2 # -f data.rb datafile = "test.context1.rb" @input = INPUT2 @expected = OUTPUT.gsub(/\(none\)/, 'Hello') @options = "-f #{datafile}" # str = <<-END @user = 'Hello' @password = 'world' END File.open(datafile, 'w') {|f| f.write(str) } begin _test() ensure File.unlink(datafile) if test(?f, datafile) end end def test_untabify1 # -t (obsolete) yamlfile = "test.context2.yaml" @input = INPUT2 @expected = OUTPUT.gsub(/\(none\)/, 'Hello') @options = "-tf #{yamlfile}" # yaml = <<-END user: Hello password: world END File.open(yamlfile, 'w') {|f| f.write(yaml) } begin _test() ensure File.unlink(yamlfile) if test(?f, yamlfile) end end def test_untabify2 # -T yamlfile = "test.context2.yaml" @input = INPUT2 @expected = OUTPUT.gsub(/\(none\)/, 'Hello') @options = "-Tf #{yamlfile}" # yaml = <<-END user: Hello items: - aaa - bbb - ccc END File.open(yamlfile, 'w') {|f| f.write(yaml) } assert_raise(ArgumentError) do _test() end File.open(yamlfile, 'w') {|f| f.write(yaml.gsub(/\t/, ' '*8)) } _test() ensure File.unlink(yamlfile) if test(?f, yamlfile) end def test_symbolify1 # -S yamlfile = "test.context3.yaml" @input = < <%= h[:name] %><%= h[:mail] %> <% end %> END @expected = < foofoo@mail.com barbar@mail.org END @options = "-f #{yamlfile} -S" # yaml = <<-END list: - name: foo mail: foo@mail.com - name: bar mail: bar@mail.org END File.open(yamlfile, 'w') { |f| f.write(yaml) } begin _test() ensure File.unlink(yamlfile) if test(?f, yamlfile) end end def test_result1 # -B yamlfile = "test.context4.yaml" # @input = <<'END' user = <%= user %> <% for item in list %> - <%= item %> <% end %> END @expected = <<'END' user = World - aaa - bbb - ccc END @options = "-f #{yamlfile} -B " # yaml = <<-END user: World list: - aaa - bbb - ccc END File.open(yamlfile, 'w') {|f| f.write(yaml) } begin _test() ensure File.unlink(yamlfile) if test(?f, yamlfile) end end def test_context1 # -c @input = <<'END' user = <%= @user %> <% for item in @list %> - <%= item %> <% end %> END @expected = <<'END' user = World - aaa - bbb - ccc END # @options = ['-c', '{user: World, list: [aaa, bbb, ccc]}'] _test() @options = ['-c', '@user="World"; @list=%w[aaa bbb ccc]'] _test() end def test_include1 # -I dir = 'foo' lib = 'bar' Dir.mkdir dir unless test(?d, dir) filename = "#{dir}/#{lib}.rb" File.open(filename, 'w') do |f| f.write <<-'END' def escape(str) return "<#{str.upcase}>" end END end # @input = "<% require '#{lib}' %>\n" + INPUT.gsub(/<%= item %>/, '<%= escape(item) %>') @expected = OUTPUT.gsub(//, '<>').gsub(/b\&b/, '').gsub(/"ccc"/, '<"CCC">') @options = "-I #{dir}" # begin _test() ensure File.unlink filename if test(?f, filename) FileUtils.rm_r dir if test(?d, dir) end end def test_require1 # -r dir = 'foo' lib = 'bar' Dir.mkdir dir unless test(?d, dir) filename = "#{dir}/#{lib}.rb" File.open(filename, 'w') do |f| f.write <<-'END' def escape(str) return "<#{str.upcase}>" end END end # @input = INPUT.gsub(/<%= item %>/, '<%= escape(item) %>') @expected = OUTPUT.gsub(//, '<>').gsub(/b\&b/, '').gsub(/"ccc"/, '<"CCC">') @options = "-I #{dir} -r #{lib}" # begin _test() ensure File.unlink filename if test(?f, filename) FileUtils.rm_r dir if test(?d, dir) end end def test_enhancers1 # -E @input = < b&b "ccc"] %> % for item in list - <%= item %> : <%== item %> - [= item =] : [== item =] % end END @expected = < - <aaa> : - b&b : b&b - b&b : b&b - "ccc" : "ccc" - "ccc" : "ccc" END @options = "-E Escape,PercentLine,HeaderFooter,BiPattern" _test() end def test_bodyonly1 # -b @input = INPUT @expected = SRC.sub(/\A_buf = '';/,'').sub(/\n_buf.to_s\n\z/,'') @options = '-b -x' _test() end def test_escape1 # -e @input = INPUT @expected = SRC.gsub(/<< \((.*?)\).to_s;/, '<< Erubis::XmlHelper.escape_xml(\1);') @options = '-ex' _test() end def test_invalid_option # -1 (invalid option) @input = INPUT @options = '-1' _error_test(Erubis::CommandOptionError, "-1: unknown option.") end def test_invalid_enhancer # -E hoge @options = '-E hoge' errmsg = "hoge: no such Enhancer (try '-h' to show all enhancers)." _error_test(Erubis::CommandOptionError, errmsg) end def test_invalid_lang # -l hoge @options = '-l hoge' errmsg = "-l hoge: invalid language name (class Erubis::Ehoge not found)." _error_test(Erubis::CommandOptionError, errmsg) end def test_missing_argument # -E @filename = false @options = '-E' _error_test(Erubis::CommandOptionError, "-E: enhancers required.") @options = '-l' _error_test(Erubis::CommandOptionError, "-l: lang required.") end def test_pi1 # --pi -x @input = PI_INPUT @expected = PI_SRC @options = '-x --pi' _test() end def test_pi2 # --pi -x --escape=false @input = PI_INPUT @expected = PI_ESCAPED_SRC @options = '-x --pi --escape=false' _test() end def test_pi3 # --pi @input = PI_INPUT @expected = PI_OUTPUT @options = '--pi' _test() end def test_pi4 # --pi --escape=false @input = PI_INPUT @expected = PI_ESCAPED_OUTPUT @options = '--pi --escape=false' _test() end def test_pi5 # --pi=ruby -x @input = PI_INPUT.gsub(/<\?rb/, ' - @{arr[i]}@ / @!{arr[i]}@ END @expected = <<'END' StringBuffer _buf = new StringBuffer(); for (int i = 0; i < arr.length; i++) { _buf.append(" - "); _buf.append(escape(arr[i])); _buf.append(" / "); _buf.append(arr[i]); _buf.append("\n"); } return _buf.toString(); END @options = '--pi -xl java' _test() end self.post_definition() end ruby-erubis-2.7.0/test/test-users-guide.rb000066400000000000000000000031631170760342400205140ustar00rootroot00000000000000### ### $Release: 2.7.0 $ ### copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ### require "#{File.dirname(__FILE__)}/test.rb" class KwarkUsersGuideTest < Test::Unit::TestCase DIR = File.expand_path(File.dirname(__FILE__) + '/data/users-guide') CWD = Dir.pwd() def setup Dir.chdir DIR end def teardown Dir.chdir CWD end def _test @name = (caller()[0] =~ /`(.*?)'/) && $1 s = File.read(@filename) s =~ /\A\$ (.*?)\n/ command = $1 expected = $' if ruby19? case @name when 'test_main_program1_result' expected.sub!('["eruby", "items", "x", "_buf"]', '[:_buf, :eruby, :items, :x]') when 'test_main_program2_result' expected.sub!('["_context", "x", "_buf"]', '[:_buf, :x, :_context]') end elsif rubinius? command.sub!(/^ruby\b/, 'rbx') case @name when 'test_main_program1_result' expected.sub!('["eruby", "items", "x", "_buf"]', '["_buf", "eruby", "items", "x"]') when 'test_main_program2_result' expected.sub!('["_context", "x", "_buf"]', '["_buf", "x", "_context"]') end end result = `#{command}` assert_text_equal(expected, result) end Dir.chdir DIR do filenames = [] filenames += Dir.glob('*.result') filenames += Dir.glob('*.source') filenames.each do |filename| name = filename.gsub(/[^\w]/, '_') s = <<-END def test_#{name} # $stderr.puts "*** debug: test_#{name}" @name = '#{name}' @filename = '#{filename}' _test() end END eval s end end self.post_definition() end ruby-erubis-2.7.0/test/test.rb000066400000000000000000000015241170760342400162610ustar00rootroot00000000000000## ## $Release: 2.7.0 $ ## copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ## unless defined?(TESTDIR) TESTDIR = File.dirname(__FILE__) LIBDIR = TESTDIR == '.' ? '../lib' : File.dirname(TESTDIR) + '/lib' $: << TESTDIR $: << LIBDIR end require 'test/unit' #require 'test/unit/ui/console/testrunner' require 'assert-text-equal' require 'yaml' require 'testutil' require 'erubis' Test::Unit::TestCase.class_eval do if RUBY_VERSION >= "1.9" ## minitest doesn't have 'name()' method def name @name || @__name__ end def ruby19 yield end else def ruby19 end end end if $0 == __FILE__ require "#{TESTDIR}/test-erubis.rb" require "#{TESTDIR}/test-engines.rb" require "#{TESTDIR}/test-enhancers.rb" require "#{TESTDIR}/test-main.rb" require "#{TESTDIR}/test-users-guide.rb" end ruby-erubis-2.7.0/test/testutil.rb000066400000000000000000000051721170760342400171620ustar00rootroot00000000000000### ### $Release: 2.7.0 $ ### copyright(c) 2006-2011 kuwata-lab.com all rights reserved. ### require 'yaml' require 'test/unit/testcase' def ruby18? # :nodoc: RUBY_VERSION =~ /\A1.8/ end def ruby19? # :nodoc: RUBY_VERSION =~ /\A1.9/ end def rubinius? # :nodoc: defined?(RUBY_ENGINE) && RUBY_ENGINE == "rbx" end class Test::Unit::TestCase def self.load_yaml_datafile(filename, options={}, &block) # :nodoc: # read datafile s = File.read(filename) if filename =~ /\.rb$/ s =~ /^__END__$/ or raise "*** error: __END__ is not found in '#{filename}'." s = $' end # untabify s = _untabify(s) unless options[:tabify] == false # load yaml document testdata_list = [] YAML.load_documents(s) do |ydoc| if ydoc.is_a?(Hash) testdata_list << ydoc elsif ydoc.is_a?(Array) ydoc.each do |hash| raise "testdata should be a mapping." unless hash.is_a?(Hash) testdata_list << hash end else raise "testdata should be a mapping." end end # data check identkey = options[:identkey] || 'name' table = {} testdata_list.each do |hash| ident = hash[identkey] ident or raise "*** key '#{identkey}' is required but not found." table[ident] and raise "*** #{identkey} '#{ident}' is duplicated." table[ident] = hash yield(hash) if block end # return testdata_list end def self.define_testmethods(testdata_list, options={}, &block) identkey = options[:identkey] || 'name' testmethod = options[:testmethod] || '_test' testdata_list.each do |hash| yield(hash) if block ident = hash[identkey] s = "def test_#{ident}\n" hash.each do |key, val| s << " @#{key} = #{val.inspect}\n" end s << " #{testmethod}\n" s << "end\n" $stderr.puts "*** load_yaml_testdata(): eval_str=<<'END'\n#{s}END" if $DEBUG self.module_eval s end end def self.post_definition if ENV['TEST'] target = "test_#{ENV['TEST']}" self.instance_methods.each do |method_name| m = method_name.to_s private m if m =~ /\Atest_/ && m != target end end end def self._untabify(str, width=8) return str if str.nil? list = str.split(/\t/, -1) # if 2nd arg is negative then split() doesn't remove tailing empty strings last = list.pop sb = '' list.each do |s| column = (n = s.rindex(?\n)) ? s.length - n - 1 : s.length n = width - (column % width) sb << s << (' ' * n) end sb << last if last return sb end end