Ответ 1
ActionController::Base.helpers.asset_path('missing_file.jpg')
Чтобы получить путь изображения в контроллере, я использую следующий метод:
class AssetsController < ApplicationController
def download(image_file_name)
path = Rails.root.join("public", "images", image_file_name).to_s
send_file(path, ...)
end
end
Есть ли лучший способ найти путь?
ActionController::Base.helpers.asset_path('missing_file.jpg')
Не уверен, что это было добавлено уже в Rails 3, но определенно работает в Rails 3.1. Теперь вы можете получить доступ к view_context
с вашего контроллера, что позволяет вам вызывать методы, которые обычно доступны для ваших просмотров:
class AssetsController < ApplicationController
def download(image_file_name)
path = view_context.image_path(image_file_name)
# ... use path here ...
end
end
Обратите внимание, что это даст вам общедоступный путь (например: "/assets/foobar.gif" ), а не путь к локальной файловой системе.
view_context.image_path('noimage.jpg')
URL-адрес актива:
ActionController::Base.helpers.asset_path(my_path)
URL-адрес изображения:
ActionController::Base.helpers.image_path(my_path)
view_context
работает для меня в Rails 4.2 и Rails 5.
Найти коды в Rails repo объясняет view_context
:
# definition
module ActionView
# ...
module Rendering
# ...
def view_context
view_context_class.new(view_renderer, view_assigns, self)
end
end
end
# called in controller module
module ActionController
# ...
module Helpers
# Provides a proxy to access helper methods from outside the view.
def helpers
@_helper_proxy ||= view_context
end
end
end
Вы можете проверить image_path(image.png)
для своего сценария.
Вот примеры из :
image_path("edit") # => "/images/edit"
image_path("edit.png") # => "/images/edit.png"
image_path("icons/edit.png") # => "/images/icons/edit.png"
image_path("/icons/edit.png") # => "/icons/edit.png"
image_path("http://www.example.com/img/edit.png") # => "http://www.example.com/img/edit.png"