Rails Helpers and Instance Variables
1 <%= render :partial => "partial", :object => the_object %>
2
I was reading the code for the FileColumn, helper and I had a thought. What if we could obviate the need for requiring instance variables for helpers ?
A recent example on the mailing list ? render partial and passing in the object, by Mark Van Holstyn. In the thread, he asks why he can’t do:
app/controllers/user_controller.rb
1 def edit
2user</span> = <span class="co">User</span>.find_by_id(<span class="i">1</span>) <span class="no">3</span> render <span class="sy">:partial</span> => <span class="s"><span class="dl">'</span><span class="k">address</span><span class="dl">'</span></span>, <span class="sy">:object</span> => <span class="iv">user.address}
4 end
His partial being:
app/views/shared/_address.rhtml
1 ><%= text_area(‘address’, ‘street’) %>
2
Reading FileColumn helper’s code, and the code in Rails own helpers, the following idiom is used to get a hold of the instance variable:
file-column-0.3/lib/file_column_helper.rb
1 def url_for_file_column(object_name, method, suffix=nil)
2 object = instance_variable_get("@#{object_name.to_s}")
3 …
4 end
What if we did it this way instead ?
file-column-0.3x/lib/file_column_helper.rb
1 def url_for_file_column(object_name, method, suffix=nil)
2 object = case object_name
3 when String, Symbol
4 instance_variable_get("@#{object_name.to_s}")
5 else
6 object_name
7 end
8 …
9 end
Actually, this should all be abstracted away in some kind of helper for helpers. Let me take a moment to prepare a patch. I think this would make things quite a bit easier for partial users.