ruby - How to extend class Object in Rails? -
i add method nil_or_empty?
classes, therefore 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 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 add library file lib/extensions.rb
in rails 3 app, seems not added
nomethoderror (undefined method `nil_or_empty?' nil:nilclass): app/controllers/application_controller.rb:111:in `before_filter_test'
i load library file (all other extensions file working fine) and
# config/application.rb # ... config.autoload_paths << './lib'
where wrong?
first, it's cleaner reopen object class directly:
class object def nil_or_empty? nil? || respond_to?(:empty?) && empty? # or shorter: nil? || try(:empty?) end end
second, telling rails autoload /lib doesn't mean files in /lib loaded when app starts - means when use constant that's not defined, rails file in /lib corresponding constant. example, if referred objectextensions in rails app code, , wasn't defined somewhere, rails expect find in lib/object_extensions.rb.
since can't extend core class in /lib this, it's better idea put core extensions in config/initializers directory. rails load files in there automatically when app boots up. try putting above object extension in config/initializers/object_extension.rb, or config/initializers/extensions/object.rb, or similar, , should work fine.
Comments
Post a Comment