#208
Apr 05, 2010

ERB Blocks in Rails 3

Blocks in ERB templates are handled differently in Rails 3.0 Beta 2. Learn all about it in this episode.
Download (21.2 MB, 9:41)
alternative download for iPod & Apple TV (18 MB, 9:41)

UPDATE: I recommend using the “capture” method instead of “with_output_buffer”. This has the added benefit of working outside of ERB views. Code below has been updated.

Resources

rvm install ruby-head
rvm ruby-head
gem install rails --pre
bundle install
# Gemfile
gem "rails", "3.0.0.beta2"

# application_helper.rb
def admin_area(&block)
  content = capture(&block)
  content_tag(:div, content, :class => "admin")
end
# or
def admin_area(&block)
  content_tag(:div, :class => "admin", &block) if admin?
end
<%= form_for @product do |f| %>
<% end %>

<%= div_for @product do %>
<% end %>

<% @comments.each do |c| %>
<% end %>

<% content_for :side do %>
<% end %>

<% cache do %>
<% end %>

<!-- products/show.html.erb -->
<%= admin_area do %>
  <%= link_to "Edit", edit_product_path(@product) %> |
  <%= link_to "Destroy", @product, :confirm => "Are you sure?", :method => :delete %> |
  <%= link_to "View All", products_path %>
<% end %>

RSS Feed for Episode Comments 29 comments

1. Andy Apr 05, 2010 at 01:01

How does this work with HAML??


2. Gregor Apr 05, 2010 at 01:38

You are the reason why I get out of bed on Monday mornings :-)
Thanks for another fantastic episode.


3. Bagwan Pankaj Apr 05, 2010 at 03:23

Another great addition to rails. Keep it up.


4. Slobodan Kovacevic Apr 05, 2010 at 05:54

It's worth noting that Rails 3 beta2 has a problem with latest Ruby 1.8.7 and with Ruby 1.9.1. The release notes for Rails 3 beta2 says:

"Note that Ruby 1.8.7 p248 and p249 has marshaling bugs that crash both Rails 2.3.x and Rails 3.0.0. Ruby 1.9.1 outright segfaults on Rails 3.0.0, so if you want to use Rails 3 with 1.9.x, jump on 1.9.2 trunk for smooth sailing."


5. Steve D Apr 05, 2010 at 07:30

This change would be ridiculous - is it an April Fool thing? What about legacy code?

I've always followed your brilliant exemplars of the practical effects of release changes, but this time I find it hard to believe it; I will go and check on the release notes - which I've never felt necessary to do before.


6. Steve D Apr 05, 2010 at 07:33

PS: I notice you didn't talk about backwards compatibility.


7. Ryan Bates Apr 05, 2010 at 08:10

@Andy, great question. I don't use HAML regularly so I haven't researched it yet. I'm guessing the HAML library will need to be updated to handle this as well.

@Slobodan, Thanks for pointing this out. I hope beta3 will soon be released with these version fixes.

@Steve, what specifically do you not like about this update?

Regarding backward compatibility. Leaving out the equal sign still works in Rails 3 but it is deprecated. So if you are building an engine that has views which need to be compatible with both Rails 2 and Rails 3 then it's best to not use the equal sign for now.

I'm not certain in what other scenarios you'll need backwards compatibility.


8. Steve D Apr 05, 2010 at 09:08

@Ryan, I think that this is a "big" update - unless I have been putting too much of my effort into views.

It is a fact that every developer has had to understand the difference between Ruby code which returned content, and Ruby code which affected the logical flow of content within the view.

This change seems to alter the syntax for the sake of some new paradigm, whilst still retaining the anomaly of the "cache" facility.

I cannot see why the backward compatibility cannot be guaranteed for the foreseeable future.

As to your point about other scenarios, I can't think of any, but unless you're using extensive JQuery (or javascript), I believe that views are a fundamental resource of any Rails application.

