ActionController :: Base.helpers.image_url doesn't generate hashed version in initializer

I got a constants.rb file in config / initializers with the following content:

DEFAULT_IMAGES  = {
  profile: ActionController::Base.helpers.image_url('v2/default_profilepic.jpg'),
  banner: ActionController::Base.helpers.image_url('v2/profile-banner.jpg'),
  missing: ActionController::Base.helpers.image_url('v2/missing.png'),
}

      

When I try to call DEFAULT_IMAGES somewhere in the code or even in the console, I get images without a hash. Is this what he should be doing and am I wrong in my expectations?

DEFAULT_IMAGES => {: profile => " http: // localhost: 3000 / assets / v2 / default_profilepic.jpg " ,: banner => " http: // localhost: 3000 / assets / v2 / profile-banner.jpg ", : missing => " http: // localhost: 3000 / assets / v2 / missing.png "}

I would expect something like this: "/assets/v2/missing-d38d4bdbf9f2cf313e346a844de298c0.png"

+3


source to share


4 answers


You can also try Proc try



proc { ActionController::Base.helpers.image_path('v2/missing.png') }.call

      

+1


source


Place your code in an after_initialize block in your specific environment file or application.rb:

config.after_initialize do
  DEFAULT_IMAGES  = {
    profile: ActionController::Base.helpers.image_url('v2/default_profilepic.jpg'),
    banner: ActionController::Base.helpers.image_url('v2/profile-banner.jpg'),
    missing: ActionController::Base.helpers.image_url('v2/missing.png'),
  }
end

      



The downside is that you will need to refer to your constant through your application's namespace:

Foo::Application::DEFAULT_IMAGES

      

+1


source


config.asset_host = 'http://localhost:3000'

      

Add this line to application.rb and check your rails console.

0


source


Here is the fix

DEFAULT_IMAGES  = {
  profile: ActionController::Base.helpers.image_path('v2/default_profilepic.jpg'),
  banner: ActionController::Base.helpers.image_path('v2/profile-banner.jpg'),
  missing: ActionController::Base.helpers.image_path('v2/missing.png'),
}

      

You need to use *_path

, not *_url

according to your expected data.

image_path

: calculates the path to the image resource.

0


source







All Articles