In Ruby, what are the use cases for adding methods to an instance's singleton class? -


Thank you for some other posts and reading, I understand singleton / meta classes. And I think why we want to use them on the class. But I still can not understand why we want to use them at frequencies. And I still saw it in practice.

I am referring to something like this: class vehicle DEF odometer _reading # some code end end my_car = vehicle new def my_car.open_door # some code end

The first thought was that it seems like a bad idea because it has to face difficulties in understanding code and debugging.

Why do we want to do this? When this is a good idea, what are some of its examples?

An example is using it for testing purposes: Duplicate methods to create duplicate and double objects . Debugging is closer: redefining the logging method for a specific object that you suspect is wrong behavior, so that the log information is printed directly to the console (or more information printed) during the debug session.

Another example is working with special cases - instead of legacy you can do this starting from the classical example if you use two types of employee s , Then, engineers s and SalesPerson s, for which the compensation calculation rules are different, you can put the general rule in the employee category, Again, you can get the second two sections and apply your own calculate_salary methods Now, if an outlair - is a star salesman, instead of making a whole sub-class for this particular employee, you have agreed on a separate compensation plan with a CEO with a special plan, you It can only define the method for the specific object representing that employee.

The third example is dealing with objective lifecycle and performance considerations. In some processing methods, instead of being a long code of different states like file-reading classes, which transparently cache the entire file in the background (I have a very simple-real-real approach I know, but know as a model) read all the requests, while the file is not completely reading, it should check whether the requested data is already in the cache or disc Should be read from. They always go from the cache after the files are completely read. You can redefine the read method on the object instead of if ( case if there are more states)) to deal with it After being fully read in the cash-Livel For this simple example, it does not take any major performance advantage (if any benefits at all), but for more complex cases which may be worth it.

Comments

Popular posts from this blog

php - PDO bindParam() fatal error -

logging - How can I log both the Request.InputStream and Response.OutputStream traffic in my ASP.NET MVC3 Application for specific Actions? -

java - Why my included JSP file won't get processed correctly? -