Today I Learned

A collection of useful bits & bobs I'd rather not forget
Ruby Decorators

Callbacks in active record can, even with the best intentions, quickly become a tangled web of despair. Decorators are a neat way of layering functionality in a more specific way.

For example, let's say you have a class which generates an image.

class GenerateImage
  def call
    # do some image processing stuff
  end
end

GenerateImage.new.call

Simple enough, but perhaps you also want to send an alert when the image processing is complete. You could do this with an active record callback, but using a decorator provides a nice declarative way of doing the same thing:

class GenerateImage
  def call
    # do some image processing stuff
  end
end

class ImageProcessingDecorator < SimpleDelegator
  def call
    if __getobj__.call
      # Send alerts after the call method
      # of GenerateImage is complete
    end
  end
end

ImageProcessingDecorator.new(
  GenerateImage.new("params")
).call

Effectively whatever arguments you pass to GenerateImage then "fall" through to the ImageProcessingDecorator after processing has successfully completed. Using this pattern you can layer functionality together in a way that's easier to unpick at a later date.

Big thanks to the mighty Ben Orenstein for his video on the subject. If you write ruby code, you should check out his upcoming course.

RUBY
RAILS
Things I learned on other days →