Rails ActiveRecord or DDD?

November 6, 2021 by johny

Picking the right Rails code style

Yesterday I’ve seen this amazing 8 years old video October CincyRb - Jim Weirich on Decoupling from Rails. The mentioned video presents interesting way of separating App Code - business domain core logic - from infrastructure, Rails (ActiveRecord) specific code. As I understand this is called DDD - Domain Driven Design. There are multiple books about this concept. Just google them if interested. Going against the main flow - with DDD Rails concept - requires a lot of discipline and patience to learn, teach and adapt the whole team to stick to it. This might be a time consuming. I guess there are multiple benefits of this kind of architecture. I would look directly into one of them. Which would be FAST unit tests. The reason I fall in love with Nodejs and GO after working with Java Spring apps.

The result of following DDD rules is to leave domain logic in pure ruby classes - POROs - so it’s easier to unit test with rspec. Simple empty rails+rspec unit test (require rails_spec_helper?) takes 1,5 seconds to run conversely single similar rspec unit test takes 0.002 seconds to complete - huge difference - multiple orders of magnitude. Hard to achieve but gains are tempting. Maybe halfway solution is to only to Speed up Rails tests 10x by using PORO domain models

The majority of rails coders follows default rails style which comes out of rails g scaffold. Mixed concerns. Controllers methods like

  def create
    @room = Room.new(room_params)

    respond_to do |format|
      if @room.save
        format.html { redirect_to @room, notice: 'Room was successfully created.' }
        format.json { render :show, status: :created, location: @room }
        format.html { render :new }
        format.json { render json: @room.errors, status: :unprocessable_entity }

This is totally fine for even big projects especially after reading Growing Rails from people from Makandra.

More on DDD Rails might be found related sources:

Other great Ruby on Rails resources:

© [Hu]Core theme & Hugo