[caption id="attachment_141384" align="alignnone" width="1912"] Ruby Metaprogramming can be a good thing.[/caption]
Recently, I was reviewing one of my student's code. He had a program with many methods that printed out various messages, for example:
class MyClass
def calculate(a)
result = a ** 2
puts "The result is #{result}"
end
end
class MyOtherClass
def some_action(a, b)
puts "The first value is #{a}, the second is #{b}"
end
def greet
puts "Welcome!"
end
end
I suggested that he store these messages in a separate file to simplify the process working with them. Then, I remembered how I18n translations are stored in Rails and got an idea. Why don't we create a YAML file (a so-called dictionary) with all the messages and a helper method to fetch them properly, all while supporting additional features like interpolation? This is totally possible with Ruby's metaprogramming!
Continue reading %Learn Ruby Metaprogramming for Great Good%
by Ilya Bodrov-Krukowski via SitePoint
No comments:
Post a Comment