One of the mantras in the Rails community is DRY (Don’t repeat Yourself), this is nothing new if your a software developer you should always look for ways to refactor your code to avoid copy and paste. Trying to maintain code with logic that has been copied and pasted to different locations is a nightmare, and one that unfortunately most of us have been exposed too.
In Rails the view part of MVC is handled by ActionView and the default templates are ERb. The views are further broken down into layouts and views. Layouts are called first for each controller then the view corresponding to the action. For the most part the layout is going to contain header elements for the xml, but what if you need some special javascript in one of you actions but not others.
You could just add it to the layout and say tough you are going to have the client load it no matter what, besides taking up extra bandwidth this can cause javascript errors for things like Google Maps where there is no associated div.
Rails gives you a better way though, you can use content_for to specify content associated with a particular yield command. For example if you wanted to use YM4R (Yellow maps 4 Ruby) to helps with your Google Maps mashup project, you could do something like this:
You would add a yield item to your layout.
<head>
<%= stylesheet_link_tag :all %>
<%= javascript_include_tag :defaults %>
<%= javascript_include_tag "popup" %>
<%= yield :head %>
</head>
Then in you view for the action you want to use the Google Map you would do something like this:
<% content_for :head do %>
<%= GMap.header %>
<%= @map.to_html %>
<% end %>
In your controller you need something that actually sets up your map, for example…
@map = GMap.new("map_div")
@map.control_init(:large_map => true,:map_type => true)
@map.center_zoom_init([75.5,-42.56],4)
@map.overlay_init(GMarker.new([75.6,-42.467],:title => "Hello", :info_window => "Info! Info!"))
That’s it, your layout stays DRY and your single view gets the Google Map.
