Is it possible to define an instance method in ruby โโfrom a string (method name) and a block (method contents)?
I suppose this will need to use instance_eval (), but I haven't figured out how to mix the two data types yet. Both the string and the block are dynamically determined, so it will work to create a block with "def # {string}" at the beginning - I do not know how to do this.
My use case is a class representing the Bacula configuration file. A configuration file can have many different types of resources. They are all stored in a relatively complex data structure behind the scenes (for other reasons, simplifying this structure will not lead to what I'm looking for). I would like resources to be quickly accessible using named methods.
For example, A represents one configuration file, B represents another. A has resources Director, Client, Work and B have Messages and Director.
In this case, A must have director (), client (), and job () methods, while B has messages () and director (). Each of them will return the corresponding resource from the corresponding configuration file.
I know that there are simpler ways to do this (for example, implement the [] method), but at the moment I am pursuing a more difficult solution for the sake of curiosity.
source
share