I would like to use the following partial in various views across different controllers. Is there a way to replace @person with a more general variable that simply calls the instance variable of the current controller, not matter if it’s @person or @user or @company or whatever?
<% content_for(:timestamps) do %>
<p>Created: <%= l @person.created_at, :format => :long %>, Last updated: <%= l @person.updated_at, :format => :long %></p>
<% end %>
Thanks for any help.
This is my helper function based on Xavier’s code:
def timestamps
content_for(:timestamps) do
current_string = controller.controller_name.singularize
current_object = instance_variable_get("@#{current_string}")
created_at_time = l(current_object.created_at, :format => :long)
updated_at_time = l(current_object.updated_at, :format => :long)
text = "Created: #{created_at_time}, Last updated: #{updated_at_time}"
content_tag(:p, text)
end
end
This is doable. Try this:
Of course, you’ll want to do error/nil checking. And if you’re an MVC purist (or just like clean code), you’ll probably want to move it to a helper. But it’s a functional starting point.
Hope that helps!