views:

345

answers:

4

I have a method on an active record class that renders an ERB template for a messaging system. The simplified code looks like this:

ERB.new(template).result(binding)

where binding is the current Binding of the ActiveRecord model object and template is an erb template file read in from the file system.

I would like to use some named routes within the template, but haven't been able to make the named routes available.

I've seen posts all over stating to include/require various combinations of the following into the current ActiveRecord model (or preferably as a singleton):

include ActionView::Helpers::TagHelper
include ActionView::Helpers::AssetTagHelper
include ActionController::UrlWriter
require 'action_controller/routing'
include ActionController::Routing
include ActionController::Routing::Routes
include ActionController::Routing::NamedRoutes

Some of these error and I think are not correct at all...others I see no benefit from since the routes still don't work. Does anyone have an idea?

A: 

Try "include ApplicationController"

btelles
ApplicationController is a class so it can't be included, that's part of the problem with some of my initial statements in the question.
johnml
A: 

I think you're approaching this the wrong way. MVC is all about separating the Models from Views, and Controllers. You're trying to give your Model access to the View, which just shouldn't be done in Rails.

It kind of begs the question, why? Unless you're planning on storing the rendered template in your model, you're going about this the wrong way. Even then, there are better ways to do it.

Such as a call to render :partial in the controller at creation/update time.

Including all those extra classes are going to bog down your model.

EmFi
The situation you describe isn't exactly what we are doing. It's true we could break this into a slightly different setup with some controller type class between the model and the render, but at this time it doesn't seem necessary.What we are doing is really giving a custom view / renderer access to application and rails view methods. Also, the methods don't need to be included in the model as a whole, only when the method containing the `ERB.new` is called. This is generally done in background processing, not in the middle of every web request.
johnml
+1  A: 

I got all named routes and tag helpers into the binding by using:

class << self
  include LegacyUrlsHelper #a proprietary module
  include ActionView::Helpers::TagHelper
  include ActionView::Helpers::AssetTagHelper
  include ActionView::Helpers::UrlHelper
  include ActionController::UrlWriter
end

The only issue might be setting default_url_options[:host], which I have yet to test.

johnml
A: 

You really only need:

include ActionView::Helpers::UrlHelper
include ActionController::UrlWriter

You will also need to set default_url_options[:host] if you try to use any *_url methods or url_for instead of just *_path.

Matt Todd