rails-observers cannot be required manually

TL;DR: As it is mentioned in the topic line, install and require it in Gemfile if you use rails (of coz).

I was supposed to use rails-observers gem to audit models' changes on particular case. So I added the gem into Gemfile but not require like this.

# Gemfile
gem 'rails-observers', require: false

# config/initializers/audit.rb
require 'rails-observers' if needed

It gave me an undefined method error but worked fine if omit the require: false part.

vendor/bundle/gems/activerecord-5.0.7/lib/active_record/dynamic_matchers.rb:21:in `method_missing': undefined method `instantiate_observers' for ActiveRecord::Base:Class (NoMethodError)

After digging into the rails-observers's code, it turns out that a few monkey patches will be done when active_record is loaded (https://github.com/rails/rails-observers/blob/v0.1.5/lib/rails/observers/railtie.rb#L6-L12) which happened before all self-defined initializers loaded (https://guides.rubyonrails.org/configuring.html#initializers).

So, as a result, require it at the beginning or let Gemfile do the requirement.

Additional, I found a good discussion on issue to read, if interested: https://github.com/rubygems/rubygems/issues/1104

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容