Skip to main content

Slimming Down Your Models and Controllers with Concerns, Service Objects, and Tableless Models

Connor Lay|

The Single Responsibility Principle

“A class should have one, and only one, reason to change. - Uncle Bob”

The single responsibility principle asserts that every class should have exactly one responsibility. In other words, each class should be concerned about one unique nugget of functionality, whether it be User, Post or InvitesController. The objects instantiated by these classes should be concerned with sending and responding to messages pertaining to their responsibility and nothing more.

“Fat models, thin controllers”

This is a common Rails mantra that a lot of tutorials, and thus a lot of beginners, follow when building their next application. While fat models are a little better than fat controllers, they still suffer from the same fundamental issues: when any one of the object’s many responsibilities change, the object itself must change, resulting in those changes propagating throughout the app. Suddenly a minor tweak to a model broke half of your tests!

Benefits of following the single responsibility principle include (but are not limited to):

  • DRYer code: when every bit of functionality has been encapsulated into its own object, you find yourself repeating code a lot less.
  • Change is easy: cohesive, loosely coupled objects embrace change since they don’t know or care about anything else. Changes to User don’t impact Post at all since Post doesn’t even know that User exists.
  • Focused unit tests: instead of orchestrating a twisting web of dependencies just to setup your tests, objects with a single responsibility can easily be unit tested, taking advantage of doubles, mocks, and stubs to prevent your tests from breaking nearly as often.

No object should be omnipotent, including models and controllers. Just because a vanilla Rails 4 app directory contains models, views, controllers, and helpers does not mean you are restricted to those four domains.

There are dozens of design patterns out there to address the single responsibility principle in Rails. I’m going to talk about the few that I explored this summer.

Encapsulating model roles with concerns

Imagine you’re building a simple online news site similar to Reddit or Hacker News. The main interaction a user will have with the app is submitting and voting on posts.

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Post</span> <span class="hljs-inheritance">< <span class="hljs-parent">ActiveRecord::Base</span></span></span>
 validates <span class="hljs-symbol">:title</span>, <span class="hljs-symbol">:content</span>, <span class="hljs-symbol">presence:</span> <span class="hljs-keyword">true</span>

 has_many <span class="hljs-symbol">:votes</span>
 has_many <span class="hljs-symbol">:comments</span>

 <span class="hljs-function"><span class="hljs-keyword">def</span> </span>vote!
 votes.create
 <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Comment</span> <span class="hljs-inheritance">< <span class="hljs-parent">ActiveRecord::Base</span></span></span>
 validates <span class="hljs-symbol">:content</span>, <span class="hljs-symbol">presence:</span> <span class="hljs-symbol">:true</span>

 belongs_to <span class="hljs-symbol">:post</span>
<span class="hljs-keyword">end</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Vote</span> <span class="hljs-inheritance">< <span class="hljs-parent">ActiveRecord::Base</span></span></span>
 belongs_to <span class="hljs-symbol">:post</span>
<span class="hljs-keyword">end</span>

So far so good.

Now imagine that you want users to be able to vote on both posts and comments. You decided to implement a basic polymorphic association and end up with this:

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Post</span> <span class="hljs-inheritance">< <span class="hljs-parent">ActiveRecord::Base</span></span></span>
 validates <span class="hljs-symbol">:title</span>, <span class="hljs-symbol">:content</span>, <span class="hljs-symbol">presence:</span> <span class="hljs-keyword">true</span>

 has_many <span class="hljs-symbol">:votes</span>, <span class="hljs-symbol">as:</span> <span class="hljs-symbol">:votable</span>
 has_many <span class="hljs-symbol">:comments</span>

 <span class="hljs-function"><span class="hljs-keyword">def</span> </span>vote!
 votes.create
 <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Comment</span> <span class="hljs-inheritance">< <span class="hljs-parent">ActiveRecord::Base</span></span></span>
 validates <span class="hljs-symbol">:content</span>, <span class="hljs-symbol">presence:</span> <span class="hljs-symbol">:true</span>

 has_many <span class="hljs-symbol">:votes</span>, <span class="hljs-symbol">as:</span> <span class="hljs-symbol">:votable</span>
 belongs_to <span class="hljs-symbol">:post</span>

 <span class="hljs-function"><span class="hljs-keyword">def</span> </span>vote!
 votes.create
 <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Vote</span> <span class="hljs-inheritance">< <span class="hljs-parent">ActiveRecord::Base</span></span></span>
 belongs_to <span class="hljs-symbol">:votable</span>, <span class="hljs-symbol">polymorphic:</span> <span class="hljs-keyword">true</span>
<span class="hljs-keyword">end</span>

Uh oh. You already have some duplicated code with #vote!. To make matters worse you now want to have both upvotes and downvotes.

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Vote</span> <span class="hljs-inheritance">< <span class="hljs-parent">ActiveRecord::Base</span></span></span>
 enum <span class="hljs-symbol">type:</span> [<span class="hljs-symbol">:upvote</span>, <span class="hljs-symbol">:downvote</span>]

 validates <span class="hljs-symbol">:type</span>, <span class="hljs-symbol">presence:</span> <span class="hljs-keyword">true</span>

 belongs_to <span class="hljs-symbol">:votable</span>, <span class="hljs-symbol">polymorphic:</span> <span class="hljs-keyword">true</span>
<span class="hljs-keyword">end</span>

Vote’s API has changed, as .new and .create now require a type argument. In the small case of just posts and comments, this is not too big of a change. But what happens if you have 10 models that can be voted on? 100?

Enter ActiveModel::Concern

<span class="hljs-class"><span class="hljs-keyword">module</span> <span class="hljs-title">Votable</span></span>
 extend <span class="hljs-constant">ActiveModel::Concern</span>

 included <span class="hljs-keyword">do</span>
 has_many <span class="hljs-symbol">:votes</span>, <span class="hljs-symbol">as:</span> <span class="hljs-symbol">:votable</span>
 <span class="hljs-keyword">end</span>

 <span class="hljs-function"><span class="hljs-keyword">def</span> </span>upvote!
 votes.create(<span class="hljs-symbol">type:</span> <span class="hljs-symbol">:upvote</span>)
 <span class="hljs-keyword">end</span>

 <span class="hljs-function"><span class="hljs-keyword">def</span> </span>downvote!
 votes.create(<span class="hljs-symbol">type:</span> <span class="hljs-symbol">:downvote</span>)
 <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Post</span> <span class="hljs-inheritance">< <span class="hljs-parent">ActiveRecord::Base</span></span></span>
 <span class="hljs-keyword">include</span> <span class="hljs-constant">Votable</span>

 validates <span class="hljs-symbol">:title</span>, <span class="hljs-symbol">:content</span>, <span class="hljs-symbol">presence:</span> <span class="hljs-keyword">true</span>

 has_many <span class="hljs-symbol">:comments</span>
<span class="hljs-keyword">end</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Comment</span> <span class="hljs-inheritance">< <span class="hljs-parent">ActiveRecord::Base</span></span></span>
 <span class="hljs-keyword">include</span> <span class="hljs-constant">Votable</span>

 validates <span class="hljs-symbol">:content</span>, <span class="hljs-symbol">presence:</span> <span class="hljs-symbol">:true</span>

 belongs_to <span class="hljs-symbol">:post</span>
<span class="hljs-keyword">end</span>

Concerns are essentially modules that allow you to encapsulate model roles into separate files to DRY up your code. In our example, Post and Comment both fulfill the role of votable, so they include the Votable concern to access that shared behavior. Concerns are great at organizing the various roles played by your models. However, concerns are not the solution to a model with too many responsibilities.

Below is an example of a concern that still breaks the single-responsibility principle.

<span class="hljs-class"><span class="hljs-keyword">module</span> <span class="hljs-title">Mailable</span></span>
 extend <span class="hljs-constant">ActiveModel::Conern</span>

 <span class="hljs-function"><span class="hljs-keyword">def</span> </span>send_password_reset_email
 <span class="hljs-constant">UserMailer</span>.password_reset(<span class="hljs-keyword">self</span>).deliver_now
 <span class="hljs-keyword">end</span>

 <span class="hljs-function"><span class="hljs-keyword">def</span> </span>send_confirmation_email
 <span class="hljs-constant">UserMailer</span>.confirmation(<span class="hljs-keyword">self</span>).deliver_now
 <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>

