我试图在引擎内部创建一个关注点,以便在将要挂载此引擎的主应用程序中添加/覆盖此函数。问题是我遇到了一些问题,包括引擎模块中的问题。似乎Rails找不到它。
这是我在app/models/blorgh/post.rb中的post.rb文件:
module Blorgh
class Post < ActiveRecord::Base
include Blorgh::Concerns::Models::Post
end
end这是我在lib/concerns/models/post.rb中的post.rb关注点
需要'active_support/concern‘
module Concerns::Models::Post
extend ActiveSupport::Concern
# 'included do' causes the included code to be evaluated in the
# conext where it is included (post.rb), rather than be
# executed in the module's context (blorgh/concerns/models/post).
included do
attr_accessible :author_name, :title, :text
attr_accessor :author_name
belongs_to :author, class_name: Blorgh.user_class
has_many :comments
before_save :set_author
private
def set_author
self.author = User.find_or_create_by_name(author_name)
end
end
def summary
"#{title}"
end
module ClassMethods
def some_class_method
'some class method string'
end
end
end当我运行test/dummy时,我得到了this error: uninitialized常量Blorgh::Concerns
这是我的blorgh.gemspec:
$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "blorgh/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "blorgh"
s.version = Blorgh::VERSION
s.authors = ["***"]
s.email = ["***"]
s.homepage = "***"
s.summary = "Engine test."
s.description = "Description of Blorgh."
s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"]
s.test_files = Dir["test/**/*"]
s.add_dependency "rails", "~> 3.2.8"
s.add_dependency "jquery-rails"
s.add_development_dependency "sqlite3"
end有人能帮我一下吗?
发布于 2014-08-10 07:57:04
在使用引擎时,您需要跟踪加载顺序,尤其是在更改主应用程序的行为时。假设你的引擎名为"engine_name",你应该有这个文件:engine_name/lib/engine_name/engine.rb.这是一个包含您所关心的问题的地方。
Bundler.require
module EngineName
class Engine < ::Rails::Engine
require 'engine_name/path/to/concerns/models/post'
initializer 'engine_name.include_concerns' do
ActionDispatch::Reloader.to_prepare do
Blorgh::Post.send(:include, Concerns::Models::Post)
end
end
# Autoload from lib directory
config.autoload_paths << File.expand_path('../../', __FILE__)
isolate_namespace EngineName
end
end通过这种方式,您可以确保一切正常加载,但要非常小心地使用关注点,并可能重新考虑使用依赖注入来重构Blorgh::Post来处理不同的配置。
发布于 2013-04-03 09:22:16
这是因为在Rails3中,没有自动查看lib目录来查找类。您可以在引擎中更新config.autoload_paths以将lib目录添加到其中,或者您可以将concerns/models/post.rb移出lib目录,并将其移到app/models中,在那里将自动找到它。
https://stackoverflow.com/questions/14218223
复制相似问题