I shall still watch your impeccable Railscasts despite my pique on this issue with Rails 3!


9. Steve D Apr 05, 2010 at 09:38

Further to my comments, as someone who has seen (and worked in) the dramatic expansion of IT from the 70s (IBM), through the 80s and 90s (Microsoft), and the 21st century (Microsoft/Apple/Open Source), I am concerned that new releases of established frameworks/products will require upgrading in a way which requires expensive in-house/consultany effort which would not be otherwise necessary.

Cannot some bright chap in the Rails community (I'm too thick) produce a plugin which emulates backward compatibility in this area; or at least a migration tool which identifies and converts heretic syntax to its new spiritual home?


10. anon Apr 05, 2010 at 09:54

@Steve Yes, that would be ideal. Unfortunately, the Rails team and open source does not have the funding of MS or Sun/Oracle. While I agree the Rails team should make each version backwards compatible, I think framework innovation would be slowed. Rails 3 is a major version so expect it to have breaking changes.


11. Steve D Apr 05, 2010 at 10:26

@anon Yes I understand the constraints; but the drivers of Rails 3 have put an extraordinary amount of effort into the new framework. I'm just a bit disappointed, that having created a game-changing technology, they have not put (in my opinion) enough thought into the time and resources their "adherents" have expended in developing businesses/sites which follow their lead.

To an old man, this seems IBM/Microsoft ish rather than community-sensitive progress.

I shall now be silent, as I'm sure I'm offending the majority.


12. Jose Apr 05, 2010 at 11:40

This cast came just in time. I was getting duplicate output due to yields that I had in the helpers. The cast pointed me in the right direction and was able to solve the problem quickly. Thanks.

This fundamental change in the handling of ERB makes for better streamlined helper code. It's a good design improvement. Although it potentially breaks legacy code, it's well worth it.


13. Michael Koper Apr 05, 2010 at 13:14

@Andy: you can easily do this with haml.

="string" == <%= "string" %>
-"string" == <& "string" %>


14. Ashley Williams Apr 05, 2010 at 15:01

@Steve D: Why is full backwards compatibility important in a major release? Rails 2.x isn't going anywhere, it's feature packed, and if necessary will receive security updates for the foreseeable future — Rails 3 won't make 2.x any less awesome! I can see many production Rails 2.x apps never needing to be upgraded.

What makes Rails great is it *isn't* an enterprise framework, it's driven on innovation by developers who like to move fast. Let's not bog that down with specs and red tape.


15. Roshan Shah Apr 05, 2010 at 19:12

Drupal does no gurantee backward compatibility. If you want to lead by innovating, sometimes you have to sacrifice legacy. We always do that.

I think it is a positive step by Rails community to carry a vision to have backward compatibility where possible only if it does not slow down innovation.


16. Gang Apr 06, 2010 at 05:59

A good changes.


17. Steve D Apr 06, 2010 at 06:46

Despite my vow of silence, I just want to reply to a couple of (good) points.

@Ashley I agree that full backward compatibility may be inappropriate for a major release, but I should have thought that such a major element of MVC should at least have an easy migration path, or a long-lasting "compatibility mode". It seems to me that either would be relatively easy; and ideally, should be integrated into the official Rails releases, rather than waiting/hoping for one (or more) individuals in the community to chuck in such tools or plugins.
I also take your point on the ability to stick with 2.x, but I don't really believe that fixes and minor releases are going to be abundant in the coming years.
I also get your comment that this "product" is driven by developers who want to move quickly (of whom I am an avid member); but development is - like it or not - but a minor part of the lifecycle, and we must always have an eye to the legacy we are leaving.


18. Phil Apr 06, 2010 at 08:37

a railscast about authentication in rails 3 would be really nice.


19. Bill Apr 06, 2010 at 09:56

Ryan! You are so sexy!


20. Maxim Kulkin Apr 06, 2010 at 13:34

What happened to #capture helper method ? What is the difference of it and new #with_output_buffer ?


21. jamesw Apr 06, 2010 at 20:27

Well, I don't know where you find the time to get to grips with all the new functionality that's going on and I really ought to say thank you as your Railscasts have saved my bacon many times.

I am a little dissapointed and rather pleased at the same time with this new form functionality.

I've been looking forward to Rails introducing form inheritance and I had an incling that Rails 3 mught just be the time this ws done but alas it seems to be not the case. I believe this is a major oversight in Rails particularly when everything else is an object. The pleasing thing is to see the view helpers becoming more friendly and intuitive to use but they are still not a substitute for form inheritance.

Thankyou for your massive contributions to the Rails community

James


22. Ernie Miller Apr 07, 2010 at 17:01

Thanks Ryan. When this change showed up in Rails master just a little bit before beta 2 I was sort of wondering what the proper form (no pun intended) would be, now, for those of us writing helper methods.

This confirms the direction I was going with my collection_check_boxes FormBuilder mixin, since I'm not outputting any extra content, just yielding a specific object to the block, more like fields_for than form_for.


23. Mark Richman Apr 08, 2010 at 07:35

I get this error using rvm:

mark@macpro:~# rvm install ruby-head
Installing Ruby from source to: /Users/mark/.rvm/rubies/ruby-head
Running autoconf
Configuring ruby-head, this may take a while depending on your cpu(s)...
Compiling ruby-head, this may take a while, depending on your cpu(s)...
Installing ruby-head
Installation of ruby-head is complete.
Updating rubygems for /Users/mark/.rvm/gems/ruby-head@global
Updating rubygems for /Users/mark/.rvm/gems/ruby-head
Installing gems for ruby-head.
Installing rdoc
Installing
Error running '/Users/mark/.rvm/rubies/ruby-head/bin/gem install --no-rdoc --no-ri ', please check /Users/mark/.rvm/log/ruby-head/gems.install*.log
Installing rake
Installing
Error running '/Users/mark/.rvm/rubies/ruby-head/bin/gem install --no-rdoc --no-ri ', please check /Users/mark/.rvm/log/ruby-head/gems.install*.log
Installation of gems for ruby-head is complete.


24. Peter Apr 08, 2010 at 12:41

I'm loving the Rails 3 with all it's new features, but I'm having problem with the ruby process literally EATING memory. With each request the process grows with perhaps 10 mb. Does anyone know why this is? Working on a Mac and a SQLite DB.


25. Boris Apr 09, 2010 at 16:55

Thanks a lot Ryan for all your hard work! This web site is really inspiring for many people and slowly but surely becomes "Ruby on Rails encyclopedia"!

Unfortunately, these pesky shoe-spammers got into feedback as well and flooded it with useless feedbacks trying to get extra link.

Fortunately, there are quite a few solutions:
1) Railscasts switches to "nofollow" links (http://en.wikipedia.org/wiki/Nofollow)
2) switching to something like tinyurl.com
3) put same cleanup mechanism as in "comments" section into "feedback" section

