Skip object or identifier

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?

+7
ruby ruby-on-rails
source share
2 answers

I assume ActiveRecord is doing something like this. Or rather, how do I do it.

 def my_method(oid) oid = oid.id if oid.respond_to?(:id) # proceed end 
+7
source share

If the process is actions with several controllers or in a session, it is better to use id. For example, you are going to save the cart in the session, the best choice is id. It's hard to see how large the object is, using id will help improve performance and avoid unnecessary errors.

However, if the methods are inside the same request and all actions are in memory, using the object itself will be faster. For example, you pass a user to an authority class to check if he can do something. Since all objects are only a reference in memory, an additional step to extract the identifier is superfluous and inefficient.

+6
source share

All Articles