rails -double negative of variable
* warning - newbie alert *
I'm reading a book called RailsSpace to learn Ruby on Rails framework. The author built user profiles which the user can edit, and now he's building the public facing profiles based off the other user profiles. The only change he has to make is to basically hide the edit links on the public facing profile. He uses this function to hide it, but I don't understand how it works...hide_edit_links is a variable
# Return true if hiding the edit links for spec, FAQ, etc.
def hide_edit_links?
not @hide_edit_links.nil?
end
He also writes
By the way, the reason hide_edit_links? works in general is that instance variables are开发者_运维知识库 nil if not defined, so the function returns false unless @hide_edit_links is set explicitly.
but I don't really get it.
Can you explain in a bit more detail for a newbie?
He implements it later with this
<div class="sidebar_box"> <h2>
<% unless hide_edit_links? %> <span class="edit_link">
<%= link_to "(edit)", :controller => "faq", :action => "edit" %> </span>
<% end %>
I think the key to understand that code (I haven't read the book) is that @hide_edit_links
is not a boolean, it's just some kind of tag. If @hide_edit_links
is not nil
( it doesn't matter which object type it's) then hide_edit_links?` will return true.
I have to say that the code is not at all straight forward, it's definitely convoluted and complicated (probably without any reason)
Example 1 (New instance, without @hide_edit_links
set, so it shows link).
- The class is instantiated (this code is not in the original question, but I assume it's there), and since there's not reference to
@hide_edit_links
, the value of the instace variable isnil
- When
hide_edit_links?
is invoked from the page,@hide_edit_links
is nil, so@hide_edit_links.nil?
returns true, and thusnot @hide_edit_links.nil?
is false. - Since the page uses
unless hide_edit_links?
, it shows the link.
Example 2 (New instance, with @hide_edit_links
set with an object, so it doesn't show the link).
- The class is instantiated and
@hide_edit_links
is set to a value which is notnil
. - When
hide_edit_links?
is invoked from the page,@hide_edit_links
is not nil, so@hide_edit_links.nil?
returns false, and thusnot @hide_edit_links.nil?
is true. - Since the page uses
unless hide_edit_links?
, it doesn't show the link.
Sorry about the trivial examples... the 'feature' is not complicated, but the solution used by the author looks terribly complicated to my dumb brain.
精彩评论