This will zero value of the links and spammers will disappear in a little while


26. dimas priyanto Apr 10, 2010 at 02:06

i'm late on this is great episode..


27. Roel Apr 10, 2010 at 05:26

When I try to install ruby-head using RVM i get the following error message:

run with --debug for full backtrace
make: *** [rdoc] Error 1
[2010-04-10 14:22:10] make
uh-oh! RDoc had a problem:

Directory .ext/rdoc already exists, but it looks like it
isn't an RDoc directory. Because RDoc doesn't want to risk
destroying any of your existing files, you'll need to
specify a different output directory name (using the
--op <dir> option).

Any idea what can be going wrong? And how do I specify rvm to install without RDOC?

Thanks.


28. Luis Apr 10, 2010 at 09:52

Does anyone have a solution to the ".ext/rdoc already exists" problem?


29. Michael Hasenstein Apr 10, 2010 at 11:22

@Roel

You didn't include the important line which should be just above where you started cutting. If you saw the same message I had it said it could not find yaml.h, "please install libyaml". So go ahead and install libyaml :-) (and libyaml-devel, if that's a different package)


30. Michael Hasenstein Apr 10, 2010 at 11:23

@Luis: yes "rm -r .ext/rdoc" followed by "make install".


31. judd Apr 10, 2010 at 15:33

