6. CONTENT_FOR
# /layouts/application.html.erb
# foobar.html.erb
<p>fooooooooooooooooooo</p> A <html>
<head>
<% content_for :page_javascript do %>
<script type=quot;text/javascriptquot;> B <%= yield :page_javascript %>
... B
</script> </head>
<% end %> <body>
<p>barrrrrrrrrrrrrrrrrr</p> A A <%= yield %>
<div id=”sidebar”>
<%= yield :sidebar %>
<div>
</body>
</html>
7. PASSING BLOCK PARAMETER
Original version, we need a helper
<% link_to_remote some_helper(contact), :url => contact_path(contact), :method => :get %>
My Want
<% link_to_remote :url => contact_path(contact), :method => :get do %>
<span class=quot;picturequot;>
<%= image_tag contact.buddy_icon %>
</span>
<span class=quot;real-namequot;> <%= contact.full_name %></span>
<% if contact.friendly? %>
<span class=quot;is-friendquot;>is your friend.</span>
<% else %>
<span class=quot;no-friendquot;>is not your friend.</span>
<% end -%>
<span class=quot;nicknamequot;><%= contact.nickname %></span>
<% end -%>
8. PASSING BLOCK PARAMETER
Use block_given?, concat and capture(&block)
# provide block suppoet
def link_to_remote(*args, &block)
if block_given?
options = args.first || {}
html_options = args.second
concat( link_to_function(capture(&block), remote_function(options), html_options ||
options.delete(:html)) )
else
name = args.first
options = args.second || {}
html_options = args.third
link_to_function(name, remote_function(options), html_options ||
options.delete(:html))
end
end
9. CONTENT_TAG
Ruby Style, less line of code
<% if some_condition %>
<h1>foobar</h1> <%= content_tag(quot;h1quot;, quot;foobarquot;) if some_condition %>
<% end %>
HTML attributes as helper options
def some_helper( title, options = {} )
content_tag(quot;pquot;,
content_tag(quot;spanquot;, title, options), :class => 'p_classquot;)
end
<p class=quot;p_classquot;><span class=quot;foobarquot;>test</span></p>
12. PROBLEM AND SOLUTION
• Weneed complex/logistic HTML in helper, but write a lot
HTML string + operators are painful.
• Myearly solution: use markaby plugin, but it’s slow and yet
another dependency.
• currentsolution idea from Composite&Builder pattern
(Refactoring to Patterns book), it’s simple, component and fast.