gpt4 book ai didi

ruby-on-rails-3 - 如何在 Rails 引擎中创建关注点?

转载 作者:行者123 更新时间:2023-12-03 23:36:39 24 4
gpt4 key购买 nike

我正在尝试在引擎内部创建一个关注点,以便在将安装此引擎的主应用程序中添加/覆盖此功能。问题是我遇到了问题,包括引擎模块中的问题。 Rails 似乎找不到它。

这是我的post.rb文件在 app/models/blorgh/post.rb :

module Blorgh
class Post < ActiveRecord::Base
include Blorgh::Concerns::Models::Post
end
end

这是我的 post.rb关注 lib/concerns/models/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

当我运行测试/虚拟对象时,我得到了这个错误:未初始化的常量 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

有人可以帮我弄这个吗?

最佳答案

使用引擎时,您需要跟踪加载顺序,尤其是在更改主应用程序的行为时。假设你的引擎叫做“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

这样可以确保所有内容都正常加载,但在使用 Concerns 时要非常小心,并且可能通过重构 Blorgh::Post 来重新考虑使用依赖注入(inject)来处理不同的配置。

关于ruby-on-rails-3 - 如何在 Rails 引擎中创建关注点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14218223/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com