Reputation: 891
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?
Upvotes: 3
Views: 1428
Reputation: 53038
You could resolve this issue in a few different ways:
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 }
Move hash_extensions.rb
under config/initializers
and it should be automoagically loaded.
lib
or extensions
under your_app/app
and move hash_extensions.rb
to it and Rails would take care of loading it.Upvotes: 6