Build a minimal decorator with Ruby in 30 minutes

https://news.ycombinator.com/rss Hits: 4
Summary

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. 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. # teachers/index.html.erb <table class="table table-striped"> <thead> <tr> <th>Name of the teacher</th> <th>Available places</th> </tr> </thead> <tbody> <% teachers.each do |teacher| %> <tr> <td><%= teacher.full_name %></td> <td class="<%= teacher.colour_coded_availability %>"> <%= teacher.available_places %> </td> </tr> <% end %> </tbody> </table> I could write the Teacher#colour_coded_availability method in my model like so: class Teacher < ApplicationRecord has_many :students def maximum_number_of_students = 30 def available_places (maximum_number_of_students <=> students.size).clamp(0..) end def colour_coded_availability case available_places when 0 then "bg-colour-red" else "bg-colour-green" end end end However, models are not the place for methods generating CSS classes. Decorators are! Drafting a decorator My decorator should accept an instance of Teacher and expose the colour_coded_availability public method. # app/decorators/teacher_decorator.rb class ...

First seen: 2025-06-12 08:44

Last seen: 2025-06-12 11:46