ActionController::RoutingError (No route matches [GET] "/assets/jquery.blockUI-49c048033e3dfb8cfab8eff7edbdc553.js"):" - ruby-on-rails

When I run my application with nginx and passenger, not even single css or js loading..it show me following error.
cache: [GET /assets/application-403103e41ab40b92f00b841ac9afb23a.js] miss
Started GET "/assets/application-403103e41ab40b92f00b841ac9afb23a.js" for localhost at 2013-10-07 10:48:13 +0530
ActionController::RoutingError (No route matches [GET] "/assets/application-403103e41ab40b92f00b841ac9afb23a.js"):
cache: [GET /assets/jquery.blockUI-49c048033e3dfb8cfab8eff7edbdc553.js] miss
Started GET "/assets/jquery.blockUI-49c048033e3dfb8cfab8eff7edbdc553.js" for localhost at 2013-10-07 10:48:18 +0530
ActionController::RoutingError (No route matches [GET] "/assets/jquery.blockUI-49c048033e3dfb8cfab8eff7edbdc553.js"):
In my config/environments/production.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = true
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
In config/application.rb
config.assets.precompile << Proc.new do |path|
if path =~ /\.(css|js)\z/
full_path = Rails.application.assets.resolve(path).to_path
app_assets_path = Rails.root.join('app', 'assets').to_path
if full_path.starts_with? app_assets_path
puts "including asset: " + full_path
true
else
puts "excluding asset: " + full_path
false
end
else
false
end
end
I have compiled every file separately as it is requirement for my app, my application.css and application.js file dont have any manifest included. This files are blank.
Please help...

Related

Rails 5.2 asset helpers not including fingerprint digests

I am in the process of upgrading our product from rails 4.1 to 5.2. I'm hung up on what appears to be an asset pipeline related issue. When I load the app in our browser, I see the following error in the server log and the app is missing all styling and javascript code that it normally has.
DEPRECATION WARNING: The asset application.js" is not present in the asset pipeline.Falling back to an asset that may be in the public folder.
This behavior is deprecated and will be removed.
To bypass the asset pipeline and preserve this behavior,
use the `skip_pipeline: true` option.
When I wget the index.html of the application, I see that all of the images and javascript urls are lacking the fingerprint digest they should have. Interestingly enough, they do have the S3 asset_host we have, so they are in fact being processed by the helpers.
To demonstrate, I have two servers which have identical configurations, but one is running 4.1 and the other 5.2. On both, I am using S3 as an asset_host and digest is turned on. I've run the following commands in their consoles:
=== Rails 4 ===
Loading qatest environment (Rails 4.1.0)
irb(main):001:0> Rails.application.config.action_controller.asset_host
=> "https://redacted.s3.amazonaws.com"
irb(main):002:0> Rails.application.config.assets.digest
=> true
irb(main):003:0> ActionController::Base.helpers.asset_path('application.js')
=> "https://redacted.s3.amazonaws.com/assets/application-042f2014ca329c79c304ab1332557040d3f7b922247202f40c28acc950f30ef8.js"
=== Rails 5 ===
Loading sean environment (Rails 5.2.1)
irb(main):001:0> Rails.application.config.action_controller.asset_host
=> "https://redacted.s3.amazonaws.com"
irb(main):002:0> Rails.application.config.assets.digest
=> true
irb(main):003:0> ActionController::Base.helpers.asset_path('application.js')
=> "https://redacted.s3.amazonaws.com/application.js
As requested, production.rb
require "#{File.dirname(__FILE__)}/includes/s3_assets"
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb
config.eager_load = true
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = false
config.log_level = ENV['SHOW_SQL'] != 'false' ? :debug : :info
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
user_name: Rubber.config.email_username,
password: Rubber.config.email_password,
address: Rubber.config.email_server,
port: Rubber.config.email_port,
enable_starttls_auto: true, # detects and uses STARTTLS
authentication: 'login' # Mandrill supports 'plain' or 'login'
}
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Raise exception on mass assignment protection for Active Record models
# config.active_record.mass_assignment_sanitizer = :strict
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fall back to assets pipelin if a precompiled asset is
# missed.
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
config.assets.enabled = true
# Nginx will serve as an asset proxy to s3, where assets are
# stored.
config.serve_static_assets = false
# instead of bundling the assets, include multiple css style includes
config.assets.debug = true
config.assets.logger = false
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# NB: The exclusion of any protocol in the asset host declaration above will allow browsers to choose the transport mechanism on the fly.
# So if your application is available under both HTTP and HTTPS the assets will be served to match.
configure_s3_assets config
config.action_controller.asset_host = "https://#{Rubber.config.s3_assets_bucket}.s3.amazonaws.com"
config.action_mailer.default_url_options = { :host => Rubber.config.external_host }
config.sequel.search_path = %w(public audit)
end
config/initializers/assets.rb
# Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'
# Add additional assets to the asset load path
# Rails.application.config.assets.paths << Emoji.images_path
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# Rails.application.config.assets.precompile += %w( search.js )
Rails.application.config.assets.precompile += %w( *.js *.png *.eot *.woff *.ttf *.svg *.gif)
config/environments/includes/s3_assets.rb
def configure_s3_assets(config)
# Do not compress assets
config.assets.compress = false
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Generate digests for assets URLs
config.assets.digest = true
config.assets.enabled = true
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
config.assets.precompile += %w(
)
# find javascripts/ stylesheets/ -type f | sed 's/\.scss//' | sed 's/\.coffee//' |
# sed 's/^.*\/\///'| sort
# defaults to application.js, application.css
# application.css has home.css ?
config.assets.precompile += %w(
handlebars.js
jquery-1.7.js
json2.js
)
end
After digging around in the sprockets code, I discovered that my list of resolvers was empty. I'm not sure what was missing from my configuration, but I fixed the problem by adding the following to config/application.rb
config.assets.resolve_with = [:manifest] // in production
config.assets.resolve_with = [:manifest, :environment] // in development

