3

I have a rails application where I need to extend the Hash module to add a method -

class Hash
  def delete_blank
    delete_if{|k, v| v.nil? or (v.instance_of?(Hash) and v.delete_blank.empty?)}
  end
end

I have created a filed named, hash_extensions.rb and placed this in my lib folder and of course configured autoloading paths with the following line in config/application.rb

config.autoload_paths += %W(#{config.root}/lib) 

When I call the delete blank method on a Hash however, I get the below error -

undefined method `delete_blank' for #<Hash:0x000000081ceed8>\nDid you mean?  delete_if

In addition to this, I have also tried placing require "hash_extensions" at the top of the file I am calling the delete_blank method from.

What am I doing wrong here or can I avoid extending Hash to have the same functionality?

Michael Victor
  • 861
  • 2
  • 18
  • 42

1 Answers1

5

You could resolve this issue in a few different ways:

  1. Assuming that hash_extensions.rb resides under your_app/lib/extensions. (It's a good idea to store all extensions in a separate folder), require all extensions in config/application.rb as below:

    Dir[File.join(Rails.root, "lib", "extensions", "*.rb")].each {|l| require l }
    
  2. Move hash_extensions.rb under config/initializers and it should be automoagically loaded.

  3. Create a folder say lib or extensions under your_app/app and move hash_extensions.rb to it and Rails would take care of loading it.
Kirti Thorat
  • 52,578
  • 9
  • 101
  • 108