Camille Baldock

Aspect Oriented Programming in Ruby

April 14, 2014 | 2 Minute Read

London Ruby User Group: April 14, 2014 [Slides] (http://www.slideshare.net/CamilleBaldock/aspect-oriented-programming-in-ruby) [Video] (https://skillsmatter.com/skillscasts/5199-aspect-oriented-programming-in-ruby)

Aspect-oriented programming is a solution to the problem of some features affecting virtually all business requirements, and expresses that problem in a compact and DRY way. This talk is about how, when and why to leverage AOP when working in a Ruby environment.

##Abstract

Many of us developers love arguing about architecture that we dislike and refactoring our code to loosen coupling and weaken dependencies between our objects. Unfortunately, some overarching parts of our applications, like persistence, networking, notifications, logging, auditing, are scattered in our code, forcing us to specific explicit dependencies between them and our domain objects.

Aspect-oriented programming is a solution to the problem of some features affecting virtually all business requirements, and expresses that problem in a compact and DRY way.

In this practical talk, I:

  • introduce the basic concepts of AOP, and how it is still relevant even in a non-statically typed language like Ruby
  • show you how to easily and quickly leverage some AOP principles in your Rails application
  • play with some AOP-friendly constructs in Ruby 2, in particular TracePoint
  • walk you through two existing Ruby frameworks to practice Aspect-Oriented Programming

I even attempted to prove that not all things coming from the Java world are necessarily bad.

##What is AOP ?

AOP provides a generalised and low ceremony method of wrapping any object with something akin to Rails before, after and around filters. This is particularly useful for extracting and DRYing up code that handles cross-cutting concerns such as logging or error handling. AOP modularises and provides a domain-specific language to specify which methods or execution points are affected and the actions that should be invoked at those points.

##References and acknowledgements

The code example used (code snippets storage) comes from this excellent blog post from Marcin Grzywaczewski. I first considered the classic line/point geometrical example, or the bank account example, but his example struck me as being one of the simplest to present orally as well as realistic.

Images

Frameworks

Further reading