Have you ever wanted to include a partial in Ruby on Rails only if the partial file actually exists ? This can be handy e.g. if you want to be able to include a special menu (as a partial) for some controller actions based on the action name (controller.action_name) but don’t want to make a dummy partial for every action (which is normally needed since Rails will throw an error if it can’t find a partial).

The following example will render a partial contained in the file _.rhtml only if this file exists:

def render_menupartial
render_partial(controller.action_name) if FileTest.exist?(File.join(RAILS_ROOT, 'app', 'views',controller.controller_name,'_'+controller.action_name+'.rhtml'))
end

remember to call this from your view (or probably layout) like < %= render_menupartial %> instead of < % render_menupartial %>.

I know: basic stuff, but since I already used this basic functionality quite often I’m sure someone out there will find this useful.