I have a render
method in a view to call partial template like this:
<%= render @post if @post.present? %>
Is there a way to write like this?
<%= method_like_try(:render, @post) %>
So that I don't need to check the presence of @post
.
If it is not implemented in Ruby or Rails, I'll just stick first style.
To be honest, there is nothing wrong with
<%= render @post if @post.present? %>
It's already concise. Any attempt to shorten it will effectively cause the opposite effect.
<%= method_like_try(:render, @post) %>
Is less readable, and hides the intent of the rendering. There are a couple of possible improvements I can suggest, instead of hiding the logic into that method.
You can still reduce the line into
<%= render @post if @post %>
A nil
object evaluates to false.
The other improvements is to catch the fact that @post
is nil before. For instance, where is @post
coming from? If it's a show action, you can easily use a bang-method to raise an exception if the value is nil. Or you can use a before filter
class MyController
before_filter :find_post
def show
render @post
end
def find_post
@post = Post.find_in_someway
@post or head(404)
end
end
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments