← Back to Upcase

Functors Are More Fun Than Nil

(Upcase ) #1
Joe and Ben introduce a concept from the functional world: Functors. Learn how you're using functors in your every day work already, and see how to apply those concepts to make code with nils safer. Check out Learn You a Haskell For Great Good an...
This is a companion discussion topic for the original entry at https://thoughtbot.com/upcase/videos/functors-are-more-fun-than-nil

(Matthucke ) #2

I watched this episode only yesterday, and immediately found a use for it.

Looking through several gems that provided this feature - wrapped, maybe, ruby-maybe, and monadic - I eventually settled on monadic because I liked the syntax it provided, and also because there were some other features I could explore and learn and use later.

The immediate use for it? In a view, I render an “advanced search” form. This could be either an initial invocation (in which case everything is empty) or a results page (in which case the various search fields may be seeded with values).

If I just wanted the form to echo what the user typed I’d use a “form object” (ActiveModel) to remember their entries. But for this, I wanted more structured data echoed back - if the user selects a product category using a javascript autocomplete widget, I want to re-display the form with the actual category’s ID and name rather than whatever substring was typed.

Ie, the user starts typing “Neoprene”, and the autocomplete resolves this to “12345 - Neoprene Seat Covers”, which is the numeric ID of that category followed by something human-readable (the extra part will be discarded when “.to_i” is called on that parameter).

So, wanting to print the form when @category may or may not be nil:

%input.category-search{name: :category_id,  value: Maybe(@category).id_and_name._('') }

when Maybe(@category) == Just(@category), it calls method .id_and_name, which prints the nicely formatted string that the autocomplete library (and the human user) want to see. (This is an admin app, so I don’t mind them seeing the numeric ids of things).

when Maybe( nil ) == Nothing, id_and_name returns Nothing.

Finally the “._( default )” unwraps the burrito and returns either the string (“12345 - Neoprene Seat Covers”) or, in the case of Nothing, a default value (an empty string).

It’s a fun little technique that’ll save me from typing some hugely long ternary operator expressions.

(Trent Lloyd) #3

New video just out which his sortof an expansion on this one.