This problem is not something concerns are good at solving. A User model should not know about UserMailer. While the actual user.rb file does not contain any reference to UserMailer, the User class does.

Concerns are a great tool for sharing behavior between models, but must be used responsibly and with a clear intent.

Reducing controller complexity with Service objects

On the topic of emails, lets take a look at controllers. Imagine we want users to be able to invite their friends by submitting a list of emails. Whenever an email is invited, a new Invite object is created to keep track of who has already been invited. Any invalid emails are rendered in the flash with an error message.

class InvitesController < ApplicationController
 def <span class="hljs-built_in">new</span>
 <span class="hljs-function"><span class="hljs-keyword">end</span></span>

 def <span class="hljs-built_in">create</span>
 emails.<span class="hljs-keyword">each</span> <span class="hljs-built_in">do</span> |email|
 <span class="hljs-keyword">if</span> Invite.<span class="hljs-built_in">new</span>(email).save
 UserMailer.invite(email).deliver_now
 <span class="hljs-keyword">else</span>
 invalid_emails << email
 <span class="hljs-function"><span class="hljs-keyword">end</span></span>
 <span class="hljs-function"><span class="hljs-keyword">end</span></span>
 unless invalid_emails.<span class="hljs-constant">empty</span>?
 flash[:danger] = <span class="hljs-string">"The following emails were not invited: #{invalid_emails}"</span>
 <span class="hljs-function"><span class="hljs-keyword">end</span></span>
 redirect_to :<span class="hljs-built_in">new</span>
 <span class="hljs-function"><span class="hljs-keyword">end</span></span>

 <span class="hljs-keyword">private</span>

 def emails
 <span class="hljs-built_in">params</span>.<span class="hljs-built_in">require</span>(:invite).permit(:emails)[:emails]
 <span class="hljs-function"><span class="hljs-keyword">end</span></span>

 def invalid_emails
 @invalid_emails ||= []
 <span class="hljs-function"><span class="hljs-keyword">end</span></span>
<span class="hljs-function"><span class="hljs-keyword">end</span></span>

What exactly is wrong with this code you might ask? The single responsibility of a controller is to accept HTTP requests and respond with data. In the above code, sending an invite to a list of emails is an example of business logic that does not belong in the controller. Unit testing sending invites is impossible because this feature is so tightly coupled to InvitesController. You might consider putting this logic into the Invite model, but that’s not much better. What would happen if you wanted similar behavior in another part of the application that was not tied to any particular model or controller?

Fortunately there is a solution! Many times specific business logic like sending emails in bulk can be encapsulated into a plain old ruby object (affectionately known as POROs). These objects, often referred to as Service or Interaction objects, accept input, perform work, and return a result. For complex interactions that involve creating and destroying multiple records of different models, service objects are a great way to encapsulate that responsibility out of the models, controllers, views, and helpers framework Rails provides by default.

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BulkInviter</span></span>
 <span class="hljs-keyword">attr_reader</span> <span class="hljs-symbol">:invalid_emails</span>

 <span class="hljs-function"><span class="hljs-keyword">def</span> </span>initialize(emails)
 <span class="hljs-variable">@emails</span> = emails
 <span class="hljs-variable">@invalid_emails</span> = []
 <span class="hljs-keyword">end</span>

 <span class="hljs-function"><span class="hljs-keyword">def</span> </span>perform
 emails.each <span class="hljs-keyword">do</span> |email|
 <span class="hljs-keyword">if</span> <span class="hljs-constant">Invite</span>.new(email).save
 <span class="hljs-constant">UserMailer</span>.invite(email).deliver_now
 <span class="hljs-keyword">else</span>
 invalid_emails << email
 <span class="hljs-keyword">end</span>
 <span class="hljs-keyword">end</span>
 <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">InvitesController</span> <span class="hljs-inheritance">< <span class="hljs-parent">ApplicationController</span></span></span>
 <span class="hljs-function"><span class="hljs-keyword">def</span> </span>new
 <span class="hljs-keyword">end</span>

 <span class="hljs-function"><span class="hljs-keyword">def</span> </span>create
 inviter = <span class="hljs-constant">BulkInviter</span>.new(emails)
 inviter.perform
 <span class="hljs-keyword">unless</span> inviter.invalid_emails.empty?
 flash[<span class="hljs-symbol">:danger</span>] = <span class="hljs-string">"The following emails were not invited: <span class="hljs-subst">#{inviter.invalid_emails}</span>"</span>
 <span class="hljs-keyword">end</span>
 redirect_to <span class="hljs-symbol">:new</span>
 <span class="hljs-keyword">end</span>

 private

 <span class="hljs-function"><span class="hljs-keyword">def</span> </span>emails
 params.<span class="hljs-keyword">require</span>(<span class="hljs-symbol">:invite</span>).permit(<span class="hljs-symbol">:emails</span>)[<span class="hljs-symbol">:emails</span>]
 <span class="hljs-keyword">end</span>

 <span class="hljs-function"><span class="hljs-keyword">def</span> </span>invalid_emails
 <span class="hljs-variable">@invalid_emails</span> ||= []
 <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>

