瞎扯淡 Bring Many monad to Active Support and Active Record relations

zzz6519003 · December 05, 2019 · Last by zzz6519003 replied at December 06, 2019 · 3770 hits

Inspired by @tomstuart's lovely talk on monads in Ruby, I'd like to dip our feet in with Rails on the Many monad.

Tom has gracefully permitted us to copy his work from the monads gem into Active Support as needed. The API I'm most keen to see is the one that allows us to use the Many monad with Active Record relations, like so:

Blogs.all.with_many.categories.posts.comments.body.split(/\s+/).values

It's a huge level up over the flat_map version:

Blogs.all.flat_map(:categories).flat_map(:posts).flat_map(:comments).flat_map(:body).split(/\s+/).values

I've wanted this for a very long time, but could think of the right way to express it. The monad is the way!

So to make this work, I'd propose that we pull in the Maybe monad into Active Support, then do a core extension for Enumerable called #with_many, and then making sure that plays nicely with the AR relations (I think it should, out of the box).

You need to Sign in before reply, if you don't have an account, please Sign up first.