使用Gem加载资产(有麻烦不会加载资产)

时间:2016-03-02 04:42:54

标签: ruby-on-rails ruby ruby-on-rails-4 rubygems asset-pipeline

我有一个我经常在我的网站上使用的主题。我一直在尝试通过gem加载css,js和plugin文件夹(包含在主题中)资产。

Sprockets::FileNotFound: couldn't find file 'phcthemes' with type 'application/javascript'

如果我拿出javascript(仅限css),这不会执行,并且在编译资产中显示如下所示

*= phcthemes

我的想法应用程序没有识别宝石,我尝试使用isolate_namespace(暂时注释掉)也使用下面的回答中的信息尝试了几个不同的配置无效。

主应用程序application.css

*= phcthemes

Main App 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

1 个答案:

答案 0 :(得分:2)

您的Engine类中缺少一些代码。 包括以下

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类,因此在主gem模块中包含以下类:

class MyRailtie < Rails::Railtie
end

应该这样做。实际上你根本不需要改变gemspec。

您可以查看我的socket_helpers gem作为示例。当我遇到同样的问题时,这就是我正在构建的内容。