Hanami: Container Architecture

If you’ve had a chance to catch my presentation on Hanami, you know that one of my favorite features is the separation of concerns when it comes to “apps”. What do I mean by that?

Let’s think about a blog. You’d have your front facing portion of the site, where people can read posts, and the backend portion of your site, where you create the posts. If you think about it, these really are two different web apps sharing the same monolithic application. If you come from a Rails background maybe you’ve worked around this by name-spacing a controller like Admin::PostsController

Hanami has a solution for that. Container Architecture. Using this type of architecture within Hanami allows us to cleanly place multiple apps within the same Hanami project. This allows the HTTP layer of our project to be divided up into separate applications.

If we had a fresh Hanami project and wanted to add an admin “app”, we could just run:

bundle exec hanami generate app admin

Now, within our apps/ directory we would find apps/admin. Even better, you can see how the application handles the two separate apps by taking a peek at config/environment.rb

Hanami::Container.configure do
  mount Admin::Application, at: '/admin'
  mount Web::Application, at: '/'

Each app has it’s own set of routes. Any routes we add to the admin app will be name-spaced in the url under /admin.

For more information on Hanami and it’s different architecture types, check out the Architecture Overview

Centralize It, with Scopes

I recently gave a talk on Hanami at CodeStock. While putting the presentation together, I dug in to querying against a database with Hanami. Hanami follows the DataMapper pattern. Essentially, your model is only used for business logic. It knows nothing about the database. To interact with the database you have a corresponding repository that handles that interaction. You can read more about this here. I bring this up because in Hanami the query methods are private to the repository. Confused? Let me try to explain better…

Lets take a look at how we query in Rails. The examples I’m going to use  are somewhat simplified. Our database design would likely be much different.

We strap the ActiveRecord backpack to our model and querying is a breeze.

# app/models/movie.rb
class Movie < ApplicationRecord

# somewhere in your application
Movie.where(director: "David Lynch")

I’m kind of an ActiveRecord fanboy. Looking at the above code  is just as fantastic to me today as it was the first time I saw it. Anyway… we’ve got our database filled up and we’re ready to start using this all throughout our application. We start sprinkling this .where query above throughout the site and everything is working as planned.

You’ve launched the application and you realize that maybe you should do some refactoring. You’ve realized that you should have a database table for your directors. So you run something like:

$ rails g model director name:string
$ rails g migration add_director_id_to_movies director_id:integer
$ rails g migration remove_director_from_movies director:string
$ rake db:migrate

Voila, you have a directors model. Maybe you create a script to create directors based on the directors in your Movie model. Now you’re done with the director column in Movie and you’ve dropped it from your database.

Uh Oh.

We’ve got queries all over the application that explicitly query by the now non-existent director column.

Movie.where(director: "David Lynch")

How could we have avoided this from the beginning? You might have guessed- scopes.

What are scopes? I think the Ruby on Rails Guides explain it well:

Scoping allows you to specify commonly-used queries which can be referenced as method calls on the association objects or models.

So what could we have done from the beginning to fix this complexity?

# app/models/movie.rb
class Movie < ApplicationRecord
  scope :by_director, -> (name) { where(director: name) }

Now whenever you want to lookup a director, you would just call:

Movie.by_director("David Lynch")

This is where our database change would cause less headache. We just added our directors table and the column no longer exists on Movie. Instead of going throughout the application to change every Movie.by_director, you only have to update your scope. Likely you have a relationship setup here, like the following:

# app/models/movie.rb
class Movie < ApplicationRecord
  belongs_to :director

# app/models/director.rb
class Director < ApplicationRecord
  has_many :movies

With this type of relationship setup, our scope can just adapt to query through the relationship:

# app/models/movie.rb
class Movie < ApplicationRecord
  scope :by_director, -> (name) do
    joins(:director).where(directors: { name: name })

Now your references to Movie.by_director() throughout the application remain untouched. This also provides one extra, and important, benefit. It’s much easier to test. If you’re doing any controller or feature testing, then you can just mock calls to Movie.by_director() and your tests don’t break across the board when you make your changes to the database.

Rails: belongs_to Required in Rails 5

I ran across something the other night in Rails 5 that I want to share. Let’s say you have code similar to the following:

class Organization < ApplicationRecord
  has_many :users

class User < ApplicationRecord
  belongs_to :organization

This code works fine as long a user has an organization. If you try to save a user and organization_id is blank, you’d get the error: Organization can't be blank. This threw me for a loop. Rails has never required this before. A quick Google search shows that using belongs_to now requires an association to be present. This is default behavior in Rails 5. It makes complete sense, typically our relationships that belong to something rely on the associated record to exist.

This would be the same as:

class Organization < ApplicationRecord
  has_many :users

class User < ApplicationRecord
  belongs_to :organization
  validates :organization, presence: true

Keep this in mind when using things like accepts_nested_attributes_for. It would work fine as long as your form included fields_for an organization. What if you want an organization to be optional, though?

class Organization < ApplicationRecord
  has_many :users

class User < ApplicationRecord
  belongs_to :organization
  accepts_nested_attributes_for :organization, reject_if: :all_blank

With the new requirement, this will fail without an organization. How do we fix that? It’s pretty simple.

class User < ApplicationRecord
  belongs_to :organization, optional: true

Rails: Confirmation Validator

I came across a validator the other day that I have not yet come across, confirmation.

If you’ve done any password storing in Rails, especially with something like Devise, you’ll be familiar with password_confirmation. This is an attribute that is not persisted, but is used to verify that the user provided the password correctly, and didn’t mis-spell it. It turns out, Rails has this type of functionality built in.

Taken straight from the docs:

class Person < ActiveRecord::Base
  validates :email, confirmation: true

This will create a ‘virtual attribute’ that validates the object trying to be saved or created passed a matching attribute of email_confirmation. This can be used on any field provided to the validator. Want to verify the user provided the right age? (Sorry, just needed an example) validates :age, confirmation: true and voila, the validation will fail if the virtual attribute age_confirmation isn’t matching.

There is a catch If the confirmation field is nil, it won’t fail the validation. This is easy to fix, however. Add in a validator for presence on the virtual attribute. Once again, from the Rails docs:

class Person < ActiveRecord::Base
  validates :email, confirmation: true
  validates :email_confirmation, presence: true

Rails: Join Table Migration & Many to Many Relationships

When I was learning Rails, I was never more excited than when I could get a many-to-many relationship to work properly. What is a many-to-many relationship? Let’s take a quick look.

Let’s say we’re writing for a blog. This blog allows posts to be attributed to multiple authors. So I co-write with my friend, we both are listed as authors. This post has many authors. We also want to see all the posts that an author has written. This author has many posts. This type of relationship is called many-to-many.

In rails there are a couple of different ways to achieve this. There is has_and_belongs_to_many and has many through. To demonstrate this migration method, I’m going to be using has_and_belongs_to_many. Let’s build a really small Rails application to look at how this works.

  1. Create a new application with rails new blog
  2. cd blog to change the directory to your new Rails application
  3. Let’s create an Author model using rails new model author first_name last_name
  4. Let’s create a Post model using rails new model post title
  5. Run rake db:migrate to run our new migrations for the two models we’ve created.

