So Many Services – Rails is MVC – Compartmentalize



So Many Services – Rails is MVC – Compartmentalize

0 0


do-not-panic


On Github rcode5 / do-not-panic

So Many Services

Mr Rogers / @rcode5

Rails is MVC

  • M odel
  • V iew
  • C ontroller

Fine for simple stuff

But Single Responsibility?

“ every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility ”

Compartmentalize

Compartmentalize

views services models mailers helpers controllers assets presenters validators serializers forms policies lib workers paginators jobs inputs importers authorizors

app/services

              % ls app/services

              artist_email_list_manager.rb
              artist_studio_manager.rb
              tag_frequency_service.rb
              ...
          

app/services/artist_email_list_manager.rb

class ArtistEmailListManager
  def initialize(artist)
    @artist = artist
  end

  def add_email(email)
    ...
  end

  def remove_email(email)
    ...
  end
end

app/services/artist_studio_manager.rb

class ArtistStudioManager
  def initialize(artist)
    @artist = artist
  end

  def assign_studio(studio)
    ...
  end

  def unassign_studio(studio)
    ...
  end
end

app/services/tag_frequency_service.rb

class TagFrequencyService
  def self.compute(model)
    # compute frequency of tag usage for model
    ...
  end
end

Repos (from Hexagonal Rails)

app/repos/artists_repo.rb

class ArtistRepo
  def self.find_by_art(art)
    ...
  end

  def self.find_by_name_or_login(name_or_login)
    ...
  end
end

Is this still SRP?

class ArtistAssociationsManager
  def initialize(artist)
    @artist = artist
  end

  def add_email(email)
    ...
  end

  def remove_email(email)
    ...
  end

  def assign_studio(studio)
    ...
  end

  def unassign_studio(studio)
    ...
  end
end

How do we name these things?

  • ActiveRecord abstraction things (Repos)
  • Things that manage 2+ models (Managers, Form Objects, Domain Models)
  • Things that compute stuff (Calculators, Paginators)
  • Is app/lib ever right?

Proposal:

Think about it early

Add more directories

Agree on “how big is a responsibility”

Thanks for not sleeping

References/Reading list

 

Mr Rogers jon@carbonfive.com bunnymatic @rcode5