I'm on Rails 5.2.2 and I'm building a web app that uses some static HTML, CSS, and JavaScript that I'm serving from inside of the public directory. Much of the time when I update a file it doesn't update in my browser when I refresh, but if I go into private browsing it works -- until it caches again and then I need to open a new private window.
How can I turn off caching for file in the public folder? Or if it's easier, how can I turn off all caching during development?
This is what my development.rb looks like. I tried commenting out the entire if Rails.root.join('tmp', 'caching-dev.txt').exist? block but that didn't do anything.
I'm also open to installing a gem to solve this if it can't be fixed with a setting.
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# 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
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
config.file_watcher = ActiveSupport::FileUpdateChecker
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join('tmp', 'caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Store uploaded files on the local file system (see config/storage.yml for options)
config.active_storage.service = :local
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
# Add devide default mailer url
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
It's not rails who caches, it's your browser.
Either you explicitly set
config.public_file_server.headers = {
'Cache-Control' => "no-cache"
}
(and clean your browser cache, who has all old and valid versions of your files), or you disable browser cache completely.
Related
so I'm following this article https://medium.com/#andrea.wayte/using-amazon-s3-to-store-images-for-react-on-rails-b1414ba2c0b2. Whenever I'm at the part where she migrates her database after updating the database I get this error.
admins-MBP:direct-s3-example admin$ rake db:migrate
rake aborted!
NameError: undefined local variable or method `config' for main:Object
/Users/admin/direct-s3-example/config/environments/development.rb:65:in `<main>'
/Users/admin/direct-s3-example/config/environment.rb:5:in `<main>'
Tasks: TOP => db:migrate => db:load_config => environment
(See full trace by running task with --trace)
I don't have an environment.rb file but here's my development.rb file.
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# 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
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join('tmp', 'caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.action_controller.enable_fragment_cache_logging = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations.
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
Paperclip.options[:command_path] = "/usr/bin/"
config.paperclip_defaults = {
storage: :s3,
s3_host_name: 's3-us-east-2.amazonaws.com',
s3_credentials: {
bucket: ENV.fetch('petition-form'),
access_key_id: ENV.fetch('--------'),
secret_access_key: ENV.fetch('--------------'),
s3_region: ENV.fetch('us-east-2'),
}
}
The question has been answered. The code at the bottom was past the last end
The logout feature in my Rails application appears to be working when I run the app locally using localhost:3000; however, when I logout on the production server it is directing me to http://example.com/users/logout and then when I go to http://example.com I am still logged in.
I pushed all my changes up to the git repo and both dev / prod are both running the same source code. I am not sure why the prod box isn't logging the user out when they click the logout link.
development.rb
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# 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
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
production.rb
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# General Settings
config.app_domain = 'example.io'
# Email
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.default_url_options = { host: config.app_domain }
config.action_mailer.smtp_settings = {
address: 'smtp.example.com',
port: '587',
enable_starttls_auto: true,
user_name: 'foo',
password: ':)',
authentication: :plain,
domain: 'example.com'
}
# 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
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# 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
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# 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
# 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 = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# 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
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
The logout behavior appears to be working now. I put //= require jquery_ujs below //= require jquery in the application.js file and now I am able to logout on the prod box. Thanks for the help guys.
I am trying to change my styles of my scss assets on my ruby on rails project but they are applying just after rake assets:precompile and restarting rails server.
With JS files everything allright and they are changing on fly.
Possible problem is with compass gem.
That is my repo - https://github.com/tanotify/blog
And file development.rb
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# 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
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
end
Found solution! In config/environments/development.rb added line:
config.serve_static_assets = false
Hello stackoverflow community,
I am building a Rails application which uses devise for authentication and it works fine on development mode. And when I host the app on Heroku everything works fine but the Checkbox next the question to save the password is missing.
I am using the Metronic Admin Theme which is based on Twitter Bootstrap.
Here is the checkbox which doesn't show up on production mode.
.form-actions
.checkbox
= f.check_box :remember_me
= f.label :remember_me, 'Passwort merken'
This is my production.rb file
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
# Disable Rails's static asset server (Apache or nginx will already do this)
# --> nope, enabled it because we dont have no nginx!
config.serve_static_assets = true
# Compress JavaScripts and CSS
config.assets.compress = true
config.assets.js_compressor = :uglifier
config.assets.css_compressor = :sass
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# change this if you want to expire all your assets
config.assets.version = '1.0'
# Generate digests for assets URLs
config.assets.digest = true
# 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
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = ENV['HTTPS'].to_bool
# Set to :debug to see everything in the log.
config.log_level = :info
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
#Set timezone
config.time_zone = 'Bern'
# google analytics
GA.tracker = ENV['GA_TRACKER']
# mailers
config.action_mailer.delivery_method = :smtp
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_deliveries = true
config.action_mailer.smtp_settings = {
address: ENV['SMPT_HOST'],
port: ENV['SMPT_PORT'].to_i,
domain: ENV['SMPT_DOMAIN'],
user_name: ENV['SMPT_USER'],
password: ENV['SMPT_PASS'],
authentication: :plain,
enable_starttls_auto: true
}
# default host for mailer and controllers
default_url_options = {
host: ENV['HOST_FOR_LINKS'], protocol: config.force_ssl ? 'https://' : 'http://'
}
config.action_mailer.default_url_options = default_url_options
routes.default_url_options = default_url_options
end
and my development.rb file
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# 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
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
config.action_view.raise_on_missing_translations = true
# strong_parameters: raise exception
config.action_controller.action_on_unpermitted_parameters = :raise
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = ENV['HTTPS'].to_bool
# mailcatcher
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = { address: "localhost", port: 1025 }
#Set timezone
config.time_zone = 'Bern'
# default host for mailer and controllers
default_url_options = {
host: ENV['HOST_FOR_LINKS'], protocol: config.force_ssl ? 'https://' : 'http://'
}
config.action_mailer.default_url_options = default_url_options
routes.default_url_options = default_url_options
# Live reload for debugging
if ENV['LIVE_RELOAD'].to_bool
config.middleware.use Rack::LiveReload
end
end
I recently updated my Rails to 3.1.
Here's a part where I added:
<%= asset_path('logo_symbol.png') %>
This renders /assets/logo_symbol.png which works perfectly fine in development environment. However, when i push the code to production on heroku, it shows a broken image, with the url: assets/logo_symbol-135ddc8db2c9b59f032bed7db520137a.png. I am guessing the new name is for the reason of some optimization.
It is however interesting to note that when I go to the assets/logo_symbol-135ddc8db2c9b59f032bed7db520137a.png url on production, I see a blank page, but when I change that url to anything random, like adding numbers to it, it shows a page not found. So clearly it is finding something on that url. It also shows a blank page when I go to /assets/logo_symbol.png directly on production/heroku.
If this is any help, heroku does not precompile successfully when I push the code and heroku's documentation says that there is currently no work around for that issue.
Any help in this will be greatly appreciated.
My guess is that it has something to do with some configuration related to environments. I am attaching contents of my application.rb, development.rb and production.rb files
here are the contents of my production.rb file
# Settings specified here will take precedence over those in config/application.rb
# 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 webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
#config.action_mailer.default_url_options = { :host => 'localhost:3000' }
#config.action_mailer.default_url_options = { :host => 'localhost:3000' }
config.action_mailer.delivery_method = :smtp
# 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
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = true
end
module ActiveAdmin
class Reloader
def attach!
end
end
end
and here are the contents of my development.rb file
# Settings specified here will take precedence over those in config/application.rb
# 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 webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
#config.action_mailer.default_url_options = { :host => 'localhost:3000' }
#config.action_mailer.default_url_options = { :host => 'localhost:3000' }
config.action_mailer.delivery_method = :smtp
# 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
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = true
end
module ActiveAdmin
class Reloader
def attach!
end
end
end
Here are the contents of my production.rb file
# Settings specified here will take precedence over those in config/application.rb
# The production environment is meant for finished, "live" apps.
# 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
# Specifies the header that your server uses for sending files
config.action_dispatch.x_sendfile_header = "X-Sendfile"
# For nginx:
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
# If you have no front-end server that supports something like X-Sendfile,
# just comment this out and Rails will serve the files
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Disable Rails's static asset server
# In production, Apache or nginx will already do this
config.serve_static_assets = false
# Enable serving of images, stylesheets, and javascripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
#config.action_mailer.default_url_options = { :host => 'ha1.heroku.com' }
config.action_mailer.delivery_method = :smtp
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# 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
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
config.assets.js_compressor = :uglifier
config.assets.css_compressor = :scss
I have compared my config files with the rails documentation for 3.1 and seems like I have all the defaults needed. However I am still seeing no image. Any help will be much appreciated
Remove this line from production.rb:
config.action_dispatch.x_sendfile_header = "X-Sendfile"
You should also align the settings in your config files with those in section 9 of the pipeline guides.
Sendfile headers contain information for the upstream webserver of where to find the file (on the file system) to serve it. This removes the load from the backend (Rails/Sprockets). When sendfile is on the HTTP response contains no body (it is zero length) which is why you see nothing.
On heroku the nginx servers do not have access to the application filesystem, so this won't work.
See this note on the Heroku dev site re sendfile.
If you are using heroku, this document outlines the best options for using the pipeline effectively.
You need to do two things to resolve it.
First, change these two lines from false to true in production.rb file.
config.assets.compile = true
config.assets.digest = true
Second, if you've syntax like this for your images
background: url("imgo.jpg")
Change it to
background: image-url("image.jpg")
I hope it does your job.