【问题标题】:How to create a rails 4 offline webapp?如何创建一个 rails 4 离线 webapp?
【发布时间】:2014-08-25 23:55:55
【问题描述】:

我正在尝试使用 Rails 4 创建一个应用程序,该应用程序应该可以在没有互联网连接的情况下使用。 我听说过 html5 应用程序缓存和 rack-offline gem,这是我采用的方法。 现在,它似乎无法在 Rails 4 上正常工作,因为 /application.manifest 只显示:

CACHE MANIFEST
# dd1ba6bba9339ef83f9c1225c70289dd6326d3caae01b0d52b502381030dc78f

404.html
422.html
500.html

NETWORK:
*

另外,我正在使用资产预编译,因此 application.js、application.css 和图像文件的名称中有指纹,例如 application-e8cc2fba8275c884c.js。

【问题讨论】:

    标签: html ruby-on-rails-4 application-cache


    【解决方案1】:

    我在 generate_appcahe_manifest.rake 文件中制作了自己的解决方案,并将其放入 /lib/tasks 文件夹中。

    task :generate_appcache_file => ['deploy:precompile_assets', 'html5_manifest']
    
    desc "Create html5 manifest.appcache"
    task :html5_manifest => :environment do
      puts 'Creating appcache manifest file...'
    
      File.open("public/manifest.appcache", "w") do |f|
        f.write("CACHE MANIFEST\n")
        f.write("# Version #{Time.now.to_i}\n\n")
        f.write("CACHE:\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
            # f.write("assets/#{File.basename(asset)}\n")
            f.write(filename_path.concat("\n"))
          end
        end
        f.write("\nNETWORK:\n")
        f.write("*\n")
        f.write("http://*\n")
        f.write("https://*\n")
      end
      puts 'Done.'
    end
    
    namespace :deploy do
      task :precompile_assets do
        require 'fileutils'
        if File.directory?("#{Rails.root.to_s}/public/assets")
          FileUtils.rm_r "#{Rails.root.to_s}/public/assets"
        end
    
        puts 'Precompiling assets...'
        puts `RAILS_ENV=production bundle exec rake assets:precompile`
        puts 'Done.'
      end
    end
    

    所以当我在终端上运行 rake generate_appcache_file 时,我得到了一个 /public/manifest.appcache 文件,其中包含如下编译的资产:

    CACHE MANIFEST
    # Version 1409045103
    
    CACHE:
    
    assets/app/backgrounds/strips-05561384267a3286ab382c852f1e8b0d.jpg
    assets/app/backgrounds/team-12e0fc5f670794c4eba3db117fba6746.jpg
    assets/app-a7de6b02d1d39b783fe4e7ab7906ec95.css
    assets/app-ae958853aa13f9011e35121cbe5b3cfe.js
    
    NETWORK:
    *
    http://*
    https://*
    

    最后,我在我的 /app/views/layouts/app.html.erb 文件中调用该文件:

    <!DOCTYPE html>
    <html lang="en" manifest="/manifest.appcache">
    

    有关离线应用程序缓存的更多信息,可以找到对我有很大帮助的here

    【讨论】:

    • 你还在使用这个解决方案吗?你知道它是否适用于 Rails 5?
    • @Marklar 不必在 Rails 5 中使用它。但我认为它仍然可以工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 2014-01-17
    • 2011-05-18
    相关资源
    最近更新 更多