MrSkinny MrSkinny - 4 years ago 106
Ruby Question

Using Decorator pattern in Rails but can't access view helper

I'm trying to implement Decorators using the learnings from "Rails 4 Patterns" Code School course, but I'm running into trouble as I need a view helper in the Decorator class.

I want my view to have:

<%= @model_decorator.previous %>

Then in the decorator:

def previous
if object.prev_item.nil?
link_to("Previous", object)

The course suggests you make a call to the decorator within your view helper in the view file itself, but that's no good if the logic could output one result with a helper and one without. (i.e. need the output to be a link or not).

I've tried using
but it errors out as not providing the correct information for the
option. I've confirmed
link_to("Previous", object)
works within the view itself.

Answer Source

If I understand your problem correctly, you essentially want links in a plain old ruby object.

My solution would be this:

include ActionView::Helpers::UrlHelper
link_to("Previous", Rails.application.routes.url_helpers.objects_path(object))
# assuming the object is always of one class 

If the object is of a different class, than it would be possible to use the .send method to send the correct message to app ie.:

include ActionView::Helpers::UrlHelper
link_to("Previous", Rails.application.routes.url_helpers.send("#{object.class}s_path".downcase.to_sym, object))
# I'd create a function out of that line to make it a bit neater

It sounds like the error thrown by url_for comes from missing the routes and there's a few ways to include those. My solution kinda avoids that problem by using Rails.application.routes.url_helpers. Hope this helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download