Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend Hash Class in Rails Application

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?

like image 699
Michael Victor Avatar asked Mar 17 '26 13:03

Michael Victor


1 Answers

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.
like image 93
Kirti Thorat Avatar answered Mar 22 '26 14:03

Kirti Thorat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!