In this example the responsibility of sending emails in bulk has been moved out of the controller and into a service object called BulkInviter. InvitesController does not know or care how exactly BulkInviter accomplishes this; all it does is ask BulkInviter to perform its job. While much better than the fat controller version, there is still room for improvement. Notice how InvitesController still needs to know that BulkInviter has a list of invalid emails? That additional dependency further couples InvitesController to BulkInviter.

One solution is to wrap all output from service objects into a Response object.

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Response</span></span>
 <span class="hljs-keyword">attr_reader</span> <span class="hljs-symbol">:data</span>, <span class="hljs-symbol">:message</span>

 <span class="hljs-function"><span class="hljs-keyword">def</span> </span>initialize(data, message)
 <span class="hljs-variable">@data</span> = data
 <span class="hljs-variable">@message</span> = message
 <span class="hljs-keyword">end</span>

 <span class="hljs-function"><span class="hljs-keyword">def</span> </span>success?
 raise <span class="hljs-constant">NotImplementedError</span>
 <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Success</span> <span class="hljs-inheritance">< <span class="hljs-parent">Response</span></span></span>
 <span class="hljs-function"><span class="hljs-keyword">def</span> </span>success?
 <span class="hljs-keyword">true</span>
 <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Error</span> <span class="hljs-inheritance">< <span class="hljs-parent">Response</span></span></span>
 <span class="hljs-function"><span class="hljs-keyword">def</span> </span>success?
 <span class="hljs-keyword">false</span>
 <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BulkInviter</span></span>

 <span class="hljs-function"><span class="hljs-keyword">def</span> </span>initialize(emails)
 <span class="hljs-variable">@emails</span> = emails
 <span class="hljs-keyword">end</span>

 <span class="hljs-function"><span class="hljs-keyword">def</span> </span>perform
 emails.each <span class="hljs-keyword">do</span> |email|
 <span class="hljs-keyword">if</span> <span class="hljs-constant">Invite</span>.new(email).save
 <span class="hljs-constant">UserMailer</span>.invite(email).deliver_now
 <span class="hljs-keyword">else</span>
 invalid_emails << email
 <span class="hljs-keyword">end</span>
 <span class="hljs-keyword">end</span>
 <span class="hljs-keyword">if</span> invalid_emails.empty?
 <span class="hljs-constant">Success</span>.new(emails, <span class="hljs-string">"Emails invited!"</span>)
 <span class="hljs-keyword">else</span>
 <span class="hljs-constant">Error</span>.new(invalid_emails, <span class="hljs-string">"The following emails are invalid: <span class="hljs-subst">#{invalid_emails}</span>"</span>)
 <span class="hljs-keyword">end</span>
 <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">InvitesController</span> <span class="hljs-inheritance">< <span class="hljs-parent">ApplicationController</span></span></span>
 <span class="hljs-function"><span class="hljs-keyword">def</span> </span>new
 <span class="hljs-keyword">end</span>

 <span class="hljs-function"><span class="hljs-keyword">def</span> </span>create
 inviter = <span class="hljs-constant">BulkInviter</span>.new(emails)
 response = inviter.perform
 <span class="hljs-keyword">if</span> response.success?
 flash[<span class="hljs-symbol">:success</span>] = response.message
 <span class="hljs-keyword">else</span>
 flash[<span class="hljs-symbol">:danger</span>] = response.message
 <span class="hljs-keyword">end</span>
 redirect_to <span class="hljs-symbol">:new</span>
 <span class="hljs-keyword">end</span>

 private

 <span class="hljs-function"><span class="hljs-keyword">def</span> </span>emails
 params.<span class="hljs-keyword">require</span>(<span class="hljs-symbol">:invite</span>).permit(<span class="hljs-symbol">:emails</span>)[<span class="hljs-symbol">:emails</span>]
 <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>

