Open/Closed Implementation in Ruby

I would like the opinions of my friends and frenemies wherever they exist! This is how I implement Open/Closed: Open/Closed in Ruby All points of view are fair game. You can even tell me I am stupid. I can handle any conversation you want to throw at me!

I would especially love TBers thoughts on it!

Why do you prefer this meta programming trick:

Object.const_get("#{preference.capitalize}NewsDigestBroadcaster")

to accepting any object?

module NewsDigestBroadcaster
  def broadcast(user, broadcaster)
    broadcaster.(user, news_digest)
  end
end

This is IMO cleaner and simpler. It’s also easier to test. There’s no way to inject a dummy broadcaster into your code without creating a global constant (which isn’t side-effect free and might causes problems on consecutive test runs).

Also: Why do you use modules instead of classes? Modules already serve two purposes (namespaces and traits).

1 Like

I apologize. I got am email that I was going to be charged A LOT of money :smile: so I cancelled.

I am back as it was a bug.

I do this because your example causes the caller to change, my version requires NO code to change in order to add more functionality.

Modules are not for namespaces and traits. :smile: Look at ruby standard lib. Lots and lots of modules.

Instead think of it like this.

A class is for state and inheritance. OOP
A module is for pure functions (no state, no object). FP