At this point, if you open up your app/models directory, you should see post.rb and author.rb. Right now there are no relationships between the two. Let’s create some sample data real quick.

  1. Run rails c to open up an IRB instance
  2. Let’s create an author `Author.create(first_name: “Mark”, last_name: “Twain”)
  3. Let’s create another author `Author.create(first_name: “Stephen”, last_name: “King”)
  4. Let’s create a blog post `Post.create(title: “The Latest Weather Trends”)

If we were to try and call Post.find(1).authors it should miserably fail because that relationship doesn’t exist yet. Let’s fix that. The typical way we handle many-to-many relationships is with what I like to think of as an intermediate table. This intermediate table is usually a combination of both table names and has two columns, both table primary keys.

When all is said and done we want to have a table that is structured something like this:

id | author_id | post_id |
1  | 1         | 1
2  | 2         | 2

Rails, being opinionated, knows how to look for this kind of table using the has_and_belongs_to_many method in your model.

You can create a table using a standard migration rails g migration create_authors_posts author_id:integer post_id:integer which to be honest, is already very convenient for us. However, Rails also gives us some syntactic sugar in the form of a method to make this even cleaner. Let’s use this syntax to create our join table.

rails g migration create_posts_authors_join_table

In our db/migrate folder, we can open the newly created migration and should see:

class CreateJoinTable < ActiveRecord::Migration
  def change

We can call our fancy method from the change method definition.

class CreateJoinTable < ActiveRecord::Migration
  def change
    create_join_table :posts, :authors

If we now run rake db:migrate, our posts_authors table will be created for us. This means we can go back into our models and add the following:

In post.rb has_and_belongs_to_many :authors In author.rb has_and_belongs_to_many :posts

Finally, lets see how it works! 1. Open a rails console back up rails c 2. Lets add our authors to our post Post.first.authors << Author.first and Post.first.authors << Author.last

Now we should be able to call Post.first.authors and get an ActiveRecord::Associations::CollectionProxy of all the authors. AND we can also call Author.first.posts, and see the post is now a collection associated to the author.


Rails: take

I was taking a quick scroll through the Rails Guides the other day and came across an ActiveRecord query method I wasn’t familiar with. take

From what I gather, it’s essentially limit.

User.take calls the SQL SELECT * FROM users LIMIT 1

I assume a good use case for this would be only wanting 1 record from the database. You wouldn’t have to pass an argument like in limit: User.limit(1).

Take will also allow you to pass an argument for number to return, similar to limit: User.take(2)

Do with this what you will. I just found it interesting.

Rails: New & Create with Blocks

All too often I’ll come across, or in the past have written, code like the following:

user = User.new(
  first_name: "Jason",
  last_name: "Charnes",
  email: "jason@example.com,

This code would work great as a one-liner. However, in the event you see this code written like this, that means it’s probably become too long to fit on one line. This may seem harmless at first, but there are a couple of things that don’t feel right. All this should be taken with the grain of salt that is my personal preference. We’re using parenthesis, which we really don’t see too often on multiple lines in Ruby. Also, once we move to multiple lines, assigning attributes feels a little less object oriented.

It turns out we can achieve the same with using blocks. We can take the above example and refactor it, like the following:

user = User.new do |u|
  u.first_name = "Jason"
  u.last_name = "Charnes"
  u.email = "jason@example.com


When I was a teenager I noticed something was off about me. You could look at a picture of me from 2008 and think I’m talking about my weight #stillFat. You might recall a social setting we were in together where I may have said something/acted over-the-top. You might remember how I spent money, sometimes I didn’t have, to try and find happiness. While all those things aren’t necessarily normal, that’s not what I’m talking about.

I couldn’t quite pin-point what it was, though. Eventually, trying to figure it out, and keeping it to myself, became debilitating. I found that I could never rest or relax. I lived with never ending fear, worry, and a tight chest (not the sexy kind). I had no control my own thoughts. Uncontrollable thoughts sometimes lead to uncontrollable actions. It was odd.

I was also unintentionally making life hell for those close to me. I was having unwanted mood swings and depression. I was destroying my relationship with friends, my girlfriend at the time, and family. I finally learned to block it out with a wall of over-the-line humor and superficially happiness. Though it helped, it never solved anything. Surely this isn’t the way life is supposed to be? So, as anyone with my condition would do, I began to hit the internet seeing if anyone else dealt with this. It appeared that what I was going through was actually really common, though not necessarily normal.

You see, I have a General Anxiety Disorder. In a really broad sense, I worry about things that will, most likely, never happen. I also am Obsessive Compulsive. So the things I worry about gets placed on a mental carousel that doesn’t stop spinning. It spins the same thoughts ’round and ’round. To try and stop the carousel I try to take action. Actions that are odd to others, and hell- even to myself.

  • Sometimes I would drive 45 mins, at midnight, to pull on a locked door that I already locked at 7pm.
  • I would drive around in circles to make sure I hadn’t hit someone with my car because I hit a bump in the road.
    • This would actually lead me to have the windows down/radio off whenever I would drive anywhere.
  • I get particularly scared that I have a some disease. Usually that disease is impossible for me to get, as well.
  • I would, and still do, worry that every single action in my life is offensive, or straining, to relationships I have with friends and family.
  • Every time I push code to a server, I have a slight panic that disaster is about to ensue. Though this is probably good because it causes to be more thorough, and write more/better tests.
  • I fear emails because obviously the only reason someone would email me is to tell me something awful has happened.
  • Sometimes I’m anxious for no reason.

You will most likely read these and think that’s really stupid. Well, I don’t disagree. You may even ask why I don’t just move on. Well, I ask myself that quite often. It’s not that easy. If it was that easy, I wouldn’t be writing this.

When this happens, it actually can become very debilitating. It becomes hard to communicate with people. I, at times, hyper-ventilating. I lose the ability to focus. The worst part about all of it is the feeling of guilt I have for worrying about this stuff. I feel like I’m giving myself too much attention, and not those around me.

I’ve been told many times that it’s just because I’m not ‘trusting God’ with it enough. This one is particularly tough. I’ve prayed for years for this to go away and it doesn’t just go away because I trusted God with it. As a Christian, I’m not downplaying God, I just believe that sometimes God may want us to also take other action.

I’ve also been told to just take medication for it. This has been hit and miss for me. The first medicine I was put on made me very angry, I stopped taking it after a week. The second medicine I was given sent me to the hospital with a priapism. The next medicine I was put on caused my heart to do weird things. I stopped taking it too. Finally I was placed on a medicine that helps me quite a bit. It, like any other medicine, doesn’t fix it- but it helps me control it.

The real help for me came when I also started to see an amazing counselor. He has changed my life in many ways. I would say this has been one of the most important parts of my journey with anxiety. I can tell him all the crazy things that go through my head, and leave his office feeling like the weight of the world has been lifted off my shoulders. He has also taught me the power of breathing exercises. Anytime I start to go into a panic attack, I just lay back and breathe.

It’s 2015 and I’ve come quite a ways. I’m learning to separate the anxiety from the normal. The medicine helps with the smaller, day-to-day anxieties. Whenever things get bad, I know to go see my counselor. When I sense anxiety or a panic attack coming on, I take time to breathe and fight what’s happening.

I don’t think you every fully defeat anxiety, you just learn how to control it.

  • Anxiety is nothing more than thoughts.
  • Thoughts can be difficult to put aside, but it can be done.

It’s okay if you experience this

  • I didn’t know it was okay to talk about these things. I thought I was alone.
  • You can talk to me, in confidence, and I’ll try to help point you to the right people to help.

This is an actual thing.

  • I couldn’t admit that something was wrong.
  • You can’t work towards a resolution without realizing there’s a problem.

Please don’t use it as a crutch – Be vulnerable, not weak. – Be open and honest, but don’t blame anxiety- work with it.

What is this for?

  1. I needed to get this off my chest.
  2. Maybe you know someone like me and they don’t explain why they actually go through.
    • I’ve been lucky to have friends that are/have been really good to me throughout this whole journey. Be that friend.