I Did a Thing: Bought a Mechanical Keyboard

I hear… well really read a lot about developers making the switch to mechanical keyboards. I didn’t really understand all the hype, but thought that maybe I should try it out? I’ve seen people talk about the feel of actually having to press down a key to type, as well as how they enjoy the sound of the clicking of the keys. So I did a thing, I bought one. However, I’m not trendy enough to build one like I’ve seen some people do, but I thought if I got one- I should at least get something I’d enjoy.

Voila. Apple Adjustable Keyboard. That vintage Apple style, with the ergonomics that I’ve become used to. So, with that said. I’m excited to try it out for a while and then share my thoughts on the mechanical keyboard.

Also, I really needed a good way to test out my new keyboard. Hello, test subjects.

enter image description here

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
end

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
end

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:

posts_authors
-------------------------------
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
  end
end

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

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

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.

Neat.

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
end

Slides: A Quick Look at Lotus.rb

Last night I gave a talk at the Memphis Ruby User’s Group about one of the newest web frameworks in Ruby, Lotus. Lotus is still young, but is already a lot of fun to use. Most of the slides in this talk were taken, and adapted, from the Getting Started Guides, which are amazing by the way. If you have any questions, feel free to reach out!

Testing: Wont Raise Error

I’ve been writing a lot of tests with MiniTest lately. Sometimes by choice, mostly because it already exists in the project I’m working on. I recently made some contributions to Lotus. There was a specific instance where a command line generator was returning an ArgumentError, when it shouldn’t have. I made the proper adjustments and went to test.

“Okay, so where is my wont_raise method?”, I thought.

Well, it’s nowhere. I didn’t believe this, I just wanted to test that this isn’t raising an error anymore! After several Google searches, it turns out not only does that not exists, but there’s a reason behind it. The maintainers explained why:

  1. If you’re code is going to fail because an error is raised, it’s going to show E in the test. You’ll know an error was raised.

  2. If you’re looking to make sure your code isn’t raising an error, test to make sure the functionality works.

The second point made me feel like an idiot, but it made so much sense. I got so wrapped up in testing that the error wouldn’t be raised, that I didn’t think to just test the functionality. Even more embarrassing? There was actually an issue with the code that wouldn’t have been caught had I not written tests for functionality.

/me blushes

All that to say… next time you want to reach for something like wont_raise, think it through.

Rails: Ordering by Boolean

What happens when you need to sort an ActiveRecord query by a boolean?

If you wanted to do this with ruby you could say:

posts = Post.all
posts.sort { |p| p.active ? 1 : 0 }

This would work, but this makes a database call, and then ask ruby to do the sorting. Our database can handle this type of sort for us:

posts = Post.all.order(active: :desc)

We’ve now made it more readable and handed the extra task to the database.

If we wanted our false values to be first, we could ask the database for the values ascending:

posts = Post.all.order(active: :asc)