* 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_linksis not a boolean, it’s just some kind of tag. If@hide_edit_linksis notnil( 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_linksset, so it shows link).@hide_edit_links, the value of the instace variable isnilhide_edit_links?is invoked from the page,@hide_edit_linksis nil, so@hide_edit_links.nil?returns true, and thusnot @hide_edit_links.nil?is false.unless hide_edit_links?, it shows the link.Example 2 (New instance, with
@hide_edit_linksset with an object, so it doesn’t show the link).@hide_edit_linksis set to a value which is notnil.hide_edit_links?is invoked from the page,@hide_edit_linksis not nil, so@hide_edit_links.nil?returns false, and thusnot @hide_edit_links.nil?is true.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.