Hack hack hack...

An open journal-- some of it written for you, but most of it is for me.

Service Objects

rails cast #398

Modules

  • models may have lots of behavior that isn’t related, so it probably doesn’t belong in the model layer -> usually a result of pushing behavior from the controller to the model

    • create a concerns folder that lives in the models folder
      • possibly namespace the module in a class folder if only used for a specific model
    • change the autoload config path to include the concerns folder
    • include module in the model
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#namespace in class if only going to use it in that class
class User
  module Authentication
    extend ActiveSupport::Concern

#this gets scoped to the context of the class when included
    included do
      has_secure_password
    end

#this makes these class methods instead of instance methods
    module ClassMethods
      def authenticate(username, password)
       #code
      end
    end
  end
end

Service Objects

  • we are in the habit of pushing behavior from the controller to the model, but often the behavior in the controller is nicely isolated. Sometimes we need a new kind of object commonly referred to as a service object.
  • the service object gets it’s own folder in the app folder and looks like this
  • this puts all the action related behavior in one place and keeps the model focused on validations, accessibility, etc.
  • likely works best when we have a complex controller action that interacts with a complex model

  • testing:

    • create a services level dir and and easily test the class directly similarly to how one would test the models
  • Further Reading

Comments