I understand that you define_method
create a method dynamically, but... in what cases would you use it?
What is the 'advantage' or what is different in use, over creating a simple method with def
?
Please don't cite memory references or pass links to the official documentation, because that doesn't exactly say what I'm asking.
The advantage is that you can use variables in creating a method and create less code when there are multiple methods with minimal variations.
As a sample, an example: Imagine having a model
User
with an attributestatus
that defines if that user is in active or inactive state. You also need a couple of methods to help you:Then the model that I describe would look something like this:
All good so far. Now it turns out that there are new requirements and you need to add 5 new states to your user model, for which the methods that I explained should also be defined. You could then create the methods, but it would be somewhat repetitive, where the only thing that would change is the name of the state. In this case it may be necessary to do some metaprogramming and create the methods as follows:
So in this way you have saved yourself from writing 14 methods that practically did the same thing, plus you have a much cleaner code.
Another clear example is what Rails does internally with the variable names you define. For example to create the route helpers as
users_path
ornew_user_url
when you defineresources :users
in the routes file.Do not worry if at first you feel that this is not very useful or you do not find where to apply it. Its use is something that you may not be able to visualize at first, but as your code grows, you may feel the need to refactor your code and take up some metaprogramming, where it can be useful.