Rails - Asset is not present in asset pipeline when using image_tag

Goal: Using my rails app with static images in assets in production environemt
Steps:
I turned my rails app to production environment.
Precompiled the assets with RAILS_ENV=production rails assets:precompile
Set RAILS_SERVE_STATIC_FILES environemt variable to true to enable public file server (in production.rb - config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
Added line config.serve_static_assets = true to
/config/application.rb
With this setup, I`ve started the server.
I have a few static images in /app/assets/images/ which precompiled versions with fingerprint filename are now in /public/assets. Examples:
aussen-d2fb0029a12281121a1752c599e715a8e2b3db17f1e8e18248a79a7b1ca63b91.jpg
hintergrund-ca80e1ae5a697c86898f3a7e107694a76dc12e54320b8ac80c58eecbffe0414a.png
So far so great.
When I use background-image: url(<%= asset_path('hintergrund') %>); in application.css.erb it successfully loads the precompiled background-image from /public/assets.
Problem: I can't access the precompiled images with my image_tags in the views! Example:
<%= image_tag("aussen") %>
Error Logs:
I, [2018-03-23T00:46:29.133381 #9289] INFO -- : [f36ff000-6261-4c2c-bfcc-4a2f80cae682] Started GET "/" for 46.142.136.81 at 2018-03-23 00:46:29 +0100
I, [2018-03-23T00:46:29.134466 #9289] INFO -- : [f36ff000-6261-4c2c-bfcc-4a2f80cae682] Processing by HomeController#index as HTML
I, [2018-03-23T00:46:29.136604 #9289] INFO -- : [f36ff000-6261-4c2c-bfcc-4a2f80cae682] Rendering home/index.html.erb within layouts/application
I, [2018-03-23T00:46:29.138267 #9289] INFO -- : [f36ff000-6261-4c2c-bfcc-4a2f80cae682] Rendered home/index.html.erb within layouts/application (1.5ms)
I, [2018-03-23T00:46:29.138482 #9289] INFO -- : [f36ff000-6261-4c2c-bfcc-4a2f80cae682] Completed 500 Internal Server Error in 4ms
F, [2018-03-23T00:46:29.139546 #9289] FATAL -- : [f36ff000-6261-4c2c-bfcc-4a2f80cae682]
F, [2018-03-23T00:46:29.139635 #9289] FATAL -- : [f36ff000-6261-4c2c-bfcc-4a2f80cae682] ActionView::Template::Error (The asset "aussen" is not present in the asset pipeline.):
F, [2018-03-23T00:46:29.139798 #9289] FATAL -- : [f36ff000-6261-4c2c-bfcc-4a2f80cae682] 1: <%= image_tag("aussen", id: "home-img", alt: "Aussenansicht von Simson-Seelig") %>
[f36ff000-6261-4c2c-bfcc-4a2f80cae682] 2: <div id="home" class="content">
[f36ff000-6261-4c2c-bfcc-4a2f80cae682] 3: <p>Alles für Simson von Simson-Seelig.</p>
[f36ff000-6261-4c2c-bfcc-4a2f80cae682] 4: <p>Für die legendären Schwalben und alle anderen SIMSON-Modelle bieten wir Ersatzteile und Service. </p>
F, [2018-03-23T00:46:29.139867 #9289] FATAL -- : [f36ff000-6261-4c2c-bfcc-4a2f80cae682]
F, [2018-03-23T00:46:29.139930 #9289] FATAL -- : [f36ff000-6261-4c2c-bfcc-4a2f80cae682] app/views/home/index.html.erb:1:in `_app_views_home_index_html_erb__177499641769
After hours of researching, I still don't get why I can access the precompiled image in the stylesheet, but not in the view with the image_tag.
Additional information:
$ ruby --version
ruby 2.4.3p205 (2017-12-14 revision 61247) [x86_64-linux]
$ rails --version
Rails 5.1.4
/config/application.rb:
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module SimsonSeelig
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Enable rails to serve my assets
config.serve_static_assets = true
end
end
production.rb:
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Attempt to read encrypted secrets from `config/secrets.yml.enc`.
# Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or
# `config/secrets.yml.key`.
config.read_encrypted_secrets = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "simson-seelig_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
/config/initializers/assets.rb:
# Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'
# Add additional assets to the asset load path.
# Rails.application.config.assets.paths << Emoji.images_path
# Add Yarn node_modules folder to the asset load path.
Rails.application.config.assets.paths << Rails.root.join('node_modules')
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in the app/assets
# folder are already added.
# Rails.application.config.assets.precompile += %w( admin.js admin.css )
The asset "aussen" is not present in the asset pipeline.
Technically true because you have not aussen but you have aussen.jpg so it will be <%= image_tag("aussen.jpg") %>
Look, while you use <%= image_tag("aussen") %> then it will be genarate HTML like this
<%= image_tag("aussen") %>
#=> <img alt="Aussen" src="/assets/aussen" />
While you use <%= image_tag("aussen.jpg") %> then it will be genarate HTML like this
<%= image_tag("aussen.jpg") %>
#=> <img alt="Aussen" src="/assets/aussen.jpg" />
When it's going into production mode then it will be shown some encrypted key on the page source like this
aussen-d2fb0029a12281121a1752c599e715a8e2b3db17f1e8e18248a79a7b1ca63b91.jpg
image_tag AssetTagHelper see this for reference.
Update production.rb file config.assets.compile false to true
# config/environments/production.rb
...
config.assets.compile = true
...
Not sure if you want to set config.assets.compile = true in production, this will slow down your server
config.assets.compile=true in Rails production, why not?
Instead of explicitly setting config.assets.compile = false. Comment it out that worked for me, this is probably a bug. After commenting this out images were correctly rendered using the precompiled asset pipeline.
# config.assets.compile = false
This is the answer when none of the above work.
Are you referencing a .jpeg file? .jpeg files get compiled to .jpg files and so if you reference .jpeg you will get this error.
The solution is to rename the file to .jpg and reference the image_tag with the corresponding .jpg extension.
I had this same issue when working on a Rails 6 application in Ubuntu 20.04.
The issue for me was that I had not precompiled the assets in production.
Here's how I fixed it:
First, I ran the command below to precompile the assets and make them available in the public directory of my application:
rails assets:precompile RAILS_ENV=production
Note: In development this can be accomplished using webpacker with the command: /bin/webpack-dev-server
Next, set up Nginx or Apache web server to serve the static files that are available in the public directory of my application. For me I set up Nginx with the configuration below using Let's Encrypt for SSL:
upstream railsserver {
server 127.0.0.1:3000;
}
server {
# Replace 'localhost' with your FQDN if you want to use
# your app from remote or if you need to add a certificate
server_name my-website.com www.my-website.com;
root /home/deploy/my-website/public;
# Define where Nginx should write its logs
access_log /var/log/nginx/my-website/access.log;
error_log /var/log/nginx/my-website/error.log;
location / {
# First attempt to serve request as file, then
# the rails application directory
try_files $uri #railsserver;
}
location ~ ^/(assets/|robots.txt|humans.txt|favicon.ico) {
expires max;
}
location #railsserver {
proxy_set_header Host $http_host;
proxy_set_header CLIENT_IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 300;
proxy_pass http://railsserver;
gzip on;
gzip_types text/plain text/xml text/css image/svg+xml application/javas$
gzip_proxied any;
}
listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/my-website.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/my-website.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
That's all.
I hope this helps
Can refer this one if the link is ambiguous:
image_tag '#', skip_pipeline: true
It can also happen if your images are in the wrong place. For rails 6, place images inside /app/assets/images/, then simply
<%= image_tag("logo1.png", alt: "My logo", size: '200x75') %>
If it happens when using video_tag with ActiveStorage, this should work:
<%= video_tag url_for(#banner_video.file), size: "150x120", controls: true %>

Rails 4.0.13 assets url missing prefix and digest

I've started working on a rails 4.0.13 app and we're trying to move the assets to a CDN
the problem appears on our staging server , the generated url are missing the prefix and digest
Ex:
https://xxyyzz.blob.core.windows.net/stylesheets/application.css
on my local machine using the same environment as on the staging server everything works fine
Ex:https://xxyyzz.blob.core.windows.net/c532aef6b12d99b3ce3f05b4fc17c02d8a682b13/application-dd1ee03f18e6ee4df65b6a21d8cfcdeb.css
config/environments/dev_1.rb :
...
config.cache_classes = true
config.eager_load = true
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.serve_static_assets = false
config.assets.compile = false
config.assets.digest = true
config.assets.debug = false
config.assets.version = '1.0'
config.log_level = :info
config.i18n.fallbacks = true
config.active_support.deprecation = :notify
config.log_tags = [CustomTagger::USER_TOKEN_LAMBDA, CustomTagger::PROCESS_PID]
config.cache_store = :redis_store, RedisStores.new.url(db: 3), { expires_in: 1.day, driver: :hiredis }
config/application.rb :
...
config.assets.enabled = true
config.assets.precompile = Proc.new do |filename, path|
case
# JS
when /application-.+\.js/ =~ filename then true
when filename == 'vendor.js' then true
# CSS
when filename.end_with?('master-default.css') then true
when filename == 'application.css' then true
# IMG
when /assets\/images\// =~ path then true
# Exclude everything else.
else false
end
end
config.asset_host = 'https://xxyyzz.blob.core.windows.net'
# Each environment must have a different asset path (the SHA1 digest of
# Rails.env + Rails.application.revision).
#
# See http://guides.rubyonrails.org/configuring.html#rails-general-configuration.
# See https://github.com/rails/sprockets-rails/blob/master/lib/sprockets/railtie.rb#L174-L186
config.after_initialize do
ActiveSupport.on_load(:action_view) do
self.assets_prefix = Digest::SHA1.hexdigest(Rails.env + Rails.application.revision)
end unless Rails.env.development?
end
config.autoload_paths += %W(#{config.root}/lib)
config.middleware.insert_before Rack::Sendfile, 'HttpMethodNotAllowed'
Has anyone else encounter this ?
Found out what the problem was https://github.com/rails/rails/issues/15873
It seems rails checks if the file is present in public/assets and if it's not it doesn't set the prefix & digest .
similar issue : https://serverfault.com/questions/638905/does-rails-4-asset-path-helper-uses-asset-prefix
A possible solution would be keeping the manifest.json file in the repo
or adding a deploy task that precompiles only the manifest file .
https://github.com/rails/sprockets-rails/issues/107

turbo-sprockets-rails3 not supporting deploy rollbacks properly

Turbo sprockets seems to fail for the following case:
Make some changes in existing css file in a branch.
Run assets:precompile rake task.
The css file will be compiled by this gem.
Now checkout/rollback to old commit after which css file was modified.
Running precompile rake task will not compile the css file and it still contains the changes done to the css file in the later commit.
Expected Result: The css file should be compiled again as it has been restored to previous state.
EDIT:
Relevant code from application.rb
#for PDF
config.middleware.use PDFKit::Middleware, :print_media_type => true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.middleware.use I18n::JS::Middleware
config.sass.preferred_syntax = :sass
config.generators.stylesheet_engine = :sass
config.generators.template_engine = :slim
config.cache_store = :file_store, "tmp/cache" # specifying the cache store to file_store with the default tmp/cache dir
## Append path to the end of routes file to catch routing errors specifically.
config.after_initialize do |app|
app.routes.append{ match '*a', :to => 'application#error_404' } unless config.consider_all_requests_local
end
from environments/production.rb :
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = true
# Generate digests for assets URLs
config.assets.digest = true
Change the following files:
environments/production.rb:
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
application.rb
# Enable the asset pipeline
config.assets.enabled = false

Rails 3.2 asset_host setting ignored

My production environment -
# Code is not reloaded between requests
config.cache_classes = true
config.assets.enabled = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = true
config.static_cache_control = "public, max-age=31536000"
# Compress JavaScripts and CSS
config.assets.compress = true
config.assets.js_compressor = :uglifier
#config.assets.css_compressor = :yui
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = true
# Generate digests for assets URLs
config.assets.digest = true
# See everything in the log (default is :info)
config.log_level = :warn
config.log_tags = [:remote_ip, lambda { |req| Time.now }]
# Enable serving of images, stylesheets, and JavaScripts from an asset server
ActionController::Base.asset_host = Proc.new { |source|
unless source.starts_with?('/stylesheets' || '/javascripts')
"//dddd.cloudfront.net/"
end
}
However, when I using image_tag it still returns me '/assets..' relative url and not absolute url to the asset host.
irb(main):034:0> helper.image_tag('noimage.gif')
=> "<img alt=\"Noimage\" src=\"/assets/noimage.gif\" />"
irb(main):035:0> helper.image_path('noimage.gif')
I can not seem to figure what might be missing. I even tried doing simple config.asset_host setting, and still it does not recognize the setting.
Have you tried setting the designated config?
config.action_controller.asset_host = 'https://abcd.cloudfront.net'
Not sure it works with protocol relative urls. I simply use https in my apps.
It might also be worth noting that action mailer has a similar setting:
config.action_mailer.asset_host = 'https://abcd.cloudfront.net'
There's something odd in Rails configuration. According to the documentation asset_host is supposed to hold just the host part ('yoursite.com'). I resolved with an helper:
module EmailsHelper
def email_image_tag(src)
protocol = ActionMailer::Base.default_url_options[:protocol] || 'http'
image_tag asset_path(src, protocol: protocol)
end
end
Configure it in your mailer:
class EmailNotificationsMailer < ActionMailer::Base
add_template_helper(EmailsHelper)
...
end
There's no way to force image_tag to use a URL other than to pass a URL to it.

Resources