Reputation: 163
I'm trying to best understand how to use rail helpers together with haml views.
I have a view which originally contained this logic
= fund_levels_last(i, @fund_level_count) ? ( link_to "add new level", ad, {class: 'button orange sm'} ) : ( link_to "remove", accounts_ad_fund_level_path(ad, fl.object.id), {:class => 'button orange sm', :method => :delete, :remote => true, :confirm => t('q.are_you_sure')} )
Wanting to keep the view as clean of code as possible, I have been trying to move this logic to the helper.
def fund_levels_last(i, flcount)
if i == flcount
true
else
false
end
end
def fund_levels_btn(i, flcount)
if self.fund_levels_last(i, flcount)
link_to "add new level", ad, {class: 'button orange sm'}
else
link_to "remove", accounts_ad_fund_level_path(ad, fl.object.id), {:class => 'button orange sm', :method => :delete, :remote => true, :confirm => t('q.are_you_sure')}
end
end
However, in the helper I don't have access to the variables and objects in the view (ad, object, fl etc). I presume I could pass all those on to the helper methods, but somehow that seems too complicated and I have the feeling I'm heading down the wrong track here. My single line of code in the view seems to end up being 15 lines of code in the helper...
What would the simplest method of moving this logic from the view to a helper be?
Upvotes: 0
Views: 618
Reputation: 10474
If your code is simple enough, you may actually want a partial. Then you can pass code/variables like so:
<%= render :partial => 'funds/partial_view', :locals => { :var => variable } %>
but if you need a helper, you will have to pass as parameters:
def funds_helper(var)
//do something interesting
end
however, there is no reason to take all your logic out of the view, instead break it into partials:
in controller:
@fund_level = fund_levels_last(i, @fund_level_count)
in view:
<%= @fund_level ? render :partial => 'funds/add_new_level' : render :partial => 'funds/remove_level' %>
Then have your partial views have the correct view.
Upvotes: 2
Reputation: 6356
By the way, the method
def fund_levels_last(i, flcount)
if i == flcount
true
else
false
end
end
could simply be :
def fund_levels_last(i, flcount)
i == flcount
end
and also, methods that return boolean often ends with a ?
so it would become def fund_levels_last?(i, flcount)
Upvotes: 3