Now InvitesController is truly ignorant of how BulkInviter works; all it does is ask for BulkInviter to do some work and sends the response off to the view.

Service objects are a breeze to unit test, easy to change, and can be reused as your app grows. However, like any design pattern, service objects have an associated cost. Abusing the service object design pattern often results in tightly coupled objects that feel more like shifting methods around and less like following the single responsibility principle. More objects also means more complexity and finding the exact location of a particular feature involves digging through a services directory.

The biggest challenge I faced when designing service objects is defining an intuitive API that easily communicates the responsibility of the object. One approach is to treat these objects like procs or lambdas, implementing a #call or #perform method that performs work. While this is great for standardizing the interface across service objects, it heavily relies on descriptive class names to communicate the object’s responsibility.

One idea I’ve used to further communicate the purpose of service objects is to namespacing them into their specific domain:

Invites<span class="hljs-tag">::BulkInviter</span>
Comments<span class="hljs-tag">::Creator</span>
Votes<span class="hljs-tag">::Aggregator</span>

The exact implementation of these service objects is largely style based and depends on the complexity of your business logic.

Taking advantage of Active Record Model

The last topic I want to cover is the idea of tableless models. Starting in Rails 4, you can include ActiveModel::Model to allow an object to interface with Action Pack, gaining the full interface that Active Record models enjoy. Objects that include ActiveModel::Model are not persisted in the database, but can be instantiated with attribute assignment, validated with built in validations, and have forms generated with form helpers, and much more!

When would you make a tableless model? Let’s look at an example!

Imagine we are building an online password strength checker. There are many characteristics that a good password should have, such as an 8 character minimum and a combination of uppercase and lowercase letters. Since these passwords have no use elsewhere in our app, we don’t want to persist them in the database.

Our first attempt might involve some kind of service object.

class PasswordStrengthController < ApplicationController
 def <span class="hljs-built_in">new</span>
 <span class="hljs-function"><span class="hljs-keyword">end</span></span>

 def <span class="hljs-built_in">create</span>
 checker = PasswordChecker.<span class="hljs-built_in">new</span>(<span class="hljs-keyword">string</span>: <span class="hljs-built_in">params</span>[:<span class="hljs-keyword">string</span>])
 <span class="hljs-keyword">if</span> checker.perform
 flash.now[:success] = <span class="hljs-string">"That is a strong password."</span>
 <span class="hljs-keyword">else</span>
 flash.now[:danger] = <span class="hljs-string">"That is a weak password."</span>
 <span class="hljs-function"><span class="hljs-keyword">end</span></span>
 render :<span class="hljs-built_in">new</span>
 <span class="hljs-function"><span class="hljs-keyword">end</span></span>
<span class="hljs-function"><span class="hljs-keyword">end</span></span>

