I am using Ruby on Rails v3.2.2 and I would like to call methods "directly" on instance attributes and not on their receiver objects. That is, if I have an User instance @user for which
@user.name
# => "Leonardo da Vinci"
I would be able to implement methods that act "directly" on the name attribute so that I can write something like
# Note: 'is_correct?' and 'has_char?' are just sample methods.
@user.name.is_correct?
@user.surname.has_char?('V')
Is it possible? If so, how can I make that?
Note: I am trying to implement a plugin.
In order to do this, you would have to use a special type of class for each attribute, which IMHO, would be hugely overkill, assuming your reasons are purely with concern for visual style.
For example, since @user.name returns a String, you can only call methods on it that belong to the String class by default. If you want to call additional methods on it, you either want to use a subclass of String, or add some singleton methods to that particular instance of String. I think it would be confusing and inconsistent and would likely get in the way of real progress.
A better solution is just to ask something like:
@user.valid?(:name)
As for has_char?('V'), you can already do that with instances of String:
@user.surname.include?('V')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With