Chris Jarling

Fullstack Engineer
2nd Mar, 2019

On Tools

Let’s talk about physical tools for a moment. If you are a handyman and you need to drive a nail into a wall, there is a number of ways you could do that. You could try to drive it in with your fist or your shoes or even a stick. But there is also a tool that was build for the job of driving nails into wall: A hammer.
Now, there are different types of hammers. Wooden ones, ones made of steel, some may be magnetised and I am sure there is a whole list of other kinds of hammers that I don’t even know about. If you want to drive a nail in the wall, you will probably choose a hammer that is of a strong enough material and it will then allow you to accomplish your task.
It will probably not matter for about 95% of the cases which exact material the hammer is made of, which special features it has, which brand it was produced by and how expensive it was. It will get the job done and is therefor a good tool for the job.

Let’s now switch the topic to software development. There are also some tools that are made to help you perform certain tasks in this area. When you want to write code, you will need a text editor of some kind. If you want to execute programs, you will most likely need a terminal emulator and a shell. As with hammers, there are a lot of editors, terminal emulators and shells out there. I probably have tried too many of them.

Since starting university 7 years ago, I tried out: Notepad++, Sublime Text, Atom, VSCode, vim, neovim, VimR, Oni, Emacs, Spacemacs, MacVim, WebStorm and probably a few more I forgot about. I also tried some shells: Bash, zsh and fish, alongside some terminal emulators: Terminal.app, iTerm2, Alacritty and hyper. I even tried several window managers.
In January of 2018, I was staying in the office for two additional hours every evening for almost the entire month, because I thought I needed to switch to vim and wanted to make up for the lost productivity throughout the day. It was total madness

Writing code is not the bottleneck of my productivity

Calling it madness now is easy. But I really only had the best intentions. I wanted to be more productive, to write code faster, to have more output. To be better at my job, really. Here is the thing I did not understand: The speed at which I am writing actual code does not matter all that much. My productivity is not limited by writing down the solutions I came to, but by coming to those solutions in the first place. This is something that does not happen inside a code editor for the most part.

But instead of focusing on this part of my job, I was just chasing the next editor. Sometimes because someone smart showed off how productive they were in that certain editor. Sometimes because I saw it on a screenshot and thought it looked cool. Sometimes just because it is easier to be busy instead of being productive. In reality, every time I switched my environment, I was being slowed down by it. I needed to learn the new quirks of whatever thing I was swathing to with the goal of being more productive. I was working against my own intentions without realizing it.

Recently, a colleague was sitting at my desk at work and was looking over my shoulder while I worked. We talked about editors and setups a little and they said how they were really good at Sublime Text but did barely know anything else because they have been using one and the same editor for most of their career.
This was when the gist of this essay came clear to me: The tool does not matter at all. They all are good for the job. They differ, but you get the job done with every single one of them. Plus, you can also be editing at similar speeds in all of them when you know them well. Yes, maybe a very good vim user might be a little faster in editing text than someone of equal skill in Atom, but in the end, this metric is not what matters. What’s more important is this: When you have mastered one tool, you will always be more productive than someone how knows a lot of editors decently, but has mastered none of them.

What does that mean for me?

The conclusion from this is straight forward: I need to stop switching editors. I should choose one from the pool of “good” editors and master it. It doesn’t matter, which one. After all, the creator of Ruby on Rails is productive with TextMate.
I personally opted for Sublime Text. While I think I am more familiar with vim than with Sublime Text at this point, I was not feeling at home with vim. It always felt like something I just had to use because I spent so much time learning it initially.
So this is it. Sublime Text is fast and performant, it is on the market for quite some time now and has a large user base and ecosystem of extensions. This was important to me, and while it was true for other editors as well, I was just feeling most confident with Sublime when I made the decision a few days ago.

This does not mean that I will not change or improve my setup in the future. But I will not jump on every new editor or terminal emulator. I will change things that are having an actual negative impact on my productivity. I will not use something because someone on Twitter said it was cool. I want to be good at programming, not good at as many editors as I can be.

