Chris Lewis
Chris Lewis

Reputation: 1325

Rails ActionView::Helpers not resolving asset path correctly

I've got a small ruby module/class similar to this:

module MyModule
  class MyClass

    include ActionView::Helpers::TagHelper
    include ActionView::Context
    include ActionView::Helpers::AssetUrlHelper 

    def test 
      puts "asset_url:  #{asset_url('poster.jpg')}"
      puts "asset_path: #{asset_path('poster.jpg')}"
    end
  end
end

and when I create a new instance of the class in a controller and then call the test method the result is:

asset_url:  /poster.jpg
asset_path: /poster.jpg

Which is not what I want/expect/hoped for!

But if I do this in a view:

= "asset_url:  #{asset_url('poster.jpg')}"
= "asset_path: #{asset_path('poster.jpg')}"

the result is:

asset_url:  http://localhost:3000/assets/poster.jpg 
asset_path: /assets/poster.jpg

Which is exactly what I want! So why does it give a different result in a module? And how can I get that correct asset path in my module? Thanks.

Upvotes: 1

Views: 516

Answers (1)

AlkH
AlkH

Reputation: 321

If you want to use methods from views and helpers in controllers you can use view_context. For example:

class MyController < ApplicationController

  def index
    logger.debug view_context.asset_url('poster.jpg')
    logger.debug view_context.asset_path('poster.jpg')
  end
end

view_context is just object (OK, this is object of Class :)), then you can pass it to any place you need (from controller).

module MyModule
  class MyClass

    def initialize(view_context)
      @view_context = view_context
    end

    def test 
      puts "asset_url:  #{@view_context.asset_url('poster.jpg')}"
      puts "asset_path: #{@view_context.asset_path('poster.jpg')}"
    end
  end
end

Or delegate methods to this object (Ruby feature):

module MyModule
  class MyClass
    delegate :asset_url, :asset_path, to: :@view_context

    def initialize(view_context)
      @view_context = view_context
    end

    def test 
      puts "asset_url:  #{asset_url('poster.jpg')}"
      puts "asset_path: #{asset_path('poster.jpg')}"
    end
  end
end

Upvotes: 1

Related Questions