Natalia Natalia - 1 month ago 13
Ruby Question

Why do I get "uninitialized constant" when creating custom hash class?

In Rails, I'm trying to create a custom hash class, So I created a file in lib/core_ext/hash_with_variants.rb with this content

class VariantsHash < Hash
def []=(string, value)
all_variants(string).each do |variant|
super(variant, value)
end
end

def [](string)
all_variants(string).detect do |variant|
super(variant)
end
end

private

def all_variants(string)
downcase_string = string.downcase
string_length = string.length

variants = [downcase_string]

string_length.times do |i|
variants << downcase_string[0, i] + downcase_string[i + 1 , string_length]
end

variants
end
end


but when I try and initialize a new object using

VariantsHash.new


I get the error

NameError: uninitialized constant VariantsHash


What else do I need to be doing to get this right?

Answer Source

You need to require the file in your /config/application.rb. By the way, some would say it's better to mixin your custom methods using modules than opening the built-in class directly.