(This is presentation slide for RubyKaigi 2009)
Erubis is very fast and extensible implementation of eRuby. In this slides, I show you features of Erubis, and issues related to eRuby and solution by Erubis. Also I show you some ideas about the future of template system.
Diving into HHVM Extensions (php[tek] 2016)James Titcumb
HHVM is quickly gaining popularity, and it is a pretty exciting time for PHP runtimes. Have you ever wondered what is going on beneath this slick, super-speedy engine? I wondered that myself, so I dived into the internals of HHVM, discovering a treasure trove of awesome stuff. In this talk, I will show you how HHVM works and how it all pieces together through a guided tour of the codebase. I will also show you a couple of ways to write your own incredible HHVM extensions.
Description of the API concept for engineering and how it can be useful. Particularly how it should be used with respect to genomics data. Finally, an analogy of the API concept in synthetic biology and how evolution allows encapsulation.
PHP 8.0 comes with many long-awaited features: A just-in-time compiler, attributes, union types, and named arguments are just a small part of the list. As a major version, it also includes some backward-incompatible changes, which are centered around stricter error handling and enhanced type safety. Let's have an overview of the important changes in PHP 8.0 and how they might affect you!
Diving into HHVM Extensions (php[tek] 2016)James Titcumb
HHVM is quickly gaining popularity, and it is a pretty exciting time for PHP runtimes. Have you ever wondered what is going on beneath this slick, super-speedy engine? I wondered that myself, so I dived into the internals of HHVM, discovering a treasure trove of awesome stuff. In this talk, I will show you how HHVM works and how it all pieces together through a guided tour of the codebase. I will also show you a couple of ways to write your own incredible HHVM extensions.
Description of the API concept for engineering and how it can be useful. Particularly how it should be used with respect to genomics data. Finally, an analogy of the API concept in synthetic biology and how evolution allows encapsulation.
PHP 8.0 comes with many long-awaited features: A just-in-time compiler, attributes, union types, and named arguments are just a small part of the list. As a major version, it also includes some backward-incompatible changes, which are centered around stricter error handling and enhanced type safety. Let's have an overview of the important changes in PHP 8.0 and how they might affect you!
This talk discusses various issues of low-level PHP performance, such as: When is it more efficient to use arrays or objects? What causes catastrophic garbage collection? Does adding type annotations make PHP faster or slower?
I will answer these types of question with a (shallow) dive into PHP internals, touching on various topics like value representation, bytecode optimization and GC.
iPhone applications can often benefit by talking to a web service to synchronize data or share information with a community. Ruby on Rails, with its RESTful conventions, is an ideal backend for iPhone applications. In this session you'll learn how to use ObjectiveResource in an iPhone application to interact with a RESTful web service implemented in Rails. This session isn't about how to build web applications that are served up on the iPhone. It's about how to build iPhone applications with a native look and feel that happen to talk to Rails applications under the hood. The upshot is a user experience that transcends the device.
PHP data structures (and the impact of php 7 on them), phpDay Verona 2015, ItalyPatrick Allaert
We all have certainly learned data structures at school: arrays, lists, sets, stacks, queues (LIFO/FIFO), heaps, associative arrays, trees, ... and what do we mostly use in PHP? The "array"! In most cases, we do everything and anything with it but we stumble upon it when profiling code. During this session, we'll learn again to use the structures appropriately, leaning closer on the way to employ arrays, the SPL and other structures from PHP extensions as well.The impact that PHP 7 should have on data structures will be introduced as well.
PHP 7 – What changed internally? (Forum PHP 2015)Nikita Popov
One of the main selling points of PHP 7 is greatly improved performance, with many real-world applications now running twice as fast… But where do these improvements come from?
At the core of PHP 7 lies an engine rewrite with focus on improving memory usage and performance. This talk provides an overview of the most significant changes, briefly covering everything from data structure changes, over enhancements in the executor, to the new compiler implementation.
Functional programming, though far from new, has gained much traction recently. Functional programming characteristics have started to appear in the PHP world, too. Microframeworks including Silex and Slim, middleware architectures (Stack) and even standards (PSR-7) rely on concepts such as lambdas, referential transparency and immutability, all of which come from functional programming.
I’ll give you a crash course in Erlang, a pragmatic functional language to make you feel familiar with the functional paradigm. By comparing code samples between Erlang and PHP, you’ll find out how and why you should employ functional programming in your PHP applications. You’ll see that functional programming is nothing to be scared of. On the contrary, understanding its concepts broadens your programming horizon and provides you with valuable solutions to your problems.
This talk discusses various issues of low-level PHP performance, such as: When is it more efficient to use arrays or objects? What causes catastrophic garbage collection? Does adding type annotations make PHP faster or slower?
I will answer these types of question with a (shallow) dive into PHP internals, touching on various topics like value representation, bytecode optimization and GC.
iPhone applications can often benefit by talking to a web service to synchronize data or share information with a community. Ruby on Rails, with its RESTful conventions, is an ideal backend for iPhone applications. In this session you'll learn how to use ObjectiveResource in an iPhone application to interact with a RESTful web service implemented in Rails. This session isn't about how to build web applications that are served up on the iPhone. It's about how to build iPhone applications with a native look and feel that happen to talk to Rails applications under the hood. The upshot is a user experience that transcends the device.
PHP data structures (and the impact of php 7 on them), phpDay Verona 2015, ItalyPatrick Allaert
We all have certainly learned data structures at school: arrays, lists, sets, stacks, queues (LIFO/FIFO), heaps, associative arrays, trees, ... and what do we mostly use in PHP? The "array"! In most cases, we do everything and anything with it but we stumble upon it when profiling code. During this session, we'll learn again to use the structures appropriately, leaning closer on the way to employ arrays, the SPL and other structures from PHP extensions as well.The impact that PHP 7 should have on data structures will be introduced as well.
PHP 7 – What changed internally? (Forum PHP 2015)Nikita Popov
One of the main selling points of PHP 7 is greatly improved performance, with many real-world applications now running twice as fast… But where do these improvements come from?
At the core of PHP 7 lies an engine rewrite with focus on improving memory usage and performance. This talk provides an overview of the most significant changes, briefly covering everything from data structure changes, over enhancements in the executor, to the new compiler implementation.
Functional programming, though far from new, has gained much traction recently. Functional programming characteristics have started to appear in the PHP world, too. Microframeworks including Silex and Slim, middleware architectures (Stack) and even standards (PSR-7) rely on concepts such as lambdas, referential transparency and immutability, all of which come from functional programming.
I’ll give you a crash course in Erlang, a pragmatic functional language to make you feel familiar with the functional paradigm. By comparing code samples between Erlang and PHP, you’ll find out how and why you should employ functional programming in your PHP applications. You’ll see that functional programming is nothing to be scared of. On the contrary, understanding its concepts broadens your programming horizon and provides you with valuable solutions to your problems.
Hiveminder - Everything but the Secret SauceJesse Vincent
Ten tools and techniques to help you:
Find bugs faster バグの検出をもっと素早く
Build web apps ウェブアプリの構築
Ship software ソフトのリリース
Get input from users ユーザからの入力を受けつける
Own the Inbox 受信箱を用意する
今日の話
Gisting is an implementation of Google\'s MapReduce framework for processing and extracting useful information from very large data sets. At the time of this writing, the code is available for PREVIEW at http://github.com/mchung/gisting. I am currently working to release this framework for general usage.
Distributed, Incremental Dataflow Processing on AWS with GRAIL's Reflow (CMP3...Amazon Web Services
GRAIL is a life sciences company that analyzes large data sets from high-throughput DNA sequencers to develop methods for early cancer detection. In this session, hear how GRAIL's open-source, cloud-based batch processing system, Reflow, leverages Amazon EC2, Amazon S3, and Amazon DynamoDB to support the large-scale, high-throughput, and cost-efficient data analysis that enables GRAIL's research and development efforts. Reflow takes a modern, “cloud-native” approach to batch data processing, and is architected to run directly on the facilities offered by cloud providers like AWS. This approach allows Reflow to maintain a simple design and implementation while maximally utilizing the underlying AWS services and minimizing operational overhead and computing costs.
Crossing the Bridge: Connecting Rails and your Front-end FrameworkDaniel Spector
Presented at Railsconf 2015 by Daniel Spector, @danielspecs.
Crossing the Bridge explores tools, patterns and best practices to connect your Javascript MVC framework to Rails in the most seamless way possible. The talk progresses from demonstrating the standard API request cycle to preloading data to your client-side framework to rendering your javascript on the server. It explores Isomorphic Javascript and ways of implementing it with Rails.
Introduction to Ruby on Rails by Rails Core alumnus Thomas Fuchs.
Originally a 3-4 hour tutorial, 150+ slides about Rails, Ruby and the ecosystem around it.
PHP classes in mumbai, Introduction to PHP/MYSQL..
best PHP/MYSQL classes in mumbai with job assistance.
our features are:
expert guidance by IT industry professionals
lowest fees of 5000
practical exposure to handle projects
well equiped lab
after course resume writing guidance
For more Visit: http://vibranttechnologies.co.in/php-classes-in-mumbai.html or http://phptraining.vibranttechnologies.co.in
Router is one of the most important feature or component in Web application framework,
ant it is also one of the performance bottlenecks of framework.
In this session, I'll show you how to make router much faster than ever.
Oktest - a new style testing library for Python -kwatch
Oktest is a new-style testing library for Python. It helps you to read & write tests very much. Oktest is available with (or without) standard 'unittest' module.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
All about Erubis (English)
1. RubyKaigi2009
All about Erubis
And the future of template system
makoto kuwata <kwa@kuwata-lab.com>
http://www.kuwata-lab.com/
copyright(c) 2009 kuwata-lab.com all rights reserved.
1
2. I have something to say at first...
‣ Thank you for all staff of RubyKaigi!
‣ Thank you for all audience who join this
session!
copyright(c) 2009 kuwata-lab.com all rights reserved.
2
3. Agenda
‣ Part 1. Features of Erubis
‣ Part 2.Issues about eRuby and solutions
by Erubis
‣ Part 3. Future of template system
copyright(c) 2009 kuwata-lab.com all rights reserved.
3
4. Part 1. Features of Erubis
copyright(c) 2009 kuwata-lab.com all rights reserved.
4
5. Introduction to Erubis
‣ Pure Ruby implementation of eRuby
‣ Very fast
• http://jp.rubyist.net/magazine/?0022-FasterThanC
‣ Highly functional
• HTML escape in default
• Changing embedded pattern
• Support PHP, Java, JS, C, Perl, Scheme
• and so on...
copyright(c) 2009 kuwata-lab.com all rights reserved.
5
6. Basically Usage
Ruby program:
require 'rubygems' # if need
require 'erubis'
str = File.read('template.eruby')
eruby = Erubis::Eruby.new(str)
print eruby.result(binding())
command-line:
$ erubis template.eruby # execute
$ erubis -x template.eruby # convert into Ruby
$ erubis -z template.eruby # syntax check
copyright(c) 2009 kuwata-lab.com all rights reserved.
6
7. HTML Escape in Default
str =<<END <%= %> ... WITH escaping,
<%= var %> <%== %> ... WITHOUT escaping
<%== var %>
END
eruby = Erubis::Eruby.new(str, :escape=>true)
puts eruby.result(:var=>"<B&B>")
output:
<B&am;> User can choose escape or not
<B&B> escape in default (choosability)
copyright(c) 2009 kuwata-lab.com all rights reserved.
7
8. Changing Embedded Pattern
‣ ex : use '[% %]' instead of '<% %>'
[% for x in @list %]
<li>[%= x %]</li>
You must escape regexp meta
[% end %]
characters by backslash!
## Ruby
Erubis::Eruby.new(str, :pattern=>'[% %]')
## command-line
$ erubis -p '[% %]' file.eruby
copyright(c) 2009 kuwata-lab.com all rights reserved.
8
9. Use Hash or Object instead of Binding
example of using Hash example of using Object
hash = { @title = "Example"
:title => "Example", @items = [1, 2, 3]
:items => [1, 2, 3], } erubis =
erubis = Erubis::Eruby.new(str)
Erubis::Eruby.new(str) puts erubis.evaluate(self)
puts erubis.result(hash)
<h1><%= title%></h1> <h1><%= @title%></h1>
<% for x in items %> <% for x in @items %>
<% end %> <% end %>
copyright(c) 2009 kuwata-lab.com all rights reserved.
9
10. Enhancer
‣ Ruby modules which enhances Erubis features
## do HTML escape <%= %> in default
module EscapeEnhancer
def add_expr(src, code, indicator)
if indicator == '='
src << " _buf<<escapeXml(#{code})"
elsif indicator == '=='
src << " _buf<<(#{code}).to_s;"
end
end It is easy to override Erubis features
because internal of Erubis is splitted into
end many small methods.
copyright(c) 2009 kuwata-lab.com all rights reserved.
10
11. Enhancer (cont')
### Enhance which prints into stdout
### (you can use print() in statements)
module StdoutEnhancer use _buf=$stdout
def add_preamble(src) instead of _buf=""
src << "_buf = $stdout;"
end
def add_postamble(src)
src << "n""n"
end use "" (empty string)
end instead of _buf.to_s
copyright(c) 2009 kuwata-lab.com all rights reserved.
11
12. Usage of Enhancer
All you have to do is to include
### Ruby or extend ehnacer modules
class MyEruby < Erubis::Eruby
include Erubis::EscapeEnhancer
include Erubis::PercentLineEnhancer
end
puts MyEruby.new(str).result(:items=>[1,2,3])
Specify names with ','
### command-line
$ erubis -E Escape,Percent file.eruby
copyright(c) 2009 kuwata-lab.com all rights reserved.
12
13. Standard Enhancers
‣ EscapeEnhancer : escape html in default
‣ PercentLineEnhancer : recognize lines starting with '%' as
embedded statements
‣ InterporationEnhancer : use _buf<<"#{expr}" for speed
‣ DeleteIndentEnhancer : delete HTML indentation
‣ StdoutEnhancer : use _buf=$stdout instead of _buf=""
‣ ... and so on (you can show list of all by erubis -h)
copyright(c) 2009 kuwata-lab.com all rights reserved.
13
14. Context Data
‣ You can specify data to pass into template
file (context data) in command-line
### command-line
$ erubis -c '{arr: [A, B, C]}' template.eruby # YAML
$ erubis -c '@arr=%w[A B C]' template.eruby # Ruby
<% for x in @arr %> <li>A</li>
<li><%= x %></li> <li>B</li>
<% end %> <li>C</li>
copyright(c) 2009 kuwata-lab.com all rights reserved.
14
15. Context Data File
‣ Load '*.yaml' or '*.rb' as context data file
$ erubis -f data.yaml template.eruby # YAML
$ erubis -f data.rb template.eruby # Ruby
data.yaml data.rb
title: Example @title = "Example"
items: @items =
- name: Foo [ {"name"=>"Foo"},
- name: Bar {"name"=>"Bar"}, ]
copyright(c) 2009 kuwata-lab.com all rights reserved.
15
16. Debug Print
‣ <%=== expr %> represents debug print
<%=== @var %> No need to write the
same expression twice
### Ruby code
$stderr.puts("*** debug: @var=#{@var.inspect}")
### Result
*** debug: @var=["A", "B", "C"]
copyright(c) 2009 kuwata-lab.com all rights reserved.
16
17. Support Other Programming Langs
‣ PHP, Java, JS, C, Perl,Scheme (only for convertion)
<% for (i=0; i<n; i++) { %> (example of C)
<li><%= "%d", i %>
<% } %> same format as printf()
#line 1 "file.ec" (output of erubis -xl c file.ec)
for (i=0; i<n; i++) {
fputs("<li>", stdout); fprintf(stdout, "%d", i);
fputs("n", stdout); }
copyright(c) 2009 kuwata-lab.com all rights reserved.
17
18. Conslution
‣ Erubis is very functional and extensible
• HTML escape in default
• Changing embedded pattern
• Enhancer
• Context data and file
• Debug print
• Support PHP, Java, JS, C, Perl, and Scheme
copyright(c) 2009 kuwata-lab.com all rights reserved.
18
19. Part 2. Issues about eRuby
and solutions by Erubis
copyright(c) 2009 kuwata-lab.com all rights reserved.
19
20. Issue : local variables can be changed
‣ When using binding(), local variables can be
non-local
• Difficult to find if exists
i=0 ### file.erb
str = File.read('file.erb') <% for i in 1..3 %>
ERB.new(str).result(binding) <li><%= i %></li>
p i #=> 3 <% end %>
Changed insidiously!
copyright(c) 2009 kuwata-lab.com all rights reserved.
20
21. Cause of the issue
‣ binding() passes all local variables into
template file
• It is impossible to pass only variables which you
truly want to pass
• It is hard to recognize what variables are passed
b = Bingind.new This is ideal
b[:title] = "Example" but impossible...
b[:items] = [1, 2, 3]
copyright(c) 2009 kuwata-lab.com all rights reserved.
21
22. Solution by ERB
‣ Nothing, but the author of ERB introduced a
solution to define custom Struct
• http://d.hatena.ne.jp/m_seki/20080528/1211909590
Foo = Struct.new(:title, :items)
class Foo
def env; binding(); end
end
ctx = Foo.new("Example", [1,2,3])
ERB.new(str).result(ctx.env)
copyright(c) 2009 kuwata-lab.com all rights reserved.
22
23. Solution by Erubis
‣ Use Hash instead of Binding
It is very clear what
erubis.result(:items=>[1, 2, 3]) data are passed!
def result(b=TOPLEVEL_BINDING)
if b.is_a?(Hash)
s = b.collect{|k,v| "#{k}=b[#{k.inspect}];"}.join
b = binding()
eval s, b Set hash values as local vars
end with creating new Binding
return eval(@src, b)
end
copyright(c) 2009 kuwata-lab.com all rights reserved.
23
24. Solution by Erubis (cont')
‣ Use Object instead of Binding
@items = [1, 2, 3]; <% for x in @items %>
erubis.evaluate(self) <% end %>
def evaluate(ctx) Convert Hash values into
if ctx.is_a?(Hash) instance variables
hash = ctx; ctx = Object.new
hash.each {|k,v|
ctx.instance_variable_set("@#{k}", v) }
end
return ctx.instance_eval(@src)
end copyright(c) 2009 kuwata-lab.com all rights reserved.
24
25. Issue : cost of convertion and parsing
ERB
1. 8.6 Erubis::Eruby
ERB
1. 8.7 Erubis::Eruby
ERB
1.9.1 Erubis::Eruby
0 10 20 30
(sec)
Costs of parsing and Execution
convertion are higher Parsing(by eval)
than of execution Convertion(eRuby to Ruby)
copyright(c) 2009 kuwata-lab.com all rights reserved.
25
26. Solution by ERB
‣ Convertion cost : nothing
‣ Parsing cost : helper to define method
• Usage is much different from normal usage
class Foo
extend ERB::DefMethod
def_erb_method('render', 'template.erb')
end
print Foo.new.render
copyright(c) 2009 kuwata-lab.com all rights reserved.
26
27. Solution by Erubis
‣ Convertion cost : cache Ruby code into file
• 1st time : save converted Ruby code into *.cache file
• 2nd time : read ruby code from *.cache file
eruby = Erubis::Eruby.load_file("file.eruby")
print eruby.result()
Available even in CGI
copyright(c) 2009 kuwata-lab.com all rights reserved.
27
28. Solution by Erubis (cont')
‣ Parsing cost : keep ruby code as Proc object
• The same way to use
• Almost the same speed as defining method
instance_eval can take a
def evaluate(ctx) Proc object as argument
@proc ||= eval(@src) instead of string (ruby code)
ctx.instance_eval(@proc)
end
copyright(c) 2009 kuwata-lab.com all rights reserved.
28
29. Issue: extra line breaks
‣ eRuby outpus extra line breaks
• Big problem for non-HTML text
Extra line break <ul>
<ul>
<% for x in @list %> <li>AAA</li>
<li><%= x %></li>
<% end %> <li>BBB</li>
</ul>
Extra line break
</ul>
copyright(c) 2009 kuwata-lab.com all rights reserved.
29
30. Solution by ERB
‣ Provides various trim mode
• ">" : removes LF at the end of line
• "<>" : removes LF if "<%" is at the beginning of line
and "%>" is at the end of line
• "-" : removes extra spaces and LF around
"<%-" and "-%>"
• "%" : regard lines starting with "%" as embedded
statements
• "%>", "%<>", "-" : combination of "%" and
">"/"<>"/"-"
ERB.new(str, nil, "%<>")
copyright(c) 2009 kuwata-lab.com all rights reserved.
30
31. Solution by Erubis
‣ Change operation between embedded
statement and expression
• <% stmt %> : remove spaces around it
• <%= expr %> : do nothing (leave as it is)
<ul> Remove! <ul>
<% for x in @list %> AAA
<%= x %> BBB
<% end %> CCC
</ul> Leave as it is </ul>
copyright(c) 2009 kuwata-lab.com all rights reserved.
31
32. Comparison of solutions
ERB Erubis
eRuby spec
compatible
× spec) (compatible)
(extends
Spec
simplicity
× opts) (only one rule)
(too much
Easy to
implement
× (very easy)
(complicated)
copyright(c) 2009 kuwata-lab.com all rights reserved.
32
33. Hint to think
‣ "Extra line breaks" problem has been
recognized since early times
• [ruby-list:18894] extra LF in output of eRuby
‣ Nobody hit on the idea of changing
operations between stmts and exprs
• Everybody looks <% %> and <%= %> as same
• It is important to recoginize two things which
looks to be the same things as different things
copyright(c) 2009 kuwata-lab.com all rights reserved.
33
34. Issue : Escape HTML in default
‣ <%= expr %> should be HTML escaped in
default!
• But eRuby is not only for HTML but also for all
of text file
• However security is the most important thing
‣ How to do when not to escape?
copyright(c) 2009 kuwata-lab.com all rights reserved.
34
35. Solution by ERB
‣ Nothing for officially
‣ Unofficial solution
• Define a certain class which represents HTML string
(not to escape) separately from String class
• http://www2a.biglobe.ne.jp/~seki/ruby/erbquote.html
copyright(c) 2009 kuwata-lab.com all rights reserved.
35
36. Solution by Erubis
‣ Enhance embedded pattern and Erubis class
• Fast, and easy to implement
eruby = Erubis::Eruby.new(str, :escape=>true)
# or eruby = Erubis::EscapedEruby.new(str)
puts eruby.evaluate(ctx)
Hi <%= @name %>! # with escape
Hi <%== @name %>! # without escape
copyright(c) 2009 kuwata-lab.com all rights reserved.
36
37. Issue : hard to find syntax error
<% unless @items.blank? %>
<table>
<tbody>
<% @items.each do |item| %>
<tr class="item" id="item-<%=item.id%>">
<td class="item-id"><%= item.id %></td>
<td class="item-name">
<% if item.url && !item.url.empty? %>
<a href="<%= item.url %>"><%=item.name%></a>
<% else %>
<span><%=item.name%></span>
<% end %>
</td>
</tr> • HTML and Ruby code are mixed
<% end %> • It is hard to recognize corresponding
</tbody>
</table>
'end' (because 'do' and 'end' can be
<% end %> separated 100 lines for example)
copyright(c) 2009 kuwata-lab.com all rights reserved.
37
38. Solution by ERB
‣ Nothing but '-x' option
$ erb -x foo.eruby
_erbout = ''; unless @items.blank? ;
_erbout.concat "n"
_erbout.concat "<table>n"
_erbout.concat " <tr class="record">n"
$ erb -x foo.eruby | ruby -wc
Syntax OK
copyright(c) 2009 kuwata-lab.com all rights reserved.
38
39. Solution by Erubis
‣ Provides a lot of command-line options
• -x : show Ruby script
• -X : suppress to print HTML
• -N : print line numbers
• -U : unify consecutive empty lines into a line
• -C : remove consecutive empty lines (compact)
• -z : check template syntax
copyright(c) 2009 kuwata-lab.com all rights reserved.
39
40. $ cat foo.eruby
<% unless @items.blank? %>
<table>
<% @items.each_with_index do|x, i| %>
<tr class="record">
<td><%= i +1 %></td>
<td><%=h x %></td>
</tr>
<% end %>
</table>
<% end %>
copyright(c) 2009 kuwata-lab.com all rights reserved.
40
41. -x : show Ruby script
$ erubis -x foo.eruby
_buf = ''; unless @items.blank?
_buf << '<table>
'; @items.each_with_index do|x, i|
_buf << ' <tr class="record">
<td>'; _buf << ( i +1 ).to_s; _buf << '</td>
<td>'; _buf << (h x ).to_s; _buf << '</td>
</tr>
'; end
_buf << '</table>
'; end
_buf.to_s
copyright(c) 2009 kuwata-lab.com all rights reserved.
41
42. -X : suppress to print HTML
$ erubis -X foo.eruby
_buf = ''; unless @items.blank?
@items.each_with_index do|x, i|
_buf << ( i +1 ).to_s;
_buf << (h x ).to_s;
end
end
_buf.to_s
copyright(c) 2009 kuwata-lab.com all rights reserved.
42
43. -N : print line numbers
$ erubis -XN foo.eruby
1: _buf = ''; unless @items.blank?
2:
3: @items.each_with_index do|x, i|
4:
5: _buf << ( i +1 ).to_s;
6: _buf << (h x ).to_s;
7:
8: end
9:
10: end
11: _buf.to_s
copyright(c) 2009 kuwata-lab.com all rights reserved.
43
44. -U : unifiy consecutive empty
lines into a line
$ erubis -XNU foo.eruby
1: _buf = ''; unless @items.blank?
3: @items.each_with_index do|x, i|
5: _buf << ( i +1 ).to_s;
6: _buf << (h x ).to_s;
8: end
10: end
11: _buf.to_s
copyright(c) 2009 kuwata-lab.com all rights reserved.
44
45. -C : remove empty lines
(compact)
$ erubis -XNC foo.eruby
1: _buf = ''; unless @items.blank?
3: @items.each_with_index do|x, i|
5: _buf << ( i +1 ).to_s;
6: _buf << (h x ).to_s;
8: end
10: end
11: _buf.to_s
copyright(c) 2009 kuwata-lab.com all rights reserved.
45
46. Issue : expr can contain statements
embed return value of
helper method by <%= %>
block contains
statements
<%= form_for :user do %>
<div>
<%= text_field :name %>
</div>
<% end %> beyond of
eRuby spec!
copyright(c) 2009 kuwata-lab.com all rights reserved.
46
47. Cause of Issue
<%= 10.times do %>
Hello <%= expr %> is expected
<% end %> to be completed by itself
Convert
Syntax error!
_buf = "";
_buf << ( 10.times do ).to_s;
_buf << " Hellon";
end
copyright(c) 2009 kuwata-lab.com all rights reserved.
47
48. Solution by ERB+Rails
‣ Change local variable (_erbout) on caller-
size from callee-side agic!!
b lack m
Append to '_erbout' from
Not use <%= %> internal of form_for()
<% form_for do %> _erbout = ""
Hello form_for do
<% end %> _erbout.concat("Hello")
end
copyright(c) 2009 kuwata-lab.com all rights reserved.
48
49. Solution by Erubis+Merb
‣ Extend parser of Erubis
Recognize blok in
embedded expr
<%= form_for do %> @_buf << (form_for do;
Hello @_buf << "Hellon"
<% end =%> end);
Introduce end-of- Change _buf into
block notation instance variable
copyright(c) 2009 kuwata-lab.com all rights reserved.
49
50. Discussion
‣ Extend spec of eRuby
‣ Not use black magic (kool!)
‣ Available only for helper method, in fact
• It is required to manipulate @_buf from internal
of helper method
‣ Difficult to provide general solution
copyright(c) 2009 kuwata-lab.com all rights reserved.
50
51. Conslusion
‣ A lot of issues around eRuby!
• Extra line breaks
• Local variables are not local
• Difficult to specify context variable
• Large cost for convertion and parsing
• HTML escape in default
• Difficult to find syntax error
• Can't embed return value of method with block
copyright(c) 2009 kuwata-lab.com all rights reserved.
51
52. Part 3. Future of template
system
copyright(c) 2009 kuwata-lab.com all rights reserved.
52
53. Template and Programming
‣ Template is also program code
<ul> print "<ul>n"
<% for x in @a %> for x in @a
<li><%=x%></li> Equiv. print "<li>#{x}</li>n"
<% end %> end
</ul> print "</u>n"
Possible to apply programming techniques
or concepts to template system
copyright(c) 2009 kuwata-lab.com all rights reserved.
53
54. Template and Method
Template is a kind of
method definition
<ul> s = File.read('foo.eruby')
<li><%=x%></li> e = Erubis::Eruby.new(s)
</ul> puts e.evaluate(:x=>1)
Context data is actual
Rendering template is a argument for method
kind of method invokation
copyright(c) 2009 kuwata-lab.com all rights reserved.
54
55. Template and formal argument
‣ Formal arguments may be necessary for
template
<%#ARGS: items, name='guest' %>
Hello <%= name %>!
<% for x in items %>
<li><%=x%></li> • Clear context variables
<% end %> • Available default value
copyright(c) 2009 kuwata-lab.com all rights reserved.
55
56. Template and modularity
‣ Also HTML should be Small & Many, not
Single & Large
• Same as principle of method definition
<html> <html> Be benefit for
<body> designer!
<body> </body>
<h1><%=@title%></h1> </html>
<ul id="menulist">
split
<% for x in @items %> <h1><%=@title%></h1>
<li><%=x%></li> <ul id="menulist">
</ul>
<% end %>
</ul> <% for x in @items %>
</body> <li><%= x %></li>
</html> <% end %>
copyright(c) 2009 kuwata-lab.com all rights reserved.
56
57. Template and Object-Oriented
‣ Template inheritance in Django
Parent template
....
Available to overwrite
{% block pagetitle %}
or add contents
<h1>{{title}}</h1> before/after
{% endblock %} (method override)
....
copyright(c) 2009 kuwata-lab.com all rights reserved.
57
58. Template and Aspect-Oriented
‣ Weave some code into other program
• Similar to layer of Photoshop
<table>
"for x in @a" •Enable to split HTML
<tr> and presentation
<td> "print x" logics
•Available to insert a
</tr> logic into several
"end" points (DRY)
</table>
copyright(c) 2009 kuwata-lab.com all rights reserved.
58
59. Template and Data Type
‣ End is coming to escape HTML in view layer
• forget to escape, helper method argument, ...
‣ HTML should be different data type from String
(http://www.oiwa.jp/~yutaka/tdiary/20051229.html)
• No need to take care to escape or not
• Prior art : str and unicode in Python
• "HTML + String" should be String? or HTML?
• Other escaping also should be considered (ex. SQL)
copyright(c) 2009 kuwata-lab.com all rights reserved.
59
60. Conslusion
‣ Template is also programming code
‣ Available to apply programming techniques
and concepts into template system
• Formal argument, Inheritance, AOP, and so on
‣ Template system is still on developing stage
copyright(c) 2009 kuwata-lab.com all rights reserved.
60
61. Bibliography
‣ Introduction to Template System (in Japanese)
• http://jp.rubyist.net/magazine/?0024-TemplateSystem
• http://jp.rubyist.net/magazine/?0024-TemplateSystem2
‣ Erubis
• http://www.kuwata-lab.com/erubis/
‣ Benchmarks of many template systems
• http://www.kuwata-lab.com/tenjin/
copyright(c) 2009 kuwata-lab.com all rights reserved.
61
62. one more thing
copyright(c) 2009 kuwata-lab.com all rights reserved.
62
63. Tenjin - template engine replacing eRuby
‣ Both ERB and Erubis are out of date
• They are merely text-processor
• Less features as template engine
‣ Tenjin : replacer of ERB/Erubis
• Designed and implemented as template engine from the
beginning
• Provides a lot of features required for template engines
- layout template, partial template, and so on
• http://www.kuwata-lab.com/tenjin/
copyright(c) 2009 kuwata-lab.com all rights reserved.
63