0

Is a monkey patch when you extend a class?

class Hash
    def delete_blanks!
       delete_if { |k, v| v.is_nil? }
    end
end

Then you can do this:

h = { red: 'stop', yellow: 'ready', purple: nil, green: 'go'}
h.delete_blanks! #=> { red: 'stop', yellow: 'ready', green: 'go' }

Is that a monkey patch? What about this:

class ActiveRecord::Base
    def foo
        "bar"
    end
end

What's so bad about that?

I'm not being argumentative, I'm ready to assume it is bad, but how should I go about emulating this behaviour without a monkey patch? Should I send the method?

Starkers
  • 10,273
  • 21
  • 95
  • 158
  • possible duplicate of [What does 'Monkey Patching' exactly Mean in Ruby?](http://stackoverflow.com/questions/394144/what-does-monkey-patching-exactly-mean-in-ruby) – nobody Apr 14 '14 at 20:21
  • you second class is simply a class extending another class. I don't see how it is relevant to monkeypatching – njzk2 Apr 14 '14 at 20:21
  • The 'duplicate' doesn't state how you should extend a class properly. – Starkers Apr 14 '14 at 20:23

1 Answers1

0

I wouldn't say monkey patching is bad, it's more like a "should avoid" practice, there are definitely scenarios where monkey patching is useful.

Another way to solve this problem is through inheritance so you could have something like:

class SuperHash < Hash
  def delete_blanks!
    delete_if { |k, v| v.is_nil? }
  end
end
eduardosasso
  • 529
  • 2
  • 8