Another great one. Thanks for all you do!


32. Fabiano PS Apr 11, 2010 at 18:06

Cool episode! This would get me confused for a while :P

About backwards compatibility, I see it as good for 2 things: Stimulation to produce outdated code, and some more IFs in the code, adding up to a slow platform.
I simply trust Rails team, great work guys. And since it is O.S. just add your local path :)


33. Steve D Apr 12, 2010 at 05:30

I can't agree with Fabiano that backward compatibility stimulates the production of outdated code; but I must say I'm impressed if he is able to remove those performance-degrading conditional statements from his Rails code.


34. Fabiano P S Apr 13, 2010 at 11:41

Sorry, I probably expressed myself in the wrong manner, english is not my mother language.

Correcting, my point was that: in order to keep backwards compatibility, the framework/language/core must keep it open to the old format, and when you think just about 1 or 2 functions it doesn't really matter, but if becomes a policy and everything is backwards compatible, when you take the time to analise, every page request takes hundreds of IFs more than the non-compatible way.

I'm not saying that backwards c. is all bad, not whole! But if your app uses too much an old function and you decide *must* upgrade, just add your own path to that function


35. Steve D Apr 14, 2010 at 10:50

@Fabiano
Ok, I understand your point and I apologise for my assumptions of what you meant.

However, I still feel that backward compatibility woul be appropriate for at least 18 months after the final Rails 3.0.


36. Steve D Apr 14, 2010 at 10:57

I should add that I am only looking at the View component in terms of backward compatibility; I don't see that the other improvements/revisions will have a substantive impact.


37. James Whitfield Apr 20, 2010 at 15:30

Guys, can we please stop talking about Rails 3? It's still in BETA.
Let's just concentrate on rails 2.3.x? It's what we are all using and Ryan, I am sure everyone here will appreaciate your coverage on rails 2.3.x.

thanks


38. Olek Apr 28, 2010 at 14:11

Hi Ryan,

great video, as usual.

I have a question, not directly related to ERB, but more to blocks. Why use the '&' sign when passing a block as an argument?


39. Aaron M Apr 29, 2010 at 20:02

When running the rails update checker, I found i did have to provide an = for the each method, such as <%= @comments.each do |comment| %>

To those who want to see rails 2.3.x, rails 3 will most likely go into full release later this year. Personally, id rather start seeing this stuff now, to keep up with the curve.

On another note, anyone else in converting an app rails 3 have trouble using resources stored in the public folder such as stylesheets?


40. dave4c03 May 07, 2010 at 22:18

Ryan, is this what you mean by using the "capture" method?

Rail2 and Rails3 beta3 process <%= '<h1>hello</h1>' %> differently.

Rails3 must use <%= capture {'<h1>hello</h1>'} %> to get the same
result as Rails2

Is this intentional or is it a bug?


41. Christian Audigier Jul 21, 2010 at 00:35

Wonderful article,thanks for putting this together! "This is obviously one great post. Thanks for the valuable information and insights you have so provided here


42. coach pureses Jul 26, 2010 at 01:23

Coach is a world brand, product quality is good, it is a kind of fashion.


45. site dizin Aug 02, 2010 at 09:25

I am apreciating it very much.I have never read such a lovely article and I am coming back. Site dizin olarak elimizden geleni yapalım


45. Pump Seal Aug 08, 2010 at 01:56

