7

How do you get access to the asset_url or asset_path Sprockets URL helpers inside a Rake task?


I have a Rake task that seeds the database with some models. One of the models has the URL to an asset in the Rails app. How do I create a URL for this asset while inside the Rake task?

SomeModel.create(image: asset_url('awesome.png'))

For now I have a really poor solution to the issue.

path = URI.join(Rails.application.routes.url_helpers.root_url, '/assets/images/awesome.png')
SomeModel.create(image: path.to_s)
Jason
  • 3,736
  • 5
  • 33
  • 40
  • `asset_url` and `asset_path` this helper available only in sass or scss. – Roman Kiselenko Jun 29 '14 at 09:18
  • Why are you using a non-relative path? Why do you need to seed the database with these images? – jaysqrd Jun 29 '14 at 21:14
  • I assume you are trying to get at why I need to do this in this particular case and help me find a better/easier solution. Thank you, although I really have more than 1 need for the asset_url/asset_path helpers in a Rake task. Do you, @jaysqrd, know a way to enable this? – Jason Jun 29 '14 at 22:46
  • I'm wondering if it's worth the time to build something easier. It's possible to access to the `asset_path` via this [module](https://github.com/rails/rails/blob/88ee47d052790eefb28732a196b8243700ee9081/actionview/lib/action_view/helpers/asset_url_helper.rb#L120). You might need to initialize your application to do so (not sure if `rake` will do that by default). The easier thing might be to provide a default the image on your model or just hard code the path in your seeds. Reusing logic like this just isn't worth the work, if its unlikely to change. – jaysqrd Jun 29 '14 at 23:55

3 Answers3

1

I've just tested out on rails 5.0.2

Add this into your rake class or controller class

include ActionView::Helpers::AssetUrlHelper

This will let you use all these methods http://api.rubyonrails.org/classes/ActionView/Helpers/AssetUrlHelper.html

  • 1
    Including this line in a rake task lead to an error when I attempted to deploy with capistrano: `Sprockets::NotImplementedError: Custom asset_path helper is not implemented` – Matthew Zagaja Oct 01 '18 at 00:11
0

You have to include ActionView::Helpers module Then the asset_path and its other helpers will be available.

 include ActionView::Helpers

See Using helpers in model: how do I include helper dependencies?

Community
  • 1
  • 1
dre-hh
  • 7,840
  • 2
  • 33
  • 44
0

In your rake task:

include ActionView::Helpers::AssetUrlHelper
Stefan Huska
  • 547
  • 1
  • 7
  • 13