Last modified: Sat Mar 23 2019 14:49:08 GMT+0800 (Malay Peninsula Standard Time)

Chapter 3. Offline Application Cache

Many of you may have used a Web Application that is able to run even when your device is at offline mode or not connected to the internet. There is an available Gem, rack-offline, that is able to handle the operation. However, I found that the Gem does not work for me. It may be outdated or I integrated it wrongly.

Then, I came across another solution in Stackoverflow forum. The solution of implementing cache to Ruby on Rails Web Application is simple and straightforward. All the code that you seen in this chapter belongs to the owner ErwinGO. This solution may be browser specific and you should read more here.

In Information Security perspective, it is a bad to cache your website as your application may be attacked in the form of main-in-the-middle attack.

3.1 Setup

Assume that you have already have a working Web Application and you wish to add offline cache feature. Follow the instruction in Table 3.1.1 to create a file and add the code to the file.

Table 3.1.1: File to create and code to add


task :generate_appcache_file => ['deploy:precompile_assets', 'html5_manifest']

desc "Create html5 manifest.appcache"
task :html5_manifest => :environment do
  puts 'Creating appcache manifest file...'"public/manifest.appcache", "w") do |f|
    f.write("CACHE MANIFEST\n")
    f.write("# Version #{}\n\n")
    assets = Dir.glob(File.join(Rails.root, 'public/assets/**/*'))
    assets.each do |asset|
      if File.extname(asset) != '.gz' && File.extname(asset) != '' && File.extname(asset) != '.json'
        filename_path = /#{Rails.root.to_s}\/public\/(assets\/.*)/.match(File.absolute_path(asset))[1].to_s
  puts 'Done.'

namespace :deploy do
  task :precompile_assets do
    require 'fileutils'
      FileUtils.rm_r "#{Rails.root.to_s}/public/assets"

    puts 'Precompiling assets...'
    puts `RAILS_ENV=production bundle exec rake assets:precompile`
    puts 'Done.'

Then, we have to run the file that we created above in our terminal. To run the file, use the command below.

rake generate_appcache_file

A file named manifest.appcache will then be created in the folder MyApp/public/.

After that, we have to call the file that we have just created to our application.html.erb.

Table 3.1.2: Code to add


#Code to remove

#Code to add
<html lang="en" manifest="/manifest.appcache">

3.2 Testing and Verification

The testing phase for this feature is very straight forward. Start your Rails server, visit a few pages, and terminate your Rails server. Then, revisit the pages that you have visited and you should be able to visit the page even the server is terminated (for local host) or in offline mode (website hosted in the internet).

results matching ""

    No results matching ""