使用 Gem 加载资产(有问题不会加载资产)

Load Assets Using a Gem (Having Troubles Won't Load Assets)

我有一个经常在我的网站上使用的主题。我一直在尝试通过 gem.

加载 css、js 和插件文件夹(包含在主题中)资产
Sprockets::FileNotFound: couldn't find file 'phcthemes' with type 'application/javascript'

如果我取出 javascript(仅限 css)这不会执行,并且在编译的资产中完全像这样显示

*= phcthemes

我的想法应用程序无法识别 gem,我尝试使用 isolate_namespace(现在已注释掉)也尝试了几种不同的配置,使用下面答案中的信息无济于事。

主应用程序 application.css

*= phcthemes

主应用程序application.js

// require phcthemes

lib/phcthemers.rb

require "phcthemes/version"

module Phcthemes
    class MyRailtie < Rails::Railtie
    end

    class Engine < ::Rails::Engine

        # Isolate Namespace
        #isolate_namespace Phcthemes

        # Initialize Assets
        initializer :assets do |config|
            Rails.application.config.assets.precompile += %w{ application.js application.css }
            Rails.application.config.assets.paths << root.join("app", "assets", "javascripts")
            Rails.application.config.assets.paths << root.join("app", "assets", "stylesheets")
        end

    end

end

phcthemes.gemspec

$:.push File.expand_path("../lib", __FILE__)

# Maintain your gem's version:
require "phcthemes/version"

Gem::Specification.new do |spec|

    spec.name        = "phcthemes"
    spec.version     = Phcthemes::VERSION
    spec.authors     = ["BradPotts"]
    spec.email       = ["bradley.j.potts@gmail.com"]
    spec.homepage    = "http://phcnetworks.net"
    spec.summary     = "PHCThemes"
    spec.description = "PHCNetworks theme with mtdevise and assets built in."
    spec.license     = "GPL-3.0"

    spec.files         = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
    spec.bindir        = "exe"
    spec.executables   = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
    spec.require_paths = ["lib"]

    spec.files = Dir["{app,config,db,lib}/**/*", "LICENSE", "Rakefile", "README.md"]

    # Main Structure & Security
    spec.add_dependency "rails", "~> 4.2.5.2"

    # Development & Testing
    spec.add_development_dependency "sqlite3"
    spec.add_development_dependency "bundler", "~> 1.11"
    spec.add_development_dependency "rake", "~> 10.0"
    spec.add_development_dependency "rspec", "~> 3.0"

end

您的引擎 class 中缺少一些代码。 包括以下内容

initializer :assets do |config|
  Rails.application.config.assets.precompile += %w{ myfile.js myfile.css }
  Rails.application.config.assets.paths << root.join("app", "assets", "javascripts")
  Rails.application.config.assets.paths << root.join("app", "assets", "stylesheets")
end

然后将您的文件包含在 gem 目录中的 app/assets/javascripts 或 app/assets/stylesheets 中。如果它对供应商目录或任何其他目录的作用不同,我会感到惊讶。

当 gem 安装到 Rails 应用程序时,您仍然需要在 application.css 和 application.js 中放置 require 语句。顺便说一句,您的 CSS 要求陈述不正确 - 它应该是 *= require phcthemes

Railtie 文档说当 运行 初始值设定项时需要 Railtie class,因此在主 gem 模块中包含以下 class:

class MyRailtie < Rails::Railtie
end

应该可以了。实际上,您根本不必更改 gemspec。

你可以看我的socket_helpersgem举个例子。当我遇到同样的问题时,这就是我正在构建的。