Is it acceptable practice to patch Ruby's base classes, such as Fixnum?

后端 未结 4 1016
臣服心动
臣服心动 2020-12-31 03:47

I am still very new to Ruby (reading through the Pickaxe and spending most of my time in irb), and now that I know it\'s possible to patch classes in Ruby, I\'m

相关标签:
4条回答
  • 2020-12-31 04:24

    The safest way is to define your own class that inherits from the built-in one, then add your new stuff to your new class.

    class MyDateTime < DateTime
      alias...
      def...
    

    But obviously now you only get the new behavior if you declare objects of your new class.

    0 讨论(0)
  • 2020-12-31 04:36

    Personally, I think it's acceptable to add methods to the base classes, but unacceptable to modify the implementation of existing methods.

    0 讨论(0)
  • 2020-12-31 04:40

    My personal answer, in a nutshell: the core-class patching hammer should be at the bottom of your toolbox. There are a lot of other techniques available to you, and in almost all cases they are sufficient, cleaner, and more sustainable.

    It really depends on the environment in which you are coding, though. If it's a personal project - sure, patch to your heart's content! The problems begin to arise when you are working on a large codebase over a long period of time with a large group of programmers. In the organization I work for, which has Ruby codebases of over 100KLOC and and twenty or so developers, we have started to crack down pretty hard on monkey patching, because we've seen it lead to head-scratching, man-hour wasting behavior far too often. At this point we pretty much only tolerate it for temporarily patching third-party code which either hasn't yet incorporated or won't incorporate our source patches.

    0 讨论(0)
  • 2020-12-31 04:42

    I think its like this: If you honestly feel that most other programmers would agree with your patches, then fine. If not, perhaps you should instead be implementing a code library?

    0 讨论(0)
提交回复
热议问题