Last week, while developing a feature I had some code like this in a view:
link_to_unless @post.url.blank?, "Link to post", @post.url |
Where url is an attribute of type String. As people usually don’t like negative conditionals, we can easily rewrite this code as:
link_to_if @post.url.present?, "Link to post", @post.url |
However, we can clean our code a little bit using the #{attribute}? method.
link_to_if @post.url?, "Link to post", @post.url |
The #{attribute}? method is a method defined automatically by Active Record. Intuitively, you may think that it is equivalent to !!url and then would evaluate to true when an empty string, but Rails is smart enough to detect that the attribute is a string and returns the equivalent of !url.blank?, as you may see in these lines in Rails source code, which proved itself very useful.
Active Record defines many other attribute methods like that, for example url_changed?. What about you? What is your favorite Rails attribute method?
This entry was posted on Monday, May 28th, 2012 at 1:00 pm and is filed under English. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.
-
http://railscasts.com Ryan Bates
-
rlmflores
-
sameera207
-
Andrew C. Greenberg
-
Dennis Monsewicz
-
http://railscasts.com Ryan Bates
-
http://twitter.com/keymone Max

All
English only
Em português apenas