How to extend the Object class in Rails?

I would like to add the nil_or_empty? method nil_or_empty? to all classes, so I define

 module ObjectExtensions def nil_or_empty? return self.nil? || (self.respond_to?('empty?') && self.empty?) end end ::Object.class_eval { include ::ObjectExtensions } 

It works fine in a simple Ruby script

 p nil.nil_or_empty? #=> true p ''.nil_or_empty? #=> true p [].nil_or_empty? #=> true p 0.nil_or_empty? #=> false 

However, when I add it to the lib/extensions.rb library file in a Rails 3 application, it does not seem to be added

 NoMethodError (undefined method `nil_or_empty?' for nil:NilClass): app/controllers/application_controller.rb:111:in `before_filter_test' 

I load the library file (all other extensions from this file work fine) and

 # config/application.rb # ... config.autoload_paths << './lib' 

Where am I mistaken?

+6
source share
2 answers

Clear it first to just open the Object class directly:

 class Object def nil_or_empty? nil? || respond_to?(:empty?) && empty? # or even shorter: nil? || try(:empty?) end end 

Secondly, pointing Rails to autoload / lib does not mean that the files in / lib will load when your application starts - it means that when using a constant that is not currently defined, Rails will look for a file in / lib that matches this constant. For example, if you referenced ObjectExtensions in the Rails application code, and it has not yet been defined somewhere, Rails would expect to find it in lib / object_extensions.rb.

Since you cannot extend the main class in / lib like this, it is better to put the main extensions in the config / initializers directory. Rails will download all the files there automatically when your application loads. So try putting the specified Object extension in config / initializers / object_extension.rb or config / initializers / extensions / object.rb or something similar, and everything should work fine.

+16
source

In this particular case, can you just use the provided Rails Object#blank? . For the opposite exists Object#present? .

#blank? similar to your method, but also thinks lines without spaces, such as " " , are empty.

+7
source

Source: https://habr.com/ru/post/887043/


All Articles