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

zzz6519003 · 2019年12月05日 · 最后由 zzz6519003 回复于 2019年12月06日 · 3558 次阅读

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).

还是 flat map 清晰一些 😄

hooopo 回复

实现了 flat map,就是 monad

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册