Extending the Hash Class in a Rails Application
I have a rails application where I need to extend a module Hash
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 created a file called hash_extensions.rb and put it in the lib folder and of course set up the autoload paths with the following line inconfig/application.rb
config.autoload_paths += %W(#{config.root}/lib)
When I call the delete blank method on the Hash, I get the following error:
undefined method `delete_blank' for #<Hash:0x000000081ceed8>\nDid you mean? delete_if
In addition to this, I also tried to place require "hash_extensions"
at the top of the file from which I am calling the delete_blank method.
What am I doing wrong here, or can I avoid extending Hash to have the same functionality?
source to share
You can solve this problem in several ways:
-
Assuming what
hash_extensions.rb
's underyour_app/lib/extensions
. (It is recommended to keep all extensions in a separate folder), all extensions inconfig/application.rb
must be listed below:Dir[File.join(Rails.root, "lib", "extensions", "*.rb")].each {|l| require l }
-
Move
hash_extensions.rb
underconfig/initializers
and it should be automatically loaded. - Create a folder
lib
orextensions
subyour_app/app
and draghash_extensions.rb
it to it, and Rails will take care of loading it.
source to share