At this point I want to also acknowledge two things:

  1. I seem to be quite out of the norm with this behaviour. At the company I work for, most (if not all) people are having their personal setup and have been using it for a long time. But maybe someone out there is going down the same road I was and this will prove helpful.
  2. When I was in university and I first told Timo I wanted to learn vim, he told me that it was probably not going to boost my productivity as much as I thought it would. Turns out he was right.

20th Feb, 2019

Things that make me happy

I do a lot of things that make me happy over the course of a day. I'm lucky to be able to say that I do mostly things I like in a typical day. Yet, I often find myself forgetting that these things make me happy and I end up in a pursiut of happiness by consuming and buying things.

I recently read an interview with DHH on the daily sotic in which he talked about what being wealthy means to him. He noted that most of the things he loves do not cost a lot of money and that he, because of that, is not afraid to lose all his money.

Now, I am not wealthy, so I am not afraid of losing all my wealth as well. But this interview got me thinking about the things I love and how I tend to not notice the joy they give me, just because I am not paying attention to them.
I decided to wirte them down, so I don't forget.

  • Programming. I really enjoy solving problems and trying to write the best code I can. Luckily, this is also my job, so I get to do it for a long period of time every day and also get money in exchange for it.
  • Riding my bike. I do not own this thing for a long time, but it is probably the one thing of everything I have ever posessed that is sparking the most joy in me (you knew there was a Kondo reference in here somewhere, didn't you?). It keeps me healthy as well. Also, exercise in general.
  • Eating. It keeps me alive, and if done right, it also tastes awesome.
  • Hanging out and talking with people. I always saw talking as some kind of necessary evil, probably because I am weird. But I really enjoy it, if I just focus on it.
  • Reading. It keeps me calm and I talk myself into believing that it makes me smarter.
  • Learning new things. No matter in which area, I just like knowing something I did not know yesterday.
  • My morning coffee. I recently reduced my coffee intake to just one cup in the morning, which makes this one cup really special. It is the best coffee I ever had, every day.
  • Sleeping. Making room in my day to get enough sleep is making everything in my day better. I don't love the process of it, since I am not present for a large part of it, but I adore what it gives me.

It's funny though, that I need to force myself to do most of these activities instead of watching YouTube videos for 6 hours a day.


12th Feb, 2019

What I learned writing my first npm package

At Railslove we are writing more an more applications that are JavaScript only, mostly React for web applications or React Native for mobile apps. Pretty much all of those apps need to communicate with an API at some point to obtain data.In a lot of these cases, we have been using the fetch API and we noticed that we wrote the same wrappers around the API for each new project. This was cumbersome and error prone, so it seemed convenient to just move that code into a package so it could be reused throughout our various projects.

This is how Snuffles was born. It did not do much in the beginning, just the things we needed in our projects. Over time, a lot of new features were introduced and Snuffles grew in functionality. We are currently in the process of identifying what exactly we want from Snuffles and rewriting the code accordingly.

Since I was in between projects at the time we identified it could be helpful to have a package for all our fetch needs, I had the chance to be developing the first release of Snuffles.
I had used a lot of npm packages before of course, but I never actually wrote one. This was a really interesting process for me and I learned a lot along the way. This article goes into detail on some of the things that I learned and problems I encountered.
Also, a lot of the things mentioned here I only know because of Timo.

Create-React-Library

It turned out that writing the actual library code was not the biggest challenge I was facing since the gist of the code was already present in some of our projects and just needed to be adapted. The biggest challange was taking care of all the things that had to happen in order for the package to be shippable. For exmaple things like the rollup and transpiling the code using babel.
This is usually something I don't want to configure by hand, as it can be pretty cumbersome and at times also cost you a night or two. Luckily, there is create-react-library.

Just like the awesome create-react-app, it gets you up and running for development within minutes, with a decent default configuration, but for libraries instead of apps.
At first, the name seemed a little strange to me, since Snuffles is not a React library per se, but could be used in any JavaScript project. However, it turns out that the package is not tightly coupled with React. I removed some files and folders that I did not see as necessary (like the /examples folder) but was able to continue benefiting form all the configuration and start developing right away.

Local development & linking

Since the code from Snuffles was similar to something we used in a recent project I was working on, it was convenient to just remove the code from the project and use it in the package, then use the package in the project to see if something breaks. Of course, Snuffles has a test suite on its own, but having it implemented in a real project from the beginning was a nice addition and allowed covering things like testing different browsers that are not trivial to set up in a test suite.

However, linking packages locally can be a bit tricky and this was the case for me as well. Now, I don't recall what the exact problem was, but I think it was related to having the project managed with yarn and the package with npm. While I'm not certain about the causes, I'm very certain about the solution I was using: yalc.

Yalc creates a local repository for you and allows you to publish your work in progress packages to this repository, as well as including them from there in your projects for testing. This made the workflow pretty seamless.

Publishing

To be honest, publishing scared me a little. Of course, publishing is always a little scary because you put out your work in the world, just as publishing this article will be a little scary, but that was not it. It was rather the process of publishing. There are commands like prepublish, prepare and postpack and of course at some point you also have to take care of the versioning. This whole process felt overwhelming to me. But there is a package for that!
np makes publishing ridiculously easy. You literally type one command, np, and then just follow the brief wizard. It does all the rollup and packaging for you, asks you what kind of release this is (minor, major, ...) and adapts the version for you. It even supports 2FA before publishing.

All in all I had a lot of fun while writing this package and learned a lot along the way. After using so many packages over the year, it feels good to be able to finally have given something back to the community (even though Snuffles is not heavily used; we are somewhere between 50 and 100 installs per week most weeks). In the future, I definitely want to keep publishing smaller packages, even if it is just for myself. It's (almost) never wrong to ship something!


5th Feb, 2019

On noise cancelling headphones and the Bose QC 35ii

Every once in a while, I purchase an item for a specific job and it really excels in that job. And then, more or less by chance, I use it in other areas which it was not specifically bought for and it also really excels in those areas. It's an item that keeps on giving and does not stop surprising you. The Bose QuietComfort 35ii* is such an item for me. I originally bought the QC35 for use in the office. I have thought about buying noise cancelling headphones for a long time, but could never really make the jump because of the rather high price point. One day, I just made the impulse pruchase and I never looked back. This is, hands down, the best way I have spent money in a long time.

In the following, I want to talk about some of the aspects I noticed about the QC35ii specifically, but also about noise cancelling headphones in general. Now keep in mind that this is not a review of that specific peice of hardware, but more of a report of my experiences — with the Bose headphones, but also with the concept of noise cancelling headphones in general.

Noise Cancelling

As this is the main reason for buying these headphones, I think it is fair to talk about this first. If you are reading this and don't know me, I'm a software engineer. That means I'm spending large stretches of my workday sitting in front of a computer thinking about things. Most of these things require at least a moderate amount of focus in order to be done properly. Now, there is this weird phenomenon in the industry: The most important thing for the individual is to be able to focus in order to do great work. Simultaneously, pretty much every office you step in is an open floor office. I don't know how exactly this happened and why it still is the trend, but those two things are pretty opposing.

I, as well, work on an open floor office. It is not big, we are 5 people in there and most of the time it is quite. But there are also times where we jokingly refer to it as the "train station". So it can happen that you are in the middle of something and suddenly someone is entering the room, wanting to discuss something and sparking a conversation across the whole room, making it hard to focus. I don't want to discuss the conept of the open floor office in too much detail here. I'll just say that there is enough evidence that it is not helping with focus, but I also kind of like being able to talk to my collegues when we're not in deep focus. It is a complicated relationship.

It was in one of these "train station" moments where I lost my calm over having just dropped my thought and bought the Bose QC35ii. I have not looked back once. Noise Cancelling headphones are really somthing that can make an open floor office viable for me. I can keep all my jolly social interaction when I want to, but I am also able to just zone out everytime I need to. If you haven't used noise cancelling headphones before, it is just awesome. It completely hides low volume conversations, and from higher volume conversations, I only get a muffled sound, so that my brain is not able to make up words and thus is not distracted.

While it is really good in an office environment, the noise cancelling is breathtaking with uniform noise, like in train or a plane. I have had moment where I put down the headphones after a while and was surprised how extremely loud my environment actually is.

Sound and comfort while wearing

Since we are talking about headphones here, we also need to talk about the sound. Since they are Bose, it was fair to assume that the sound would be good. And it is. I am no audiophile by any means and I lack the experience to identify that the highs are too high or something, so the only qualified thing I can say is the following: I used the ATH50 before, which I was told by people that know their shit in this field, sound very good. Switching from those to the Bose was easy and I did not notice the sound getting any worse. They sound different, yes, but not worse.

Another important thing for me is the comfort while wearing them over long stretches of time. I have absolutely no issues having those headphones on over three or four hours. The earpads are comfortable, the headphones are not too stiff so they do not put too much pressure on my ears and they are fairly light. At times, I even forget I am wearing headphones.

Are they worth the money?

As I mentioned at the beginning of this, this is not a review of the Bose QC35ii*, so I will not tell anyone to buy them over another product. What I will say, however, is if you are easly distracted and work in an environment that might easly distract you, spending the money on any decent noice cancelling headphones is the right thing to do. It might be a lot of money at first, but it will make your life better and it will keep on giving back every single day. If you want to buy the QC35ii, that will not be a bad purchase either. As to comparing it with similar products: Look somehwere else for the answer to that question. There are people way more qualified then I am that did the research. I just happend to buy the Bose and not the Sony WH-1000X because the Bose were discounted on my day of pruchase.


* Affiliate Link. If you were to buy the headphones through this link, I'd get a slight share of the buying price. The price won't be any different for you.


1st May, 2018

Precious Time

A few weeks ago, I stumbled upon Matt Raglands time tracking challenge and have been going with it (on and off) since then.
The general concept of the challenge is fairly easy: The whole 24 hours of the day are split in 15 minute blocks (after the idea of this Wait But Why article). For every block, you fill in what you did in that block. Since all of that happens in an A6 notebook, there's room for one word per block, so you'll have to decide what the predominant activity during that time was (If this explnanation does not make sense to you, I recommend you check out the video).
I try to fill 28 to 32 of these blocks with sleep (7 to 8 hours) and not more than 36 (9 hours) with work. I'm still working on that work part. But except for those two rather big chunks of time, I do not evaluate the collected data too much.

In contrast to Matt, I don't track everything I'm doing over the day to find out what I'm spending time with and from which activities to get time from if I want to spend it on something else. That was the reason I started it in the beginning, but I only really transferred the data to a spreadsheet once and didn't get much from it.
I'm writing down everything I do to make more conscious decisions about what I spent my time with right in that moment. See, I'm not trying to be productive every single minute of my day (that's pretty much the highway to burnout, I guess), but if I'm spending time (time I'm never getting back, ever) on something, I want to be damn sure about that decision.
I want to be sure that I'm aware about what I'm going to do and I want to be sure I'm giving it 100%. If I'm jotting down 6 blocks of Leisure Time, I want to make the conscious decision to do that, not get hung up on a YouTube video while I wanted to write something and then another and a third.

Knowing I'll have to be aware of what I'm doing in order to be able to write it down helps a lot with that. When I know I'll have to write down "Leisure" for the next few blocks, I can evaluate if I actually want to do that or if there is something that would make me happier in the long run. And if I decide to hang around on YouTube the next 45 Minutes, boy that will be good 45 Minutes.
Ever since starting the challenge, I feel like I'm actively doing things, instead of just standing there and having things happen to me until the day is over.


6th Apr, 2018

Island Life

The house is located on a small island. So small even, you could walk across it by feet in 30, maybe 45 Minutes on the shorter edge. What the island is missing in depth, it has added in length though, being probably five times as wide.
The house sits on a small hill thats roughly in the middle of the island, giving it a good view of its shores on either side. On a sunny day like today, you can see the silhouette of to the mainland from the living room window emerging from behind the nordic nature of the island and the sand beach that gets longer or shorter with the tide.
Right now, the water is moving away from the island, slowly but steady giving it some land back until the sea will claim whats hers in a few hours. Seagulls are taking the chance to hunt for snails and worms in the wet and muddy sand that no longer is protected by the salty water.

From the kitchen window on the opposite side of the house, where he is standing and doing the dishes, none of that can be seen, of course. All you could see from here except the offshore wind generators would be the shore of Norway, if it wasn't that far away. On beautiful days like this, he likes to take his time when doing the dishes, watching the various birds that live on the island in the dunes and the reflection of the sun on the seemingly endless North Sea. The repetitive motions combined with the view have something meditative to it. The radio in the living room is playing some music in the background that is matching the beginning of spring perfectly. Life is good.

She is upstairs in a small room packed with all kinds of things, probably working on one of her handiwork projects. The two of them are the only two people living in this big house, that is almost a mansion, with more rooms a reasonable person could ever need. In earlier days, this house was probably the home of three generations of a family, and given its architecture, probably some personnel that was keeping everything tidy. The family that lived here was probably the richest on the island, owning lots of ground. Nowadays, there is a lot less life in the house. Almost half of the rooms are empty, as there is just no need for a third bedroom or a fourth bathroom right now. There is a lot of happiness in the house though. Both of them are enjoying the unhasty life on the island. The clocks just seem to run slower here.
And in seven more months, there will be at least one more room in use, with one more soul inhabiting the house. They'll need a crib for that room. They'll probably need to get that from the mainland by ship.

At least thats what I imagine as I watch the house get smaller by the minute through the window of the ferry. The small wave the ship produces pushes a little water back towards the island, causing some of the birds to abandon their search for critters and fly away. Just a minute longer and the ship takes a turn, vanishing the house form my sight.
The ferry moves closer and closer back to the mainland, back to calendars and budgets, back to clients and deadlines, back to noise and problems and hecticness, to goals and reviews and a quantified self.
I'll keep thinking about that house a lot in the following days and weeks.


27th Mar, 2018

A Year without Alcohol - Three Months In

At the beginning of the year I sat down and thought about what I want to do with this new year that had just begun, as so many of us do. I though about where I was, where I wanted to go, defined goals and checked if I was still standing behind my long term plans. At some point, more or less out of the rose, I decided I would not drink alcohol for this entire year. This was 86 days ago. In the following, I want to talk about the reasons why I decided to stay sober for an entire year and reflect about how the first three months went. Let’s start at the beginning.

Why would I stay sober for a year?

When I drank, I never used to drink much (I wasn’t really drunk in about 3 years now), but I used to drink often. I was the kind of guy to never say no if someone asked for a beer after work. At some point, I was drinking almost every day. I was healthy otherwise, I worked out regularly and I was on a vegan diet, which makes it a lot more complicated to eat unhealthy. I just used to drink beer often. Recently, I noticed it got harder for me to just drink a single beer. I used to be disappointed if the group only drank one beer and did not want to do another. At times, I would just drink a second one on my own. I think these are some red flags. I would not consider myself an alcoholic, but I think I set my self on a dangerous path. That’s the main reason I decided to cut out alcohol for a year.

There are a couple of other reasons, though. I like to challenge myself and try out roads less traveled. I took the cold shower therapy multiple times, back in university I joined the NoFap community, I started to get up at 5am the last few months and went Vegan last year. I believe there is something to find on these paths most people don’t take, even though they tend to be more uncomfortable in the beginning. I might be wrong.
I also was curious: The last time I was sober for a year was the very year before the day I first drank alcohol. I never was sober for a year in my entire adult life. What would that be like?

Benefits after three months

There are a lot of articles on this topic already (like this or this, or one of my favourites, this video), and the following list of benefits mostly coincides with those pointed out in these articles, so I’ll just go over the most important ones real quick.

  • Better sleep: This is possibly the most valuable benefit so far. I sleep way better (I should note that we also threw our bed out in favour of a futon, which has also affected my quality of sleep). I generally sleep deeper, wake up less often and feel more well rested in the morning.
  • Weight Loss: Without changing my diet or workout routine, I lost some weight around my waistline. I do not own a scale, but its visually visible, so I think it must well be some kilos. It makes sense when you think about it: No more empty calories from beer and no more eating shit after drinking because I’m too lazy to cook.
  • Longer days: When I drank a beer after work, the day was basically over. I would go home, cook something, but never really had the feeling of being productive or doing anything other than lying around and clicking through Youtube or Netflix. Without alcohol, I find easier motivation to still do something in the evening, like writing this.
  • Less anxiety: In general, I feel a lot less anxious, both in my head and in social situations. I feel like I’m in control more. Here again, I have to point out that I’m also doing the Headspace course on anxiety, so I don’t know how much of this is due to lesser alcohol intake for sure.
  • Saved money: I read this in a lot of other articles and thought it wouldn’t be so impactful, but over the course of the past months I’d say I probably saved 30€ - 50€ per month. Not the world, but nice nonetheless.

Disadvantages

For every decision in life, there are consequences, and not all of them are positive. The same goes for this one. Some of the disadvantages I have noticed include:

  • Most alcohol-free beers taste bad: I really like the taste of beer, in the last year I started getting into craft beer a lot, so alcohol-free beer is mostly a disappointment. Most of them are really sweet. I try to get my hands on a Clausthaler Extraherb, Becks rose or Jever Fun when I can. Also most alcohol-free white beers do taste decent.
  • You are always that guy: If you have social surroundings that are okay with having people around that do not drink like I have for broad parts, that’ll make things easier. But you will often have to explain why you do not drink. A lot of people did sober January in the beginning of the year, which helped a lot.

For me, all the advantages, by far, outweigh the disadvantages I found, so I’m pretty excited to see what will happen in the next few months. I’m not sure if this will be a regular check in, or if it will just happen every now and then, when there is enough to write about. But I like the idea of having this written down somewhere, if not only to remind myself that it’s worth to stick with it.


25th Mar, 2018

A Tale of two Bookmarking Services

I read quite a few things on the internet. More than reading though, I'm saving things I may want to read later. For a long time, my tool of choice for this has been Instapaper (and it still is today). A little over a year ago, I notice I also want to save things that are not articles. Even though you can basically throw anything at Instapaper and it will at least save the URL, I didn't like to have a lot of random noise in my reading list. I then signed up for Pinboard and it was perfect to save and organize bookmarks of any kind.

I set out to just save things that aren't articles with Pinboard, but soon wanted to organize everything, including articles, with tags and descriptions. For a while, I used Pinboard exclusively for everything. That worked just fine, but I missed the queue of offline-available articles in a readable and unified style Instapaper provided. Some Pinboard-Apps for iOS make use of Safaris Reader-View, but that doesn't help me at all when I'm stuck in the subway and have no possibility to load the content in the first place.

The logical next step was an IFTTT-Hook, that would save everything I threw at Pinboard to Instapaper as well. There's two problems with this approach, though:

  1. I went full circle and now had non-articles added to Instapaper as well.
  2. I needed to keep track of one item in two places. When I finished an article in Instapaper and archived it, I had to head over to Pinboard, mark it as read as well and write the summary or description.

Not optimal at all. This lead to me neglecting Pinbaord in favor of just keeping most things in Instapaper, which is a shame, since Pinboard is a very great service with an even better philosophy behind it.

Now, I've been thinking about this for quite a while now. Both services offer an API, so it must be possible to solve my problem. It should be possible to write a service that acts like a middleman between the two. There are few responsibilities such a service would need to take care of:

  • When given a URL, save it to both, Instapaper and Pinboard as unread. Keep track of the id of the item in both services. It should be able to take a list of tags, so a first categorization on Pinboard can be done.
  • Regularly check if the item has been read in either of the services and sync the state over to the other services (I assume most of the time the case would be that it is archived on Instapaper and then needs to be marked as read on Pinboard).
  • It should be free and open source.
  • (optional): It preserves a list of things that have been read and do not have a description on Pinbaord yet. It allows for adding that description while presenting the highlights done in Instapaper

Without looking into both APIs much deeper (especially the Terms of Usage), this looks like it should be possible. I might give building such a service a shot on a free weekend. Otherwise, if someone else wants to build it, I'd be more than happy.


18th Mar, 2018

Learnings Week 11/2018

For some weeks now, I keep a folder in my bookmarks bar named "Learned this week". Whenever I stumble upon something interesting I learn during the week, I save the according page there. Aditionally, I keep a note in Bear for everything I learn that is not savable as a bookmark (i.e. is not a Webpage). Usually on sundays, I comb through that folder and the notes and prepare everything so that I can possibly come back at it later.
I used to do this for myself, in private, but I might as well do it here.

This week is rather short on content, since I dove into React Native for the most part and did not really go much deeper than the documentation and some usual pitfalls. There's two things though:

Why is using “for…in” with array iteration a bad idea?

I tend to forget the right way to loop over an Array / an Object in JavaScript about every 3 to 6 Months. While I was refreshing my memory on the topic, I also stumbled across this question on StackOverflow.

Demystifying Multi-file Searches in Vim and the command line

I've been using vim exclusively for more than two weeks now, and it's going pretty well. When I was pairing with a co-worker on Friday and he told me to do a project-wide search for a string, I had to open Sublime Text for the first time since moving to vim.
In an effort to avoid future embarrassements, I did some research on searching project-wide in vim. I always thought I'd need a plugin like the silver searcher for that, but vim actually provides satisfactory methods by itself.


13th Mar, 2018

Custom checkboxes with collection_check_boxes

DISCLAIMER: This is one of the posts I'm writing to help myself learn new things. This is probably not the best way to do this. If you have a better way, please let me know!

Today, I found myself in a situation where I needed to build some custom checkboxes inside a Rails app. Now, custom checkboxes are not that uncommon when it comes to frontend work, but in my form, I used collection_check_boxes to render a set of checkboxes and I never had to apply custom styles to those.
I'm going to split this up in two parts.

The Markup

Let's say we want our result to look something like this:

![checkboxes example]({{ "assets/images/checkboxes.jpg" | absolute_url }})

The checkbox looks a little like a button, and when checked, it should render a solid background with a white font.
The markup for this looks rather simple:

<label class="custom-checkbox">
  <input type="checkbox" class="checkbox" />
  <span class="custom-label">Label</span>
</label>

The checkbox-hack has been around for a while now, so the following CSS should be no suprise to anybody:

.custom-checkbox
  position: relative

  // Hide default checkbox and move it out of the way
  .checkbox
    position: absolute
    opacity: 0

  .custom-label
    display: inline-block
    padding: 14px 30px
    border: 1px solid grey
    border-radius: 4px
    font-size: 18px
    font-family: sans-serif
    cursor: pointer

  // Apply styles to custom-label when the original checkbox is checked
  .checkbox:checked ~ .custom-label
    color: white
    border-color: #00CBA2
    background-color: #00CBA2

Here, we are using the fact that not only the checkbox itself can be clicked to check or uncheck it, but also the label. We're now hiding the default checkbox and styling the contents of the label (which is just a span in this example) to our likings. When the label is clicked (and thus the checkbox checked), we simply change the styling of the custom label to refelct the state of the checkbox we desire (you can try this out in this simple pen).
From a pure CSS/HTML standpoint, we reached our goal.

The Rails Part

In my from in rails, I was using the following line to render a list of checkboxes for categories:

= f.collection_check_boxes :category_ids, Category.all, :id, :name,
include_hidden: false

There are several ways to get to the markup I described above, but I did not want to forgo the comfort of using collection_check_boxes.
After some searching, I stumbled accros this answer on StackOverflow. Even though it was answering a question about simple_form, I tried to adapt it to my form_for setup.
Here's what I ended up with:

= f.collection_check_boxes :category_ids, Category.all, :id, :name, include_hidden: false do |b|
	= b.label(class: 'custom-checkbox') do
		= b.check_box(class: 'checkbox')
		%span.custom-label= b.text

This way, I could have both: Custom styled checkboxes and the advantages of using collection_check_boxes.

Newer posts
Older posts
© 2024 Chris Jarling