Re-open an ActiveRecord model that's provided by a gem

后端 未结 6 1948
旧时难觅i
旧时难觅i 2021-02-10 05:53

I\'m trying to extend an ActiveRecord model (Vote) that a gem (https://github.com/peteonrails/vote_fu) provides to my application. (I.e., there is no vote.rb<

6条回答
  •  青春惊慌失措
    2021-02-10 06:44

    Adrien Coquio has the right idea with ActiveSupport::Concerns, which are the Rails way to extend models. His code will work, and you should use it.

    However this will not work all the time in development because when Rails reloads your classes when a file changes, it will not re-evaulate the #send line. The only solution I could find was attaching to an ActionDispatch callback in production to ensure the file is re-required after every page load:

    if Rails.env.development?
      ActionDispatch::Callbacks.to_prepare do
        require_dependency "../../lib/vote_fu_extensions"
      end
    end
    

    In production, or if you set cache_classes to true in your config, you won't need to do this.

    • A source
    • RoR guides about configuration
    • This suggests it has been deprecated and you should use ActionDispatch::Reloader callbacks instead? Haven't tried yet.

提交回复
热议问题