Ruby Developer Notes Useful things

3May/111

Keep views simple

Some times you need complex logic in views to filter some fields from unregistered users and show default message for blank fields. This case instead of tons if statements you can use nifty helpers with the power of ruby blocks. Like this:

[cc lang="ruby"]
def hide_field(object, field = nil, &block)
if current_user # can? :read_fields, object # for cancan fans
block_given? ? yield : object.send(field.to_sym)
else
'hidden'
end
end

def stub_blank(object, &block)
if object.present?
block_given? ? yield : object
else
'not set'
end
end
[/cc]

And now in your views you can use it like this:
[cc lang="ruby"]
hide_field order, :contact_name
hide_field(order) { order.company.name }
stub_blank(order.employees_num)
stub_blank(order.employees_num) { I18n.t(:employee, :count => order.employees_num) }
hide_field(order) { stub_blank order.contact_name }
[/cc]

This small trick can save many lines of code in your views. Enjoy!

Comments (1) Trackbacks (0)
  1. And to think I was going to talk to sooemne in person about this.


Leave a comment

No trackbacks yet.