简体   繁体   中英

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.

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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