Access ActionView Helpers from inside the model

I have a simple template system that calls a method show_medefined inside different classes of my model (prominent widgets) when rendering a template. These widgets originally returned the html as a string. So in my erb I have somethink like this.

<% @template.widgets.each do |widget| %>
   <%= widget.show_me %>    
<% end %>

As widget representations become more complex, I begin to use partial widgets to render them, by calling the ActionView::Baserender method inside my widgets (please do not throw it out yet :)

def show_me
      # ... specific calculations and other magic.
    ActionView::Base.new(MyApp::Application.config.view_path).render(:partial => "widgets/weather_widget", :locals => {:data => data, :settings => settings})  
end

So, this works like a charm (actually ...), but when I want to use helpers inside the partial part of the widget (for example. widgets/_weater_widget.html.erb), They do not work. eg. javascript_tagraises

can't convert nil into String
actionpack (3.0.0) lib/action_view/helpers/asset_tag_helper.rb:790:in `join'
actionpack (3.0.0) lib/action_view/helpers/asset_tag_helper.rb:790:in `rails_asset_id'
actionpack (3.0.0) lib/action_view/helpers/asset_tag_helper.rb:813:in `rewrite_asset_path'
actionpack (3.0.0) lib/action_view/helpers/asset_tag_helper.rb:742:in `compute_public_path'
actionpack (3.0.0) lib/action_view/helpers/asset_tag_helper.rb:256:in `javascript_path'
actionpack (3.0.0) lib/action_view/helpers/asset_tag_helper.rb:822:in `javascript_src_tag'
actionpack (3.0.0) lib/action_view/helpers/asset_tag_helper.rb:362:in `block in javascript_include_tag'
actionpack (3.0.0) lib/action_view/helpers/asset_tag_helper.rb:362:in `collect'
actionpack (3.0.0) lib/action_view/helpers/asset_tag_helper.rb:362:in `javascript_include_tag'

I think I missed something by creating an ActionView :: Base.

, ? :)

0
2

, MVC .:( .

:

Model

class Widget < ActiveRecord::Base
  def name
    "weather_widget"
  end

  def settings
    ## something here
  end

  def data
    ## calculations here
  end
end

module WidgetHelper

  def render_widget(widget)
    render(:partial => "widgets/_#{widget.name}", :locals => {:data => widget.data, :settings => widget.settings})
  end

end

<% @template.widgets.each do |widget| %>
  <%= render_widget(widget) %>    
<% end %>

, , , -, , .:)

-1

, Rails . Rails , .

. app/helpers,

module WidgetHelper
  class WidgetPresenter < Struct.new(:widget)
    def show_me
      render(:partial => "widgets/#{widget.class}/show", :locals => {:widget => widget })
    end
  end

  def show_widgets(template)
    @template.widgets.map do |widget|
        WidgetPresenter.new(widget).show_me
    end.join
  end
end

, OO , Rails ( ), .

+3

All Articles