Search code examples
ruby-on-railsruby-on-rails-2

Cannot override core ruby class in Rails 2.3.4


I want to extend the ruby class, for example,

# lib/core_ext/hash.rb

class Hash
  def gop_compact
    delete_if{|k, v| (k.blank? || v.blank?)}
  end
end

I have created a separate folder in the /lib directory as follows,

lib/core_ext/hash.rb

And I tried to include this path in load_paths as follows,

# config/environment.rb
config.load_paths += %W( #{RAILS_ROOT}/lib/core_ext )

After all this setup, restarted the server and tried calling method on a Hash object but it throws an undefined method exception.

Note:- Rails version is 2.3.4

I spent lot of time on this but no luck yet. Any help is appreciated.

Thanks in advance!


Solution

  • Even though you've added the core_ext folder to your load paths, you'll still need to require it with require 'hash'. To minimize memory usage, Rails won't actually require ruby files just because you add them to your load_path.

    >> Hash.instance_methods.grep(/gop/)
    => []
    >> require "hash"
    => true
    >> Hash.instance_methods.grep(/gop/)
    => [:gop_compact]