ISO9002 manufacturer and exporter of manufacturer and exporter of mechanical seal, Pump Seal, Split Seal, Cartridge Seal and Flygt Seal and other sealing materials.


46. UGG Boots on sale Aug 10, 2010 at 18:43

Gooooooooooooooooooood luck ~~!!


47. Coach Outlet Aug 12, 2010 at 03:40

Here we have new style Coach Handbags.All the Coach purses are good quality and lower price.A fashion Coach Outlet is dreamed by the fashion females.Welcome to our store discountbagshop.com.I am sure you will find one for yourself.


48. p90 workout Aug 12, 2010 at 09:11

I was wondering if you ever considered changing the layout of your blog? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having one or two images. Maybe you could space it out better?


49. jordan air shoes Aug 14, 2010 at 01:10

I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better.


50. oppo Aug 15, 2010 at 08:39

This was really useful. Thanks Ryan!


51. Rip Blu-ray for Mac Aug 18, 2010 at 01:37

Thanks,it's so good.
suport!


52. supra tk society Aug 18, 2010 at 18:46

good job,good article


53. AVI to iPad Aug 19, 2010 at 00:55

This was really useful.


54. Wholesale hats Aug 20, 2010 at 20:07

Generally I do not post on blogs, but I would like to say that this post really forced me to do so, Excellent post!


55. converse all star Aug 20, 2010 at 20:50

love converse all star,love yourself.High quality low price.It's fit for you.


56. lina Aug 23, 2010 at 23:32

What youre saying is completely true. I know that everybody must say the same thing, but I just think that you put it
in a way that everyone can understand. I also love the images you put in here. They fit so well with what youre trying to say.
Im sure youll reach so many people with what youve got to say.<b><a href=http://www.tygluegun.com>glue stick</a></b> |<b><a href=http://www.tygluegun.com>glue gun</a></b>
|<b><a href=http://www.wanjia-ylm.cn>booster cable</a></b> |<b><a href=http://www.wanjia-ylm.cn>power cord</a></b>


57. lina Aug 23, 2010 at 23:41

Well done, I admire the valuable information you offer in your articles. I will bookmark your blog
and have my children check up here often. I am quite sure they will learn lots of new stuff here than
 anybody else<b><a href=http://www.hzhtdq.cn>power strip</a></b> |<b><a href=http://www.hzhtdq.cn>extension cord</a></b>
 |<b><a href=http://www.hzhtdq.cn>trouble light</a></b>


58. cool stuff Aug 25, 2010 at 02:16

very cool article ,like my cool stuff .very useful.thanks for sharing the article!


59. louis vuitton shoes Aug 26, 2010 at 20:55

Thanks for sharing your article. I really enjoyed it. I put a link to my site to here so other people can read it. My readers have about the same interets


60. rap Aug 29, 2010 at 08:53

good job,good article


61. herve leger dress Aug 30, 2010 at 19:46

Yuyao Huaneng sanitary ware factory is specialized in production of plumbing fittings.


62. snow boots Aug 30, 2010 at 20:24

Note that Ruby 1.8.7 p248 and p249 has marshaling bugs that crash both Rails 2.3.x and Rails 3.0.0. Ruby 1.9.1 outright segfaults on Rails 3.0.0, so if you want to use Rails 3 with 1.9.x, jump on 1.9.2 trunk for smooth sailing."


63. Dolce & Gabbana Belts Sep 01, 2010 at 22:47

Hi, good post, and awesome weblog you have here!
What’s this theme you use? Is it customized?
If customized can you please facilitate me the website of the company who designed it for you?
I would apreciate to have him/her do one for me also!


64. blu ray ripper Sep 02, 2010 at 00:25

This is really a nice guide for Newbies like me. Thank you.

Add your comment:

(SKIP THIS ONE)

(required)

(not shown)


(use pastie or gist for code)

sponsored by:
if you want to help:
required:
Get Quicktime Player
Give Back to Open Source