我想补充的方法nil_or_empty?
所有类,所以我定义如何在Rails中扩展类对象?
module ObjectExtensions
def nil_or_empty?
return self.nil? || (self.respond_to?('empty?') && self.empty?)
end
end
::Object.class_eval { include ::ObjectExtensions }
它在一个简单的Ruby脚本正常工作
p nil.nil_or_empty? #=> true
p ''.nil_or_empty? #=> true
p [].nil_or_empty? #=> true
p 0.nil_or_empty? #=> false
然而,当我把它添加到我的库文件lib/extensions.rb
一个Rails 3的应用程序,它似乎没有添加
NoMethodError (undefined method `nil_or_empty?' for nil:NilClass):
app/controllers/application_controller.rb:111:in `before_filter_test'
我加载库文件(所有其他extensio ns从那个文件工作正常)和
# config/application.rb
# ...
config.autoload_paths << './lib'
我在哪里错了?
可能的重复http://stackoverflow.com/questions/5654517/in-ruby-on-rails-to-extend-the-string-class-where-should-the-code-be-put-in – 2011-05-01 08:34:07