This is just a question of best practices.
Imagine you have a method that takes a single parameter. This parameter is the identifier of the object. Ideally, I would like to be able to pass either the identifier of the object directly, or simply the object itself.
What is the most elegant way to do this?
I came up with the following:
def method_name object object_id = object.to_param.to_i ### do whatever needs to be done with that object_id end
So, if the parameter is already an identifier, it just practically remains unchanged; if it is an object, it gets its identifier.
It works, but I feel it could be better. In addition, to_param returns a string, which in some cases can return a "real" string (ie, "String" instead of "2"), therefore it returns 0 when to_i is called on it. This can happen, for example, when using a friendly gem for classes.
Active recording offers the same functionality. It doesn't matter if you say:
Table.where(user_id: User.first.id) # pass in id
or
Table.where(user_id: User.first) # pass in object and infer id
How do they do it? What is the best approach to achieve this effect?
ruby ruby-on-rails
weltschmerz
source share