Exotic Ruby: Module.class_exec, Custom JSON and Liquid Drops in Action
Ruby has quite a lot of “exotic” features that are not used that often, but when you need to utilize some metaprogramming magic, you can easily take advantage of them. One of such features is Object.instance_exec which you might be familiar with if you’ve ever built some more advanced DSL.
The great thing about Object#instance_exec
is that it allows to execute code within the context of a given object but it also gives possibility to pass arguments from the current context. Thanks to that, we can build some nice DSLs and other features like this:
role_filter = ->(role) { where(role: role) }
role = "admin"
User.all.instance_exec(role, &role_filter) # same as User.all.where(role: "admin")
An interesting thing is that there is a class equivalent of Object#instance_exec
- Module.class_exec. It would be easy to figure out some theoretical example how it can be used but what could be the real-world use case where this is the best approach to solve the problem?
Post a comment