In one answer to this question user, mu is too short, explains that you wouldn't want an object's behavior to change too drastically on initialization, which makes sense, you should be able to reason about an object well by reading its definition and being introspective but I had this case in mind:
french_colors.yml
blue: blue
red: rouge
...
translations.rb
class Translations
def initialize(language: "french")
data = YAML.load_file("./translations/#{language}.yml")
data.each do |k, v|
define_method k do
v
end
end
print_french_colors
end
def print_french_colors
puts red
puts blue
end
end
When initialized, the above Errors with
#=> NoMethodError: undefined method `define_method' for #<C:0x2efae80>
Here you build all of the Translations behavior off of the file received from a translation company and want it as an instance and also want it to be dynamic based on the language file (this is all just an example)
Would it make more sense to define and set the translations as attributes of the object in initialization instead of using define_method in initialization like this questions OP and I were trying to do? Or is it the case that the method define_singleton_method
was written to handle situations like this specifically?