class PasswordChecker
 attr_reader :<span class="hljs-keyword">string</span>

 def initialize(<span class="hljs-keyword">string</span>:)
 @<span class="hljs-keyword">string</span> = <span class="hljs-keyword">string</span>
 <span class="hljs-function"><span class="hljs-keyword">end</span></span>

 def perform
 <span class="hljs-built_in">length</span>?(<span class="hljs-number">8</span>) &&
 contains_nonword_char? &&
 contains_uppercase? &&
 contains_lowercase? &&
 contains_digits?
 <span class="hljs-function"><span class="hljs-keyword">end</span></span>

 <span class="hljs-keyword">private</span>

 def <span class="hljs-built_in">length</span>?(n)
 password.<span class="hljs-built_in">length</span> >= n
 <span class="hljs-function"><span class="hljs-keyword">end</span></span>

 def contains_nonword_char
 password.match(/.*\W.*/)
 <span class="hljs-function"><span class="hljs-keyword">end</span></span>

 def contains_uppercase
 password.match(/.*[A-Z].*/)
 <span class="hljs-function"><span class="hljs-keyword">end</span></span>

 def contains_lowercase
 password.match(/.*[<span class="hljs-operator">a</span>-z].*/)
 <span class="hljs-function"><span class="hljs-keyword">end</span></span>

 def contains_digits
 password.match(/.*[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>].*/)
 <span class="hljs-function"><span class="hljs-keyword">end</span></span>
<span class="hljs-function"><span class="hljs-keyword">end</span></span>

While this works, something feels off about our new PasswordChecker service object. It’s not interacting with any models and it does not change any states. The service object API is awkward as it is not clear if #perform is a query or a command. If we take a step back and think about what exactly this service object’s responsibility is, we soon arrive at validating the strength of a password. In other words, PasswordChecker contains and validates a set of data, much like Active Record models do.

This is a great case for tableless models!

class PasswordCheck
 <span class="hljs-built_in">include</span> ActiveModel::Model

 attr_accessor :<span class="hljs-keyword">string</span>

 validates :<span class="hljs-keyword">string</span>, <span class="hljs-built_in">length</span>: { minimum: <span class="hljs-number">8</span> }
 validates :<span class="hljs-keyword">string</span>, <span class="hljs-built_in">format</span>: { <span class="hljs-operator">with</span>: /.*\W.*/, message: <span class="hljs-string">"must contain nonword chars"</span> }
 validates :<span class="hljs-keyword">string</span>, <span class="hljs-built_in">format</span>: { <span class="hljs-operator">with</span>: /.*[A-Z].*/, message: <span class="hljs-string">"must contain uppercase letters"</span> }
 validates :<span class="hljs-keyword">string</span>, <span class="hljs-built_in">format</span>: { <span class="hljs-operator">with</span>: /.*[<span class="hljs-operator">a</span>-z].*/, message: <span class="hljs-string">"must contain lowercase letters"</span> }
 validates :<span class="hljs-keyword">string</span>, <span class="hljs-built_in">format</span>: { <span class="hljs-operator">with</span>: /.*[<span class="hljs-number">0</span>-<span class="hljs-number">9</span>].*/, message: <span class="hljs-string">"must contain digits"</span> }
<span class="hljs-function"><span class="hljs-keyword">end</span></span>

class PasswordStrengthController < ApplicationController
 def <span class="hljs-built_in">new</span>
 @password = PasswordCheck.<span class="hljs-built_in">new</span>
 <span class="hljs-function"><span class="hljs-keyword">end</span></span>

 def <span class="hljs-built_in">create</span>
 @password = PasswordCheck.<span class="hljs-built_in">new</span>(<span class="hljs-keyword">string</span>: <span class="hljs-built_in">params</span>[:<span class="hljs-keyword">string</span>])
 <span class="hljs-keyword">if</span> @password.valid?
 flash.now[:success] = <span class="hljs-string">"That is a strong password."</span>
 <span class="hljs-keyword">else</span>
 flash.now[:danger] = <span class="hljs-string">"That is a weak password."</span>
 <span class="hljs-function"><span class="hljs-keyword">end</span></span>
 render :<span class="hljs-built_in">new</span>
 <span class="hljs-function"><span class="hljs-keyword">end</span></span>
<span class="hljs-function"><span class="hljs-keyword">end</span></span>

Not only do we get the power of built in validations, it becomes much easier to render error messages and generate the form for submitting a new password.


Concerns, service objects, and tableless models are all excellent ways to fight growing pains experienced when building a Rails application. It is important not to force design patterns, but to discover them while building your application. In many scenarios, DRYing up model roles with Concerns, creating a service object layer between your models and controllers, or encapsulating temporary data into tableless models makes a lot of sense. Other times it smells a lot like premature optimization and is not the best approach.

As with everything programming, the best way to learn is to get your hands dirty!

Further Reading

← Drag →