如何在Rails引擎中创建关注点?



我试图在引擎内部创建一个关注,以便在主应用程序中添加/覆盖此功能,该应用程序将安装此引擎。问题是,我有问题,包括在发动机模块的关注。似乎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/关注"

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

当我运行测试/dummy时,我得到了这个错误:未初始化的常量Blorgh::关注点

这是我的博客。

$:.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
有人能帮我一下吗?

当使用引擎时,你需要跟踪加载顺序,特别是当改变主应用程序的行为时。假设你的引擎名为"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来重新考虑使用依赖注入来处理不同的配置。

之所以会发生这种情况,是因为在Rails 3中,lib目录不会自动查找类。您可以更新配置。Autoload_paths将lib目录添加到引擎中,或者您可以移动关注点/模型/post。

把它从lib目录中取出来,放到app/models中,在那里它会被自动找到。

相关内容

  • 没有找到相关文章

最新更新