Build a minimal decorator with Ruby in 30 minutes
A few weeks ago, I needed to add some view-related methods to an object. Decorators are my go-to pattern to handle this kind of logic.
Normally, I’d use the draper gem to build decorators. But the app I’m working on used an older and incompatible version of Rails.
So I built a minimal decorator from scratch, added a bunch of extra behaviors, only to end up abstracting all of these away. Follow along!
What I’m working with
My Teacher class has a handful of methods:
A one-to-many relationship with the Student class.
class. Two public methods: one that exposes the maximum number of students a teacher can teach to, and one exposing the available teaching places.
class Teacher < ApplicationRecord has_many :students def maximum_number_of_students = 30 def available_places ( maximum_number_of_students <=> students . size ). clamp ( 0 .. ) end end
In my views, I want to display a table of teachers where the number of available places for each teacher is backed by a background colour.
... continue reading