Lazy constantize relation resources#492
Conversation
|
|
||
| def resource_class | ||
| @resource_class ||= infer_resource_class | ||
| @cons_resource_class ||= (@resource_class.is_a?(String) ? @resource_class.constantize : @resource_class) || |
There was a problem hiding this comment.
@jkeen I'm not sure about the @cons_resource_class variable name but @resource_class directly assigns in line 52. Probably the best variant would be to rename @resource_class to something like @resource_class_name and then use @resource_class here for memorization. What do you think?
There was a problem hiding this comment.
I think that sounds like a better approach, I agree.
What happens when the resource string you provide is invalid, though? Having the reference available by specifying the actual class name makes sure the reference is good before runtime, doesn't it?
There was a problem hiding this comment.
That is how ActiveRecord does it for its relations. You set the relation class_name property as a string. It's done to omit a situation when one of the classes is not defined yet. Please pay attention to the test. When Ruby interprets UserResource the BookResource is not defined yet that's why if you try to use the class directly it causes an uninitialized constant error.
Usually, developers do not face this problem because infer_resource_class actually does the "lazy constantize" based on the relation name. But it can be a problem when you use custom relation names (like was done in the test) which is pretty common when building relations between models in different namespaces.
There was a problem hiding this comment.
@bguban I updated those instance variable names and the tests now pass
## [1.7.7](v1.7.6...v1.7.7) (2025-03-15) ### Bug Fixes * change class attribute behavior on endpoint method to work in ruby 3.2+ ([#493](#493)) ([04f1f3c](04f1f3c))
## [1.7.8](v1.7.7...v1.7.8) (2025-03-16) ### Bug Fixes * compare URI-decoded path params ([#482](#482)) ([20b80dd](20b80dd)) * correct issue with many_to_many when one of the models has a prefix to the intersection model association ([#449](#449)) ([dc28a4f](dc28a4f)) * lazy constantize relation resources ([#492](#492)) ([3cc2983](3cc2983))
|
🎉 This PR is included in version 1.7.8 🎉 The release is available on:
Your semantic-release bot 📦🚀 |
When two resources have custom relation names it's hard to specify the resource for those relations because you need both resources to be loaded in memory. Doing it lazily solves the issue. You can specify a string as a resource name and it will be constantized later when needed