简体   繁体   English

从引擎扩展rails类

[英]Extending rails classes from engines

I'm playing around with creating a simple plugin system for my app. 我正在为我的应用创建一个简单的插件系统。 Currently, i wan't to be able to extend my activerecord models from inside the engine files. 目前,我将无法从引擎文件内部扩展我的activerecord模型。

Let's say i have a following model: 假设我有以下模型:

# /my_app/app/models/post.rb
class Post < ActiveRecord::Base
end

What i want to achieve is to be able to put a file, for example, /my_app/example_engine/app/example_engine/models/post.rb which will add some methods to my Post class. 我想要实现的是能够放入一个文件,例如/my_app/example_engine/app/example_engine/models/post.rb ,这将向Post类添加一些方法。 I was trying to make that by putting a following content to that file: 我试图通过在文件中添加以下内容来做到这一点:

# /my_app/example_engine/app/example_engine/models/post.rb
Post.class_eval do
  def new_method
    "hello"
  end
end

But it seems that it's not a proper way of doing this cause it's not working. 但这似乎不是执行此操作的正确方法,因为它无法正常工作。 I probably lack some elementary knowledge about ruby classes or how rails works so i would be really thankful if anyone could help me with that. 我可能缺乏有关红宝石类或Rails如何工作的基本知识,因此,如果有人可以帮助我,我将非常感激。

Thanks in advance! 提前致谢!

If you are ok with subclassing, I would recommend doing the following 如果您可以接受子类化,建议您执行以下操作

Have your engine extend the base class under a namespace such as 让您的引擎在诸如以下的名称空间下扩展基类

    module MyEngine
      class Post < Post
        .....
      end
    end

No need to eval, just inherit from the base class and extend it as you need. 无需评估,只需继承基类并根据需要扩展它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM