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.namereturns aString, you can only call methods on it that belong to theStringclass by default. If you want to call additional methods on it, you either want to use a subclass ofString, or add some singleton methods to that particular instance ofString. 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:
As for
has_char?('V'), you can already do that with instances ofString: