How to refactoring when metaprogramming has side effects?

断了今生、忘了曾经 提交于 2019-12-25 02:04:16

问题


I am using Ruby on Rails 3.2.9 and Ruby 1.9.3-p125. After my previous question I ended up that I have an issue on metaprogramming a self-implemented acts_as_customizable plugin since the related code has side effects on other classes than that "acting as customizable".

To summarize the issue: the acts_as_customizable method stated for an Article model "internally" (through metaprogramming) adds a customize method to a Comment model and, in order to save time, Rails doesn't load all those classes on startup making the application to raise a NoMethodError - undefined method 'customize' for #<Comment:0x0...> until the Article class is loaded.

A proposed solution was to require_dependency 'article' in the Comment model, but I am looking for another way (maybe, better of the proposed one) to have the application to work as it is doing right now, but without any issue as-like that explained in this question. That is, I would like to keep a *short code** and the same behavior but using a more "appropriate" way to make things, maybe changing the loading process of classes or planning a big refactoring for the whole code, if necessary.

How should I handle this situation? What do you think about?


Update: After some study, I discovered that the problem arises only in development mode since the config.cache_classes is set to false making classes to be reloaded on every request.


Note: I want point out that metaprogramming is very usefull in my case and Article and Comment classes are highly related one to another in the aspect of my conception of "customization". So I would like to find a solution alleviating changes to the underling behavior.


* In my case, metaprogramming (even if it has side effects) makes me to avoid a lot of code statements.

来源:https://stackoverflow.com/questions/13840423/how-to-refactoring-when-metaprogramming-has-side-effects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!