Friday, January 04, 2008

adding special helpers

I was cleaning up my view and decided that I want to add two helpers, display_if and display_unless to help clean up the view.

Instead of doing:

<% if @login %>
Hello <%= @user_name -%>.
<% end %>

It would be like this:

<% display_if @login %>
Hello <%= @user_name -%>.
<% end %>

I came from the Asp.Net world so writing a custom control to do this is not easy. I was expecting it to be difficult in Rails also but it turned out to be very simple.

It took me less than 10 minutes to figure it out from not knowing how to do it at all. Hopefully, I am doing it correctly.
Here is the code for the two helpers. Just put them in your application_helper.rb file.

def display_if(condition, &block)
raise ArgumentError, "Missing block" unless block_given?

if condition
output = capture(&block)
concat(output, block.binding)
end
end
def display_unless(condition, &block)
raise ArgumentError, "Missing block" unless block_given?

unless condition
output = capture(&block)
concat(output, block.binding)
end
end

No comments: