DevblastTake your dev skills to the next levelhttps://d2xhst3wq8so4j.cloudfront.net/images/devblast_logo-bb82e02fa210b7ae65597d01ac3a0c6d.png?vsn=dhttps://devblast.com/blog
http://devblast.com/blog
http://devblast.com/b/2017-a-retrospective

It’s been more than a year since the last I published something here. Well, time really flies by when you’re having fun.

I still receive emails and see comments popping up, so Devblast is far from dead.. I just haven’t had the time to be more active on it, and in this post, I want to share why. I do believe everything I wrote has still value even if it’s a bit outdated, and I will be working on refreshing things.

Let’s dive in!

2016

2016 was the year I quit my job to focus on my side business, Devblast (Samurails at the time). I took 3 months to write Master Ruby Web APIs before the summer, then took 2 months off to spend time in France with my family and friends.

When I got back to Thailand, I turned Samurails into Devblast, but switching away from Wordpress and building a custom Elixir web application. This was my first experience with Elixir, but has played a major role in where I am today (building up suspense is good I heard ;)).

This all led to the month of December, 2016. I was going back to France for Christmas, but right before that, I got approached on Upwork for some consulting work. At the same time, a friend of mine asked me if I could spend some time improving her web application. I said yes to both, and my career as a freelancer/consultant started.

My original plan was to freelance part-time, and use the rest of my time to work on new books and web applications. All the freelance work I did at that time was still in Ruby.

2017

The first 6 months of 2017 are very blurry. I did not spend time on Devblast at all.. instead I enjoyed short work days/weeks doing freelancing and earning more than ever before. I had a lot of free time, that I efficiently used to workout, rock climb and party with friends.

Everything changed in July though. One of my friend here in Bangkok was sharing stuff about cryptocurrencies. I had started getting back into it (bought some Bitcoins back in 2015) recently, and grabbed some ETH.

So I got in touch with him. Long story short, he was (still is) the CTO of Omise, a payment processing company, which was about to launch OmiseGO and do an ICO (Initial Coin Offering) for the OMG token.

After meeting with him and the other brains behind OmiseGO, I received a job offer to join OmiseGO as “eWallet Team Lead”. The eWallet application OmiseGO wanted to build is a Web 2.5 application connecting the current web with blockchain technology, in order to make it easier for small and big companies to make the switch without feeling overwhelmed.

I officially started working there on September 1st, when OmiseGO only had like 5 people (We’re around 30+ I think now). The eWallet team itself has grown to 7 people (and we’re still looking for a backend developer!).

2018

It has been a lot of fun working there for the past 10 months! We’ve just released version 1.0.0.pre0 of the eWallet and we’re looking forward to the next step: adding support for blockchain transactions!

If you check the repo (it’s open source), you will see that we’ve written the eWallet in Elixir. My liking of Elixir started when I rebuilt Devblast and hasn’t stopped since. It’s an elegant, fast and smart language and I don’t really see myself going back to Ruby anytime soon. I still write some Ruby, however, since the eWallet comes with a Ruby server SDK.

So what happens next fort Devblast? Well, I’m going to try to go back to a writing schedule. The thing is I’m super busy with OmiseGO so I don’t want to make any promises. I might only publish blog posts once in a while if I have something worth to share.

What I’m going to do, however, is update Modular Rails to work with Rails 5 and re-release it! This will be different from my previous releases: an online version of the book will be available for free, for everyone to read and learn :) I will still sell offline formats (PDF, ePub, Mobi) of the book, but the actual knowledge will be available for free.

I guess that’s it for this update. I didn’t go into details too much, but if you have any questions, I’d be happy to clarify some parts of the story :)

PS: I’m currently looking for backend and front-end developers, as well as devops to join the eWallet SDK team!

Working in a modern office brings its share of conveniences, but as anyone who sits in front of a desk all day long knows, it’s easy to slide into unhealthy habits. Humans weren’t really designed for sitting in front of desks, staring at screens all day… but that’s exactly what most of us do, 40 hours or more per week.

As developers, we need computers for most of our work, and that usually means sitting in front of one for hours on end, with every little physical activity.

You’ve got to move it, move it

One of the biggest problems of working from a desk is that you don’t get enough opportunities for passive exercise. Take the perennial college job of working in a grocery store as an example - lifting heavy boxes or bags, climbing ladders in the backroom, or just walking around all day - you’ve essentially got a workout built in. Once you’ve traded in your nametag and pulled up a seat in front of a screen, the passive health benefits start to drain away.

One tip that always gets tossed around is the 1/10 rule - for every hour, get up and walk around for 10 minutes. If you work in a bigger office, this one is a little easier to turn into a habit - walk to a coworker’s desk, go hangout near the coffee machine, or take a spin around the breakroom. If you work from home or in a smaller team, use your phone’s timer to set break reminders for yourself. Or if your working hours are flexible, run out to the post office, grocery store, or take a quick walk around the block every two hours or so. In any case, you’re reaping double the benefits from unplugging for just a few minutes - getting a little exercise will also improve your mental clarity, energy, and possibly your overall job performance.

Ergonomics

“Ergonomics” was the buzzword in the office of the early 90s. As computer use became more and more frequent, so too did headaches, backaches, and repetitive strain injuries like carpal tunnel syndrome as the new occupational hazards. The solution? Proper design of things we used everyday, like keyboards, chairs, or computer mice.

Nowadays, there are tons of tools you can buy that claim to reduce repetitive strains with the added benefit of making your workspace a touch more futuristic. The split keyboard and chairs with increased lumbar support and cushioning are becoming more and more popular.

But an ergonomic workspace also means a lot of small, non-obvious adjustments. This might mean the positioning of your keyboard, the height of your computer screen, or the distance between your chair and the screen. No matter how expensive, new, or cool an office gadget might be, there is no magic bullet for solving all the problems that can come from inactivity or odd positioning over so many hours.

A good place to start is doing a full body scan while sitting in your normal position at your desk. How does your neck feel - achy? Tight? Are your legs falling asleep? Any muscle twitches? Tune into where you sense discomfort or repetitive, unnatural movement during daily tasks.

It is super important here to take into account the circumstances of your individual body. A workstation that might work for one person could be totally counterproductive or dysfunctional for someone else. Are you prone to back problems? Taller than most people? You might need to tweak the height of your desk or the tilt of your screen.

Diet

What it is it about working at a desk that utterly destroys healthy diets? If you work in an office with others, the breakroom snacks and lunch dates are obvious culprits. But those who work remotely aren’t immune either - if you regularly work from coffee shops or other coworking style cafes, you know how easy it is to add a not-so healthy treat in with your coffee order.

One way to get started is to get organized about eating. When we’re rushing to work or parked in front of the computer pushing to meet a strict deadline, it’s easy to grab things that will give us a quick boost but that aren’t that great for us. Having a plan for chaotic times is essential, whether it’s sliced fresh fruit in a desk drawer or portion-sized bags of trail mix in your bag. When making dinner, plan to make a little extra and set aside lunch the night before, making sure to tuck in lots of leafy greens and veggies as a side. We all know that processed foods aren’t good for our energy levels or overall health, so making it a habit to keep backups for stressful times is crucial.

Beat the Desk Life

At the end of the day, our productivity is inextricably linked to our health. Especially if you make your own hours as a freelancer or work remotely, the battle for consistency and stability is real. Many times, the first things to get sacrificed are our diet, posture, and other healthy habits. But if you think about it, an investment in your health is an investment in your job satisfaction and ability to get things done.

Besides some of these general tips, here a few actual, actionable things that you can do to fight back against a sedentary lifestyle.

Try

Exercise at Your Desk

This one sounds pretty obvious, but mixing in isometric exercises during your normal work day is a good way to stay fit. Choose one of these isometric exercises and do one during a short break or every hour. If you work in a bigger office and don’t want to break a sweat in public, use mealtimes to take a walk around the block or climb up and down a flight of stairs in your building.

Journaling

There are a million ways to keep yourself accountable to your health goals. If you’re keen on using visuals or like to jot things down manually, check out bullet journaling. The beauty of this journaling system is that it’s endlessly adaptable to different productivity styles and needs. Track meals and snacks, or keep a “health to-do list” the same way you would track work tasks - anything from “drink 8 glasses of water” to “20 push ups.” Then, make it a goal to get through as many as you can.

If you’re not really the artsy type or prefer keeping things all in the cloud, add health reminders to the productivity platforms you already use. There are the old standards, like Evernote, but you can also try the stripped-down Wunderlist. Create a separate list to make sure you step away from the desk, exercise, or grab a quick snack periodically.

Automating It

Use the tools you already have - set a timer on your smartphone or calendar for every hour you’re at your desk (just make sure to for the meetings). Take just a few minutes to get away stretch, drink a glass of water, walk around, or do a few crunches. By essentially making an appointment with yourself, you increase the odds that you’ll stick to any health plan. You can also go with some time-boxing techniques like Pomodoro to ensure you take regular breaks between your tasks.

Meditating

Meditation improves not only your mental health, but also gives your eyes a rest and gives you a chance to check in with your body. If you find yourself hunching over the computer, take just 5 or 10 minutes to close your eyes, relax, and focus on your breath. Try doing a body “scan” - just practice observing your body and your posture, and make adjustments (relax your shoulders, roll
your wrists) if you notice discomfort anywhere.

Working Smarter

If you don’t always work in front of a computer, try re-organizing your daily routine so that your time at the computer is periodically broken up by other tasks. Batch similar tasks, like tracking your invoices or testing code, and then time yourself. If you feel like you’re getting sucked into the computer chair at the end of an hour, stand up and do a few stretches. Walk to a coworker’s desk to have a quick chat instead of a text, or place your printer or other devices across the room so you have to get up in order to do certain tasks.

Working smarter also means streamlining your work process to minimize the time you’re in front of the screen overall. Evaluate the tools or software you use to get things done, and change things up if necessary. If you’re a writer and need a clean, distraction-free interface for getting creative or just taking notes, try chilled out OmmWriter. Or if you need a way to stay organized while doing web development work, try a text editor that streamlines the process with Vim (here’s a few reasons to love it).

Buy

A New Workspace

Standing desks are the hot new trend in startup office management (first they came for our cubicles, now it’s our chairs). Fans of standing desks (or other chairless workspaces like the “treadmill desk”) point to their benefits, like increased circulation and calorie burning - some go so far as to say that “sitting is the new smoking.” Lifehacker’s guide to standing desks is a good place to start exploring your options. If getting a new desk is out of the question (or your budget), exercise balls and other “dynamic seats” are great for encouraging a more healthy seated posture.

The key with any workspace is to make sure it fits you as an individual. The cumulative effects of small movements, like pushing your neck forward to read your screen or overextending your wrists while typing, can negatively impact other parts of your body and cause spinal misalignments and muscle strains. Make sure you consider every area in your workspace by checking this doctor-approved guide.

Split Keyboards

Generally, a good keyboard should mirror the way you actually hold your hands while you type. Split keyboards divide the keys between the hands, and usually are curved or tilt the keys inwards, supporting optimal wrist position. Negative tilt (where the bottom of the keyboard is pointed down towards you) also combats repetitive wrist strains. Broad, curved wrist supporters on Microsoft models are good if you’re on a budget. Or check out the ErgoDox, a blowout success on Kickstarter - each keyboard can be engineered and customized to every user, with key switches specifically designed for developers, writers, and anyone else who lives in front of their computers. You can also take a look at ErgoDox EZ for pre-assembled keyboards.

The End

Though it’s difficult to put into practice, getting active is especially important for those that work in front of screens (which is honestly most of us nowadays). Working in a few exercises or updating our gear is ultimately an investment in our productivity and overall happiness - and at the end of the day, that’s really what it’s all about.

2016 was a year of change for me. I wanted to come back on what happened to me, what I did and how it’s going to affect 2017.

I started 2016 as a dev team manager for Playlab. 3 months in, I quit to focus on building my own business. After taking April off to travel, I finally got started writing my second book, Master Ruby Web APIs.

Writing Master Ruby Web APIs

Getting started was hard. I had to find new working habits and organize myself. Finding the motivation to work on my own stuff was harder than I thought, and not being able to progress as fast as I wanted to made me have doubts. Throw in some stress about money, and you get an awesome mix to write a book… or not.

Money. Something I never really worried about. When I quit my job, I only had 3-4 months of savings, and because of that I needed to finish and release the book in that time.

Staying in Thailand while not working there anymore was also complicated. I had to go to Malaysia for a few days to get a 2-month tourist visa (which was extendable one more month). I decided to go to Penang, and stayed with two great Airbnb hosts. Getting the visa was easy enough, and I spent the rest of the trip working on the book from coffee shops.

Once I got back to Thailand, I decided to set rules to ensure I would get work done everyday. To measure the time I spent working, I went with a flexible Pomodoro system. I had to do 10 Pomodoros every day before calling it a day. With this, I was able to get into a routine of getting some work done everyday. Sadly, the stress of not finishing in time prevented me from sleeping at night, keeping me awake until 3 or 4 in the morning. Obviously, I wasn’t able to wake up early the next mornings, and ended up feeling like I had already lost half of the day.

Like any writer working on a tight deadline, stress was a major issue. It was actually the reason I couldn’t fall asleep - my mind was racing to see if I could finish the book in time, and wondering if it would make any money at all. Indeed, the book was growing way bigger than I had hoped for. Looking back, I feel like it was a mistake to try to shove in as much stuff as I did. The book ended up being around 110k words (that’s about 750 pages, including a lot of code examples). The last module wasn’t even as polished as I had hoped for.

But all said and done, I finished a goal that I set out to start - and it helped a few hundreds people. Now, I’m actually looking at ways of improving it…. for instance, splitting this monster book into smaller modules so they’re easier to digest. I also received a few comments because I wasn’t explaining some of the Ruby code, and that’s because I wrote the book with an intermediate to advanced developer in mind. This will be fixed in the next version of the book.

But before I can do this, I need to release the new edition of Modular Rails, updated with Rails 5 and coming with new chapters about things I learned since the original release - almost two years ago.

In the end, I was able to release Master Ruby Web APIs in time, 2 weeks before going back to France for a holiday. I’m not going to lie - the last month was awful. I was working 10h+ a day to get everything ready, and I barely slept in the 4 days leading up to the release. I spent these nights editing the screencasts with iMovie on my burning Macbook. As a sidenote, that’s also when I decided to learn how to use Adobe Premiere so I could use my gaming PC for the editing.

In the end, the release sales brought in enough money to let me live for a few more months. It was time to fly back to France for two months, spend some time with my family, and see some of my old friends.

Spending some time in France

After the pressure of working on Master Ruby Web APIs, I needed some time away from writing and coding. The good news is that I was staying at my parent’s house, in the middle of nowhere. I was able to start working out again, eat properly, and relax. Right before going back to France, I had also started a daily vlog to learn how to edit with Adobe Premiere. This was a pretty fun experience, but I knew it wouldn’t last. It was taking me up to 3 hours to edit the vlogs each day and it wasn’t sustainable in the long run. I did it for 17 days, uploading a vlog every single day. I learned so much stuff about editing! It actually allowed me to create some awesome videos for my cousin’s wedding (using the expensive camera I had purchased for the daily vlogs). While I stopped doing daily vlogs, I don’t regret giving it a try - it was a very rewarding experiment.

I believe in the “learning by doing” motto, and this experiment proved one more time that learning by doing is an amazing and fast way to learn something new. All you need is to define the deliverables, set a timeframe and get started!

Overall, I didn’t get much done during these two months in France. I wanted to get started building Devblast, but didn’t do anything about it except learning the technologies I wanted to use and drafting some wireframes. I did however spend way more money than I was expecting, meaning I needed to tighten my belt until the release of my next monetized project.

Back to Thailand

At the end of September, I flew back to Thailand. But I still wasn’t ready to get started building Devblast, and I honestly can’t remember what I did for a month (catch up on sleep?). But in November, everything changed.

Devblast

I suddenly had so much motivation and was ready to spend my days coding. I felt back in love with the act of creating web applications and seeing it come to life. That’s something I had lost since I started working at Playlab, where I was mostly doing web API work. Writing a book about web APIs also didn’t help.

I realized that I really love building web applications, from A to Z: wireframing, designing, coding, fixing bugs… It’s so awesome!

I built Devblast in a few weeks, while still learning about Elixir and Phoenix. I could have used a static website generator or Wordpress, but my excitement came from learning to use new technologies while building something I’ve been wanting ever since I set up my first blog with Wordpress.

I also didn’t use any of these other solutions because I need to have total control over Devblast. I have big plans for it in the coming years, and these plans will require a lot of customization.

Once everything was ready, I made the switch from Samurails (Wordpress) to Devblast (Elixir / Phoenix). The migration happened without any problems.

Web Applications vs. Books

In December, before going back to France for Christmas, I thought a lot about how I felt while working on Devblast compared to writing Master Ruby Web APIs. I realized that I don’t want my business to rely mainly on books and courses. Instead, I wanted them to be byproducts, where I can teach everything I learn while building real stuff.

I love to learn new technologies and build real stuff with them. That’s why I want to build real projects that will help people and potentially generate some revenue.

A look at 2017

This year, I’m going to focus on building a portfolio of applications using different tools. I have many ideas that I want to bring to life, just the way I built Devblast from nothing.

You should know that Devblast is currently not finished - it’s only the cocoon of what it will come later. I haven’t been publishing tutorials for a while, and that’s because I’m saving my “tutorial mojo” for the next phase of Devblast.

To avoid the stress I felt while writing Master Ruby Web APIs, I’ve also started doing some freelance work again. It removes the fear of living on savings while giving me the chance to do what I love, setting my own hours and leaving me enough time to work on my own projects.

I actually shared the projects I will be working on next in this article. I will be writing a case study for each one of them: why I want to build it, how I do it, and how I market it. I would also like to share the revenue numbers of them in order to motivate you to work on your own side projects. Once they are built, I will switch back my focus to Devblast and turn it into an amazing resource to learn everything about web development.

I recently started a few freelancing Rails projects and I, therefore, won’t have as much time to write here as I’d like. I also have a bunch of web applications I’m planning to build in the coming months to learn and analyze different technologies: Elixir, Elm, React, React Native and more.

Yes, I’m going to be busy programming. But the good news is that I love it. Building stuff for the web is fun! I really, really enjoy it. Getting lost for hours in a project you believe is an amazing feeling.

That’s why I’m fine with the hours I will spend programming, for my freelance gigs and my personal projects. That’s actually about these projects that I want to talk about.

There are 6 applications I want to create.

You’re actually reading this article using the MVP of one of them: Devblast.

Devblast

This is where I share my knowledge of programming and publish books and courses to help people become awesome at their jobs. In the future, it will have a fair amount of free and premium learning resources about everything you need to know to make a killing in the world of programming. Devblast was built using Elixir and Phoenix. I’m not using any advanced front-end framework (like React or Angular) and I’m simply using Phoenix to output the HTML pages.

ProgPath

The next one I’m going to create is ProgPath, the best place to find awesome learning resources about programming. I’m planning to use Phoenix for the backend and Elm for the front-end. This will also be the first subject of a case studies where I show how to take an idea, build an application around it and potentially make money from it. progpath.com is not live.

devroutines

I can’t wait to get started on this one. I might actually start it before ProgPath just because that’s something I really care about. I’m not going to say too much right now, but it’s basically about picking into other people’s lives - just not in a bad way ;)

Battlestations.io

The fourth application is Battlestations.io. I built a first version of it at the beginning of the year but wasn’t pleased with the result and let it go. I wrote this article at that time, to share some of the things I learned. I’m now planning to rebuild it from scratch using Phoenix for the backend and React for the front-end. I also want to build a mobile application with React Native. For now I’ve only created a landing page until it’s time to work on it.

codingmerch

I’ve always wanted to have some merch website - just so I can get a mug with the Devblast logo on it. That’s the idea behind codingmerch but not just that. T-shirts, mugs, stickers and anything else that’s printable will be available on codingmerch with fun statements, beautiful illustrations and cool project logos.

Name to be defined

I don’t have the name for this one yet but I have the concept in mind. I’m still developing the idea and I won’t say more until I have more information about the project.

Why build so many things?

A few reasons. Mostly to play with new technologies while building real projects, but also to show you how to do it. Building these products will give me more experience with delivering projects to life, provide me with some street cred and allow me to write awesome case studies. After that it will be your turn to build stuff!

As explained in this post, I made the switch from a slow Wordpress website to a blazing fast application built with Elixir and Phoenix. Now, I want to share the 10 things I learned about these technologies as a Rubyist.

1. Functional Programming

Elixir is a functional language, which is quite a change when coming from the object-oriented Ruby where everything is an object.
But what does it mean exactly?

If you don’t know, functional programming is a programming paradigm. The principal characteristic of this paradigm is the absence of side effects when calling a method. Most features of the Elixir language (immutable data, pattern matching, first-class functions and more) can be derived from the desire to prevent side-effects, as can be expected from a functional language.

Functional Programming is a wide and interesting topic, one I’m not comfortable enough explaining. But if you want to take a closer look, I can recommend this article on Medium.

2. Immutability

The fact that data are immutable is a big change from Ruby. If you add an element to a list in Elixir, you won’t be getting back the same list - a new one will have been created with the added element. However, a variable can be rebinded, which means you can change which data structure the variable points to/references in memory.

x = {} # x points to the data {}
x[:one] = "two" # x still points to the same data,
# but the data has been modified

It also means you cannot change data in loops; instead, map or reduce should be used. It’s also a good example of how functions don’t have side-effects and won’t change the state of the program.

a = 0
Enum.each [1, 2, 3, 4], fn number ->
# We are not changing a, just creating new variables
# limited to the scope of this anonymous function
a = a + number
end
# Therefore a didn't change
IO.puts a # => 0

This is easily fixed with reduce - we can tell Elixir to calculate the sum using an accumulator (acc).

The property of immutability has a number of advantages like data consistency and simpler concurrent programming (no need for locks!). It also makes it easier to reason about the code since functions are just about transforming their inputs into outputs, and not changing state.

3. Pattern Matching

I love pattern matching! I’m still learning all the intricacies, but it’s super useful to implement guard clauses (for example).
Whereas in Ruby, you might do something like this:

4. Supervisors and running stuff in the background

If you’re used to working with Ruby on Rails, you know that the right way to run long tasks (like sending a bunch of emails or generating a report) is to create a background job with Sidekiq or Resque.

With Phoenix (thanks to Elixir&Erlang), there is absolutely no need for that - instead,concurrent processes (Elixir processes, not OS processes) can be spawned with 1 line of code (spawn(fn -> 2 * 2 end)).

In order to manage these processes, Elixir provides the Supervisor module.

When generating a new Phoenix application, you will have the following supervisor configuration:

Instead, you can just pipe the output of each function and send it as the first argument of the following one with the pipe operator!

[1, [2], 3] |> List.flatten |> Enum.map(fn x -> x * 2 end)

This example was taken from the Elixir documentation. I was lacking the imagination to find an example…

6. Phoenix doesn’t have much hidden magic

There is much less magic in Phoenix than there is in Rails. One of the things you really need to understand is the Plug specification. In Phoenix, the entire HTTP layer is handled internally by a bunch of plugs (note that you can easily add your own!)

Each one of these plugs will receive the request object (conn) and transform it.

7. You need to learn how Brunch works

The Phoenix team decided to use an existing build tool for the assets, which is not a bad idea. They went with brunch.io, which is pretty simple and easy to use, as long as you go through their documentation.

8. Huge lack of tutorials

There is still a huge lack of tutorials and articles on Elixir and Phoenix. I had some issues for which I wasn’t able to find any help, and had to spend a lot of time figuring on my own. I’m planning to write some stuff about them to fill the hole.

9. edeliver and exrm/distillery for deployments?

The commonly accepted way to deploy Phoenix applications is with edeliver and either exrm or distillery. edeliver lets us perform hot-code upgrades which is a cool way to upgrade your application without restarting it.

However, I was disappointed by how slow the deployment was. Maybe I did something wrong, but the generated release would take hours to get copied to the production server…

So instead, I decided to go with Dokku and I’m quite happy with it, even if I don’t have hot-code upgrades!

10. Frameworks should have unique name.

Alright, this last point is a bit of a joke - don’t take it too seriously. I really had this issue with Rails ,but it happened to me more than once with Phoenix: there are too many things named Phoenix!

I can’t tell how often I searched for something in Google using “phoenix” and my query and received results about Apache Phoenix or the city of Phoenix.

Phoenix is not unique enough :’)

The End

I still have many, many things to learn, but I just wanted to share some of the first things I’ve encountered in the past weeks. I will be writing more on my experience with Elixir and Phoenix shortly, so don’t forget to subscribe to the newsletter or the RSS feed.

I’m still a beginner in Elixir so all the information in this article might not be 100% accurate. If you find anything wrong, please leave a comment to let me know.

Last week, I announced that Samurails had been renamed as Devblast. In this post, I’m explaining the change of name, but also more importantly, why I decided to build this new version of the website from scratch using Elixir and Phoenix rather than Ruby (which I’ve been using for the past few years).

The short story of Samurails

Samurails was the programming blog I created 3 years ago to publish tutorials about web development, and more specifically Ruby. I’ve had many ups and downs with it, sometimes forgetting about it for months on end. When I first set it up, I used Wordpress. After all, it was the easiest solution and I wanted to get started writing ASAP (to avoid losing my motivation). I wasn’t aware of static generators at that time.

My Wordpress installation was good enough at first; I was writing some articles and tutorials once in awhile. But eventually I started to be annoyed by some stuff that I couldn’t really fix. I mean, I could have if I had really wanted to, but I would rather not use PHP or touch the code of a Wordpress theme. So I hacked what I could together and used external services for everything else.

But recently, I realized I’d had enough. I was stuck with a website I didn’t like and couldn’t easily expand on.

Going forward, I also didn’t want to limit myself to Ruby on Rails - therefore, “Samu-Rails” wasn’t a fitting name anymore.

Why rebuild?

But I also didn’t want to use a static generator - there are too many limitations, and I have a long list of features to build that need a dynamic backend.

Since I’m a software engineer by profession, this shouldn’t have been a problem - except that I wanted to learn a new technology along the way. I reviewed some of my options and in the end, decided to go with Elixir.

Elixir looks pretty close to Ruby, is functional (something new for me), and has a web framework people sometimes compare to Ruby on Rails. Why not give it a try?

You see, the only times I learned a technology and ended up proficient in were times when I had to build a complete project for work. That’s because learning a new language or framework is hard, and the resulting frustration pushes you to go back to what you know. If it’s for a personal project, it’s too easy to say “I can’t learn Elixir, so I’ll build it with Ruby instead”.

I would be lying if I said the same thing didn’t happen while I was building Devblast. When I hit a wall, I would just stop working on it for the day (or take a long break), and my excitement would be back the following day. Usually after taking break, it only took me a few minutes to figure out the problem that led to my frustration. Duh.

Now that I have a nice Phoenix application powering my website, I’m able to move back the stuff I externalized over time. For example, the landing pages for my books - which are currently on Unbounce - feel slow and are annoying to edit. I’m currently migrating them to Devblast and should be done soon.

I can also create the online interactive tutorials I’ve been thinking about creating for a while. While I’m not a huge fan of videos for learning in general, I understand they work well for some people. For me, they are too passive and I can’t keep my focus. However, with a good written resource, I can just dive in and actively keep reading. For me, it’s a better way to learn (and I don’t think I’m the only one).

Am I the only person who never watched a complete Railscast and just went directly for the ASCIIcast?

That’s why I want to create better tutorials to learn web development actively, using written and interactive content (to validate that a lesson was assimilated). Very soon, I’ll start working on these new tutorials, ranging from the fundamentals (what web development is and why you might want to learn it, HTML, CSS, etc.) to more advanced stuff (JS Frameworks, Ruby, Elixir, etc.).

Why not use Ruby?

Many people have been surprised about my choice to go with Elixir; after all, they know me for having a website about Ruby and having written two books about Ruby.

But as is the case with most things in life, we need to keep learning new stuff or we stagnate.The main reason to make the switch was that I wanted to add a new language to my toolbox. I still use Ruby for work purposes and will probably keep using it for a while - Ruby is definitely not dead (not to mention, it’s still way easier to find a job as a Ruby dev than as an Elixir dev).

There’s a few other advantages - for one, Elixir is faster, and that’s a fact. You might be less productive with Phoenix than you are with Rails, simply because the ecosystem is not mature enough; but eventually, this will improve too.

In short, Ruby certainly isn’t on its way out. However, I do believe that Elixir (and Phoenix) will become more common in the coming years and I want to be ready to help people learn about it.

Why I’m glad I picked Elixir and Phoenix

In the end, I’m super happy I went with Elixir. Devblast feels so, so much faster than Samurails ever was thanks to Elixir itself, caching, CDNs, etc. As a reminder, that’s a comparison between an optimized Phoenix setup and an unoptimized Wordpress, not Ruby.

FYI, the website runs with Dokku on a $20 Droplet from Digital Ocean where I will be adding more applications in the future. I tried to go with eDeliver to have Hot Code Reload, but the deployment process was just way too slow.

What about my next application?

I have two web applications I’m planning to build in the coming weeks/months. One of them will have a React/Node.js stack so I can refresh my skills with these two technologies. For the other, I will most likely use Phoenix, and maybe Elm, after extracting some features from Devblast and turning them into libraries for reusability.

Aaand it’s this time of the year again. In a few weeks, I will be off to France to see my family, eat delicious food cooked by my mom and open the presents under the tree. Along the way I will probably gain a few kilos/pounds that I will lose thanks to New Year’s resolutions. Basically, another year coming to its end.

But enough with the future, you’re probably more interested in the present. Well, I’m happy to announce that my two books, Master Ruby Web APIs and Modular Rails, are now on sale!

Until Tuesday (November 29) at 09:00 AM EST, you will be able to get any of the packages at a reduced price. If you’re interested by one of them, I’d recommend not lingering around too much because there’s a trick. Keep reading to find out.

Here are the links to the book pages if you just want to go check them out right away:

What’s the trick?

That’s the fun part. I don’t just want to do a discount of 30% for the next 5 days (boriiiing) so I’m going to try something new. There will be three different discounts: 50%, 40% and 30%.

For the first 12 hours of the sale (a bit more actually), you will be able to get 50% off. For the following 24 hours, it will go down to 40%. Finally, it will come down to 30% and stay there until the end.

Here’s a summary:

50% Off until 09:00 PM EST, 25 November 2016

40% Off until 09:00 PM EST, 26 November 2016

30% Off until 09:00 AM EST, 29 November 2016

The earlier you buy, the less you pay!

If you’re interested but would like to give it a try for free, why not head to the books pages and grab the free samples? Or keep reading and find out why now is the best time to buy.

Why buy Modular Rails now?

Well, I’m currently writing the new edition of Modular Rails and if you purchase now, you will have access to the new version for free! This new edition will be updated for Rails 5 and include new topics asked for by the readers of the first edition.

Why buy Master Ruby Web APIs now?

Once the second edition of Modular Rails is out, I will go back to Master Ruby Web APIs. The book has grown too much to my liking, so the first thing I’m going to do is split it into 4 different books (with new content added and some rewritten). Each one of them will be sold separately at a lower price, but the combined price will be higher than the current price of Master Ruby Web APIs. Every person who purchased the book will get these new books for free! And since it’s currently on sale, you won’t get a better deal.

What if you don’t like it?

I always offer a 100% money back guarantee for the first 30 days. It leaves you enough time to dig in and see if you like it or not. If you realize it’s not for you, you send me an email and I refund your purchase right away - no hard feelings.

What past readers have to say about the books

Francois van der Hoven on Master Ruby Web APIs

I really enjoyed reading this well-researched book on APIs. I have learned so much from the examples and explanations and will use this book in future as a reference guide.

Florent Guilleux on Master Ruby Web APIs

A very good book about API implementation. All key concepts are covered and illustrated with examples. It is thorough and easy to follow, highly recommended!

@FredAtBootstrap on Master Ruby Web APIs

Read half of it in two days! If you develop REST APIs in Ruby you must read this.

Alvin on Modular Rails

I got modular rails because I was interested in moving from a monolithic app and interested in advancing my knowledge of intermediate to advanced rails. As a guy who teaches at a bootcamp, there comes a time when you want students to move from the usual CRUD nonsense and on to proper software architectural patterns even in the context of a framework. I shared the table of contents with a colleague of mine from the US and he too agreed that this book was the deal. Can’t wait to get more from the author.

Simon Bonnard on Modular Rails

As a classic Rails developer who never had the opportunity to experience the joy of modularity, Modular Rails helped me dive into the subject and start to build from scratch my first modular application. This book definitely fills a much needed gap in Rails literature.

Looking for more details?

I don’t have anything else to say here… check the books pages for more information :)

Resources are mentioned in the HTTP and URI RFCs and are concepts defined by the REST architectural style in the Uniform Interface constraint. In this article, extracted from Master Ruby Web APIs, we are going to define what a resource is exactly.

You probably already have an idea of what a resource is. The term has been used widely, and most of the times pretty accurately, in different web technologies.

After being defined as a part of the REST style, it was pragmatically introduced as the target of URLs (Uniform Resource Locators - RFC 1738) before being extended to URIs (Uniform Resource Identifier RFC 3986) and IRI (Internationalized Resource Identifier - RFC 3987).

Before we continue on resources, let’s define what these acronyms mean exactly.

URI vs URL vs URN

It is important to understand the difference between URL, URI, IRI and URN because they represent different concepts. Tim Berners-Lee defined in RFC 3986 a “Uniform Resource Identifier (URI)” as “a compact sequence of characters that identifies an abstract or physical resource” and claimed that a “URI can be further classified as a locator, a name, or both.”

He also stated that the term “Uniform Resource Locator” (URL) refers to the subset of URIs that, in addition to identifying a resource, provide a means of locating the resource by describing its primary access mechanism (e.g., its network ‘location’).

The only thing that can qualify a URI as a URL is if the latter includes how to find the former. www.google.com/account is not a URL, just a URI. However, http://www.google.com/account is a URL (and still a URI) because it includes the protocol (http://) that can be used to access the resource (www.google.com/account).

URNs are much simpler - they are just names.

An ISBN (like 978-0553293357) is a unique identifier for a book, which makes it a URI, and more specifically, a URN.

Finally, IRIs are an extension of URIs meant to include characters from the Universal Character Set (Japanese Kanji, for example). Indeed, URIs are limited to a subset of the ASCII character set.

HTTP and URIs

In the scope of HTTP, URIs are “simply formatted strings which identify - via name, location, or any other characteristic - a resource.”

A resource is the thing living on the other side of a URI and a URI only points to one resource. That sounds rather abstract, so let’s look at the following example.

http://example.com/users

This URL points to a resource named users. Note that we can never retrieve this resource; instead, we can only get a representation of it as defined by the Uniform Interface constraint. So we can say that a resource never changes, only its representations do.

So how do we name resources? After all, resources are just abstract concepts pointed at by URIs. In theory, it can be anything since naming doesn’t matter to the machine that will be the final client of your web API.

But we must also consider that we are building for human beings and we are still far away from removing developers from the equation. Since we are building web APIs for humans, who will use them to implement their client code, we should use concepts and semantics that they will understand. This follows the same principle used in naming resources for websites.

The following is based on the best practices to build an easy-to-use API, and not really on web standards.

If I want to represent the concept of a list of users, I would just use the pluralized word users, which is just a noun. Making a request to this URL would return a representation listing a bunch of users. Anyone would be able to understand this, and seeing the representation will just confirm their idea about this resource.

With the URL below, we are getting a list of users.

http://example.com/users

Verbs VS Nouns?

But shouldn’t we call it http://example.com/get_users, so people understand it more easily?

The answer is no, but the question itself is not stupid. We just don’t have to include this get in the URL because HTTP has us covered already. Thanks to HTTP methods, we are able to extract as much as possible from the URI pointing to a resource. The best practice here is to use only nouns for resources, and not include meaningless verbs or words.

Some people prefer to use singular names for their resources, like user. This choice is up to you, but I recommend simply using the plural version. Whatever you decide, stick to it. Don’t use /users and /user/:id in the same API - it’s just confusing for developers. Don’t forget that your goal is to build something easy-to-use for them, not you. Think about them before thinking about what you prefer.

Going further

As said at the beginning of this article, you’ve just read an extract from Master Ruby Web APIs. If you’d like to learn more about HTTP and how to build web APIs with Ruby, feel free to check it out. While the book is targeted at web APIs, you will still learn a ton of ways to improve regular web applications.

That’s it, I said it. It’s the only thing you need to remember from this post. If you’re working with code, you are already somehow testing, right?

Maybe you do it by hand, you know, manually checking that the feature you just added works correctly. That’s a good start!

The problem with manual testing

The problem is that manual testing doesn’t scale. Let’s say you have an automated email being sent out anytime a user signs up. Are you doing it by hand? Of course not, because it doesn’t scale. If you have one new user per day, it might be fine (still, it would be a pain, let’s be honest).

When you have 10, 100 or even 100,000 new users every single day, you clearly cannot handle it manually anymore, so you just write code to deal with it. Now, let’s go back to testing. The example we just saw is a bit extreme when we’re talking about testing, I’ll admit it. Still, testing one feature is fine. Once you’ve added 20, 30 or more features to your application, are you still going to test them all when you change a piece of code?

Your answer is probably no. Personally, I wouldn’t do it (and I didn’t back in the days) because, well, it would take forever. I’d just test the latest feature I implemented, and maybe one that’s related. But I wouldn’t realize that X broke in the Y feature. Damn. Quick deploy on a Friday afternoon for a quick adrenaline rush, and off for a weekend at the beach. What I wouldn’t realize is the broken checkout process - a colossal loss of $1 billion over the weekend.

Scary story, huh?

It’s actually inspired from a real story, but the numbers have been inflated. A lot. Else they would have fired me!

Manual testing has its limits - our limits.

Everything is getting automated in our lives, why not automate the testing of our applications? You know, the applications that we created to automate something else that was too annoying to do manually.

Enter automated testing. It’s nothing new. Been around since people started writing code.

Wait… I don’t know what is “automated testing”!

Alright. Let’s me give you a quick explanation. The idea behind automated testing is to write a piece of code that only has one responsibility: ensure that a specific functionality in your application works as expected.

Automated testing includes the process of writing unit tests and integration tests. While unit tests are meant to test only “one unit” (a single component), integration tests are used to test multiple units, and how they interact together.

Now, let’s take a look at some concrete examples. Say we want to test the #add method in the Calculator class below.

# calculator.rb
class Calculator
def add(a, b)
a + b
end
end

And here is the method we would use to test that the #add method works correctly. We first setup an instance of the Calculator class, before using asset_equal (provided by Minitest), to check that calling calculator.add(2, 4) returns 6 as expected.

Now that you have an idea of what a test looks like, let’s talk about why you would want to write them exactly.

Why write tests?

Spending time writing automated tests may seem counter-productive when you’re trying to push features out as fast as possible. What you need to realize is that automated tests are an incredible useful tool that have a huge range of benefits:

Save time & money

Once you’re good enough, you can actually develop faster by reducing the time you spend interacting with a web browser.

The tests provide instant feedback on your code, allowing quick refactoring, forcing you to write code in a smarter way and reducing the coupling between your components.

Tests will allow you to catch bugs early on, before pushing anything to production.

A good set of tests for an application makes it super easy to introduce new comers to the codebase. They can play around, try to fix bugs or add features and the test suite will tell them if they broke anything.

Tests give you confidence in your code.

A test suite is an always up-to-date documentation for your code. If someone wants to know how a piece of code works, they can just checkout the logic in the tests.

Even if these don’t sound good enough for you, wait until you try it to make a judgement ;)

Going further

Learning how to write tests takes longer than reading an article on the topic. If you’re really serious about making your code better, faster and stronger, you might want to checkout this course I’m building: Rails 5 Testing - Why, Where and How?,

In this tutorial, we’re going to talk about Angular 2 router. We’ll implement a basic Angular 2 application that uses routing to simulate a static site with a navigation menu and a few main sections.

In a static site, the URI generally represents a path on a server. In basic scenario, when user navigates to:

http://static.mycoolsite.com/home/

The server interprets the incoming request and sends the contents of /home folder (most likely index.html) residing somewhere on the server. This almost always requires a page refresh. But when developing SPAs and web applications in general, we want to make as few page refreshes as possible.

However, if we keep the browser sitting on a single URI, we lose a lot of useful and familiar functionalities that browsers provide. Namely the ability to use the history and to navigate to specific points in our app.

How can we address this problem and keep a functioning URI system while limiting the amount of complete refreshes? Angular Router was designed to address this problem - it parses the URI and activates the components associated with a particular route.

Routing app overview

Let’s take a look at our sample Angular 2 application. Here we have a project with a structure that follows the official documentation guidelines.

If you’re used to Angular 1.X, this may seem a bit overwhelming at first. Gone are the days of simply including the angular.js file and be ready to go. Angular 2 is more complex in structure and uses npm modules (node_modules/) registered in package.json. To use them in the browser, we have to use a module loader like SystemJS that is configured via systemjs.config.ts file. In app/ folder we have our Typescript files that are compiled to Javascript and put in dist/ folder (configured in tsconfig.json). Typescript declaration files reside in typings/ directory. index.html serves as entry point to our application.

Making our app ready for routing

Creating the components

To get our application working, we have to create components for each section.

They will be loaded into the view with the help of a router-outlet component. We’ll try to keep those components as simple as possible. They consist of a minimum boilerplate code and a template that serves as content for the sections of our application.

Setting the base tag

To get our application ready to make use of routing we must set our base tag. It tells the browser which base URI to use for relative URI paths. Angular 2 documentation states that it should be placed as the first child of the

tag of our index.html. This path directly relates to our /app folder.

<base href="/">

Creating routes

Now that the components are ready we can start wiring them up to our routes.
Here’s what our finished routes file looks like.

After the necessary import statements, we define an array of Route objects. It tells the router which component should be associated with the given URI path. HomeComponent will serve as the default path, and we’ll use AboutComponent and ContactComponent as two navigable sections.

The routerLink attribute tells the router which route to activate when a user clicks on a given link. routerLinkActive will then apply the specified CSS class (or classes) to the element, giving us a visual clue of the current component.

Making everything come together in AppModule

Now all there is left to do is register our router and our components in AppModule. Let’s register the routing component on the @NgModule decorator like this:

Testing our router app

That was quite a lot of code to set up some basic routing. The difficulty of setting up a base application is a common complaint among new Angular 2 users. But now that we’ve got past that point, let’s test our router.
If you haven’t installed all the necessary package dependencies it’s time to do so now. First, let’s bring all necessary npm modules.

npm install

You may also have to install lite-server and typescript globally for the project to compile and run properly.

By default, lite-server should be running on port 3000. Head over to the URL below.

http://localhost:3000/

We can see that our navigation links are working properly. The URL reflects what section we’re in. The opposite is also true - when we enter the URL directly in the address bar the router parses it and loads the appropriate component.

In conclusion

We’ve successfully implemented routing in our Angular 2 application. We saw how the router can change the state of a Angular 2 application depending on the URI. The Angular 2 team put a lot of effort into the new router and went through multiple iterations across the release candidates.

This article serves as an introduction to Angular 2 routing capabilities. Router also supports more advanced features like route parameters, conditional access to routes (or guards in Angular 2 lexicon), nested routes and asynchronous loading to load components on demand.

If you want to know how the router works in details, checkout this book, Angular 2 Router, written by Victor Savkin - the mind behind this router implementation.

Angular is undoubtedly one of the most popular web application frameworks out there today. It powers countless web apps in the wild, and has cemented its fame as the front-end part of the extremely popular MEAN stack.

A new milestone was added to the history of the framework when the beta of Angular 2 was released in December 2015. It made a dramatic shift towards component-based architecture, rearranged some internal concepts, shunned all backward compatibility with Angular 1.x, and pushed users towards using Microsoft’s Typescript, a superset of the JavaScript language.

All of this created quite a stir in the community.

In this post, we are going to explore the differences between the classic Angular 1.X and the more recent Angular 2. Let’s start by introducing this shiny new version of the framework (currently RC6).

What is Angular 2?

Angular 2 is built around the concept of components, and more precisely, with the Web Components standard in mind. It was rewritten from scratch by the Angular team using Typescript (although you can use it with ES5, ES6, or Dart as well). The digest cycle from Angular 1.X has been replaced by another internal mechanism known as “Change Detection”. This feature, along with other improvements and tweaks, yields a considerable increase in performance (up to 5 times faster, according to some official sources).

A Note On Typescript…

We’ll use Typescript for demonstrating the new aspects of Angular 2, mostly because that’s the way the official documentation is written, and you’ll get the most benefits getting to know Angular 2 this way. It’s also safe to assume that most of the tutorials and articles on Angular 2 will also feature Typescript.

Barebones App Comparison

For simplicity’s sake, let’s take Plunkr’s templates for Angular 1.5 and Angular 2 as a foundation, and weed out unnecessary code and files like README. It’ll feature a simple component/directive called “coffee-machine” that’ll insert the string “Have a nice cup of coffee” in the HTML view.

We will analyze the two projects in the next section, but for now, here are the two projects.

Where are Directives, Controllers and $scope?

Roughly speaking, a component in Angular 2 replaces what was known as a directive and becomes the foundation of any Angular 2 application. Controllers and $scope are gone. Sorry for your loss, but it was changed with a good reason in mind - the rise of the Web Components standard.

Summary

By now it should be pretty obvious that Angular 2 is a completely different and reworked framework. Because of the sheer number of differences, comparing the two is a bit like comparing apples and oranges. Hopefully this article provided some food for thought on the nature of Angular 2, as well as the main differences between the two major versions.

Let’s do a wrap-up:

Angular 2 is a completely different framework, rewritten from the ground-up, and is not backwards-compatible with the previous versions of Angular.

It supports runtime-independent instances which allow more straightforward integration in mobile and native apps.

Angular 2 is written in Typescript and official documentation examples emphasize the use of Typescript, although developers can (and probably will continue to) use ES6, ES5 and Dart.

The syntax for structural directives, local variables and event bindings have changed.

Angular2 has greater performance (at least 5x, and even more in some corner cases) due to the reimagined update loop (aka Change Detection).

A brand new router.

No more controllers and directives, but instead a component-based architecture.

The team behind Angular has boldly decided to completely overhaul it. Whether we like it or not, these changes will push us, as adopters, to consider things like Typescript and Web Components more closely, as there’s no denying the gravitational pull of decisions from giants like Google on the modern Web ecosystem.

It is important to understand the difference between URLs, URIs, IRIs and URNs because they represent different concepts.

Tim Berners-Lee defined in RFC 3986 a “Uniform Resource Identifier (URI)” as “a compact sequence of characters that identifies an abstract or physical resource” and claimed that a “URI can be further classified as a locator, a name, or both.”

He also stated that the term “Uniform Resource Locator” (URL) refers to the subset of URIs that, in addition to identifying a resource, provide a means of locating the resource by describing its primary access mechanism (e.g., its network ‘location’).

The only thing that can qualify a URI as a URL is if the latter includes how to find the former. www.google.com/account is not a URL, just a URI. However, http://www.google.com/account is a URL (and still a URI) because it includes the protocol (http://) that can be used to access the resource (www.google.com/account).

URNs are much simpler - they are just names.

An ISBN (like 978-0553293357) is a unique identifier for a book, which makes it a URI, and more specifically, a URN.

Finally, IRIs are an extension of URIs meant to include characters from the Universal Character Set (Japanese Kanji, for example). Indeed, URIs are limited to a subset of the ASCII character set.

I hope this little tip about the differences between those different acronyms help you to see clearer.

You may be wondering about the difference between scope and namespace for the routes in your Rails application. It’s important to know the difference, because they affect the path of your resources and the controllers.

namespace

This is the simple option. When you use namespace, it will prefix the URL path for the specified resources, and try to locate the controller under a module named in the same manner as the namespace.

As you can see, admin was added as a prefix in the URI path (/admin/users) and as a module containing the controller (admin/users#index). With this code, Rails will expect Admin::UsersController to be located at app/controllers/admin/users_controller.rb.

scope

scope is a bit more complex - but the advantage is that it gives you more options to fine-tune exactly what you want to do.

No Options

When using scope without any options and only a scope name, it will just change the resources path.

Rails 5 was finally released, so it’s time to do an overview of all the awesome new stuff we’ve got to play with. The first thing I want to talk about is the brand new Rails 5 API mode - it lets us build web APIs without all the clutter usually included in the controllers.

What’s a Web API?

APIs are Application Programming Interfaces – basically, an interface for two softwares to communicate. Web APIs are the same thing, but are usually accessible in the World Wide Web through HTTP or similar protocols.

Web APIs are often added to web applications to offer a programmatic way to use features or retrieve data. These days, it’s also quite common to build web APIs that will only be used as backends for mobile or JavaScript applications.

Web APIs usually offer JSON (or XML) representations instead of HTML. JSON documents are easier to understand and use for an automated client, like the ones mentioned above.For example, Reddit offers a public API.

A Short History

This new feature doesn’t come out of nowhere. It’s actually the Rails-API project that was merged into Rails 5.

The discussion thread on GitHub, initiated by DHH but encouraged by Santiago Pastornio, is interesting to follow and available here.

How Does It Work?

This will create a stripped-down Rails application with a smaller set of middleware. It will also configure the generators to skip the views/helpers/assets and change the parent for ApplicationController from ActionController::Base to ActionController::API.

The following line is added to the config/application.rb file, and sets the application as a web API only:

After that, the development is pretty similar to what you’re used to with Ruby on Rails. You won’t have views, helpers, or assets because all of these will be off-loaded to the clients. To replace views, you will probably want to use some kind of serializers to build the JSON documents.

Why Use Rails API Mode Instead of Sinatra or Grape?

People often wonder why use Rails to build a web API, rather than something smaller and simpler like Grape or Sinatra. While those frameworks are fine for small applications, you will quickly find the need to add libraries in order to add some mandatory features like an ORM, some representation builders, an auto-reload feature, etc. In the end, you will have something as big as a Rails application, just made up of various libraries.

That’s not necessarily a bad thing. With this approach, you can pick exactly which gems you want to use. But deciding to go with Rails is also a viable alternative, since you get all those features from the get go.

Plus, Rails handles a lot of stuff that you may be used to, and that you won’t find in smaller frameworks (security, conditional GETs, caching, etc.).

When Should You Use It?

You should only use Rails 5 API mode if your application is a web API. This means you won’t be sending HTML representations, but instead only JSON (or XML) which will be used by automated clients.

Differences From a Traditional Rails Application

Outside of the lack of views, helpers and assets, the two main differences between Rails APIs and regular Rails applications are the middleware used and the module included in the controllers.

Middleware

Rack middleware are an implementation of the pipeline design pattern, and are heavily used in Ruby on Rails to perform actions on the request and response objects.

By default, a Rails API-only application comes with a limited set of middleware. This is meant to increase the throughput by removing unnecessary functionalities.

Adding a middleware is as simple as adding a new line in the application.rb file. For example, if you’d like to add Rack::Deflater to your API:

You can see the list of middleware used in your Rails application with the following command:

rails middleware

You can learn more about the middleware included in your application here.

Controllers

The ActionController::API, from which the ApplicationController inherits in an API-only application, also comes with fewer modules than the regular ActionController::Base.

This allows requests to be processed faster and reduce the response time of your web APIs.

Going further

If you want to dig deeper into Rails 5 API mode, take a look at Master Ruby Web APIs. In this book, you will learn the basics of building web APIs with Sinatra before going on to build a complete e-commerce API with Rails 5 API mode.

]]>
Mon, 26 Sep 2016 00:00:00 +0000http://devblast.com/b/rails-5-api-mode-overviewhttp://devblast.com/b/namespace-controllers-rails
Namespacing controllers in a Ruby on Rails application is a great way to isolate different features: invoicing, authentication, etc. It’s also pretty simple to implement, so there are no reasons not to do it if you need it.

The End

Email marketing tools are fundamental for anyone trying to make a living from a blog. Having a mailing list allows us to stay in touch with our audience - without spamming people, of course. Since the beginning of this blog, I’ve been using Mailchimp. Before releasing my new book, Master Ruby Web APIs, I decided to switch to ConvertKit to handle the launch.

I wanted to explain why I made the switch at such a crucial moment by presenting the differences between the two tools.

This article contains affiliate links, which means I will get a commission if you purchase something using them (at no extra cost to you).

Why build a Mailing List?

Before we talk about the actual tools to build and manage mailing lists, I want to tell you why you should be building a mailing list for your blog or your website in the first place. Whatever you are doing online, you need to interact with your audience, right? You can use Twitter, on Facebook or any other social media platform - but the best way to communicate directly with your audience, with the people who are interested in what you have to say and share, is through emails.

To be able to send emails, you first need the email addresses of your regular readers. Generally, people who like what you are writing or doing will give you their emails, if you ask them nicely. You just need to give them a place to enter it - with forms on your website or on your landing pages.

Once you have their emails, you will be able to build trust, and with time, build a relationship. In order to do that, you will need to give them value: tips, free content, or opinions. Once in a while, you can also promote your products, if they contain value for your subscribers.

That’s also when you’re going to make some money.

A mailing list is a fundamental and absolutely awesome tool for any blogger.

Starting Out With Mailchimp…

First, let’s talk about Mailchimp - one of the top email marketing tool today. It’s the one people usually get started with, because they offer a free plan as long as you have less than 2000 subscribers.

I was quite happy with the free plan, until I tried to implement some automation (e.g. sending a series of emails when someone signs up). To be able to start using this feature, I had to start paying $20 - which I did.

But at the end of the day, even Mailchimp’s paid features were never fully satisfying to me. For one, I wasn’t able to easily integrate with Gumroad when a subscriber purchased a product (maybe it’s possible, but I just never found out how). And I was paying more if the same subscriber was in two different list. These are just two examples on the top of my mind.

After a while with Mailchimp, I realized it just wasn’t meeting my needs - and I decided to look around and see if there was a better system out there.

… Before Switching To ConvertKit

ConvertKit is a marketing tool specifically designed for professional bloggers. It was created by Nathan Barry, whom I’ve been following for a few years now. ConvertKit was a bit more expensive than Mailchimp, which led me to avoid it for a long time - that ended up being a big mistake.

Around Christmas 2015, I was able to use ConvertKit for free for a month, and I quickly fell in love with it.

Everything was so simple and easy to use, and the automation feature (based on a “if this - then that” system) was a delight. It made managing my subscribers and interacting with my mailing list effortless. Sure, I now pay a bit more, but it’s so worth it. Read further to see the features that I can’t live without in the next section.

For info, ConvertKit starts at $29 for 1000 subscribers or less. Check the slider on this page to know how much you would have to pay.

ConvertKit Features I Love

In this section, I’m going to share some of the features ConvertKit offers that helped me to start making a living from my blog.

The four features I want to talk about are the management of subscribers, the broadcasts, the sequences and the automation. Well, that’s almost all the features of ConvertKit actually…

Subscribers

With ConvertKit, subscribers are collected through forms, like this one. By the way, it’s a real form, so feel free to subscribe if you want to hear more from me ;)

Forms can easily be embedded anywhere you need them. For places where you can’t embed anything, it’s super easy to integrate Zapier. That’s what I do for my landing pages made with Unbounce. This way, email addresses are sent to ConvertKit through Zapier.

After that, you have a list of forms that are linked to the subscribers who used it. Contrary to Mailchimp, subscribers are shared (so you don’t pay double) and you can access the global list by checking the “subscribers” page.

Broadcasts

The first step before sending a broadcast is picking the people you want to send it to. See the screenshot below to see how this process happens. Basically, you can pick anything (a form, a sequence, a tag, etc.) and include the matching subscribers. Note that you can also exclude subscribers if you want to. That’s super useful when you want to send an email targeted towards a more specific audience; for example, to market to subscribers who haven’t yet purchased your product.

The next step is pretty simple and consists in writing the actual email.

Sequences

Sequences are perfect to teach your subscribers in an automated way. For example, once someone subscribes in order to receive the free chapter from Modular Rails, they are automatically subscribed to a sequence that will teach them more about modularity and how they can use it.

Automation

The automation system in ConvertKit is awesome. You just pick a trigger and an action, and that creates a new rule. That’s it - it couldn’t be easier.

The End

Want to give ConvertKit a try? Learn more about it and sign up on convertkit.com!

I released my second book, Master Ruby Web APIs, a few weeks ago. In this post, I want to come back to the creation process and share a few tips with you. I believe anyone can write a book and self-publish it the way I did, and I hope you will get some motivation from this post. While it’s far from easy, it comes with a lot of benefits that can make a huge difference in your life.

Why Write A Book?

Starting and finishing a big project is a rewarding experience. However, it seems to be complicated these days for people to do that, myself included. With new stuff flooding our devices every day, keeping our focus on the one thing that matters is becoming excruciatingly hard. But with the use of simple techniques and habits, it’s possible to do anything - the first time you do it, you’ll will prove it to yourself.

I wrote this book because I had something to share: how to create Ruby web APIs based on the industry standards and best practices. I know it’s going to sound cliché, but this is the book I wish I had before I built my first web API.

I’m not going to lie, though - I also wrote this book to earn money. I’m trying to start a business, and what I’m earning from the book will allow me to bootstrap it and get things going.

To summarize, I wrote this book for three reasons: to prove to myself that I could do it, to provide something useful to the Web community and to make a little income.

Self-Publishing

I’m self-publishing Master Ruby Web APIs, just like I did for my first book, Modular Rails. I chose self-publishing for a number of reasons.

First, let’s not forget that I would probably never get a contract with an editor. Even if I could, I would still prefer self-publishing.

Pros

Self-publishing gives you more control. Actually, it gives you complete control. More ownership, more work, more rewards!

It’s an awesome learning experience. I had to learn more about marketing and copywriting in order to be able to make some sales.

Royalties from publishers are usually quite low. With self-publishing, you get more than 90% of the sale price.

Cons

Self-publishing also comes with a few cons.

You have to do everything, including writing, coding, editing, marketing, or hiring people to help you with all the above. It can be very stressful to have no one else to rely on.

You need to handle the review part of your book. You can always do it yourself, but a better option is to hire professional reviewers (or force your friends to read it).

Without a publisher, you will have a much smaller reach. That means fewer sales (even though you’re getting more out of each individual sale).

You need to handle the marketing which requires a lot of work. It includes building the landing page, sending emails, creating promotion materials, etc.

Now, let’s talk about the book itself, and the interesting part - how I wrote it.

The Landing Page

The first thing I did was set up a landing page about the book. This happened a year before the release, right after I published Modular Rails. After that, I didn’t do anything.

It wasn’t a strategy or anything like this, I was just busy with work and I didn’t find the time to get started. Fast-forward to a year later, when I decided to quit my job.

Over the past year, and without doing any promotion, I collected around 50 emails from people who were interested in Master Ruby Web APIs. It wasn’t that many, but to be honest, I didn’t really do anything to make it grow. Shame on me.

However, I did have the general mailing list from Samurails (my previous blog), and my first book, which altogether amounted to around 1000 people.

The original landing page was pretty simple. Since I’m using Unbounce to create my landing pages, I was able to find the pre-release version.

The first version

Quick plug for Unbounce - I could have totally created my landing page from scratch. However, I prefer to use and pay for a service like Unbounce because it makes it much easier to build different variants super fast. The a/b testing feature is also a must.

With the pre-release landing page ready, I needed a place to store the email addresses safely.

Collecting Emails

I’ve been using Mailchimp for a while now - ever since I first started collecting addresses on my blog, Samurails (before it became Devblast). It helped me launch my first book and send tutorials and articles to people who wanted to read them.

For my second book, I decided to keep using the tool that I knew. I was already paying for Mailchimp to use the automation feature, so it seemed like the best choice.

But another mailing marketing tool caught my eye. I’ve been following Nathan Barry for a long time, and I wanted to try the application he created, ConvertKit. The main difference between ConvertKit and Mailchimp is the way subscribers are handled. In ConvertKit, subscribers belong to forms, and broadcasts can be sent to a specific set of forms. There are also sequences, and an awesome automation system where pretty much anything can be automated.

After giving it a try, I completely switched to ConvertKit and I’m super happy with it.

Getting Started

Now we’re getting to the juicy part.

How the hell do you write 120,000 words and organize them in a compelling manner?

A journey of a thousand miles begins with a single step.

Well, just like any journey, you start with the first word. Then, you write the second, and so on. When I’m working on a book, I don’t spend too much time thinking about what I’m writing - I just let everything out. There is always time to organize, edit and improve on your raw material later. The first goal should be to have some meat to work with.

I find it’s better to work by iteration than to try to get it perfect on the first draft. If you’re more concerned about perfection rather than getting your thoughts down on paper, you’re setting yourself up for the dreaded blank page syndrome.

Sadly, I wasn’t getting my quota of words out every day. I needed to change something.

After procrastinating for a while, I finally decided to set some rules. I was going to write for at least 10 pomodoros per day. Until I set this rule, I had no idea how long I actually worked every day. Maybe 1 hour, maybe 5. Who knows? (It was probably closer to 0 or 1 hour though).

Sticking to this rule, I was able to produce a good amount of content for the book. The problem was that the book kept growing, and I wasn’t seeing the end.

I thought the book would be around the same size as my first one - ~ 200 pages. In the end, it grew to around 750 pages. This brings me to…

The Book Organization

I wanted to put a lot of things in this book - everything I had learned about web standards, RFCs, best practices and so on. To best organize these in the best way, I decided to divide the book into three modules:

Talking about the basics and building simple APIs with Sinatra.

Building a complete Rails 5 API and do everything from scratch, from scratch.

What REST really is, and why the API we built in the second module doesn’t respect all REST constraints.

Each module had a goal. The first one was meant to introduce the reader to the concepts of the World Wide Web, HTTP APIs and Sinatra. With these concepts, it was possible to start building something more complex, like an e-commerce API with all the necessary components, such as a way to handle authentication, authorization, security, payments, and more.

Writing the first module was actually fun. I went to Penang, Malaysia, for a week and kept writing there, from coffee shops. It reached 25k words before I decided it was complete. The chapters covered a wide range of topics like versioning and caching. At this point, the book was as big as my first one. Maybe I should have stopped there. But I wasn’t happy - it wasn’t enough to “Master” Ruby web APIs.

The second module was meant to go deeper into explaining how things can be done for real world applications. I also wanted to share some knowledge about Ruby and how the language could be used to build everything needed, from scratch (yes, from scratch!). To do this, I decided to create specialized classes to handle the generation of the JSON representations instead of using something like Active Model Serializers or JBuilder. My goal behind this approach was to show how things are made in those gems. I believe that if people have an idea of the underlying functions of these libraries, they can make better use of them.

Not everyone liked this approach, and one person even complained about it, saying it wasn’t necessary and too complicated. That’s fair. It’s an approach that I thought was valuable, and that I wanted to have. Because this might not be everyone’s style, having a free sample of the first few chapters was really important, allowing customers to see how I write before they purchased the rest of the book. If someone is really unhappy with their purchase, I offer complete refunds, of course.

While I used Sinatra in the first module, I decided to go with Rails 5 and its new API mode for the second module. Some people also questioned this choice: Isn’t Rails slow? Why would you use Rails for a web API instead of Sinatra or Grape?

The thing is that most of the logic for a web API, just like a regular application, is not in the view layer. Having Rails conventions and features is great to keep complex applications organized. I wanted that to ease people into the module, but I also went the Rails way when I had to.

All things considered, I ended up being really happy with the second module. I used a TDD-like approach in it to show that automated tests matter, and will generally make your life simpler.

Finally, let’s talk about the last module. To be honest, it didn’t turn out as good as I had hoped. But I was running out of time, money and energy after completing the first two modules, which totalled a whopping 100,000 words. In this last module, the goal was to dig deep into REST and what it is. Then I explained why Alexandria (the app built in the second module) was missing a few of the REST constraints. After that, I showed how the application could be improved by adding the Hypermedia constraint.

This module can clearly be improved, and it will be. I’m planning to add chapters to that last module to improve it. Anyone who buys the book will, of course, get these for free. While the third module is lacking, I believe it’s still a very important read for any web developer. Understanding that REST doesn’t simply equal using HTTP verbs and resources is fundamental.

Master Ruby Web APIs will evolve with time.

The Tools

My writing setup is a bit peculiar. I came up with it right before publishing my first book because I wasn’t happy with anything else.

I use Markdown to write all my books. I actually use Markdown for everything these days, including this article. I just love it. To structure and generate the book, I used the Softcover gem.

Getting reviewers

If you’re self-publishing, you need to collect some early feedback before releasing. I asked some of my friends to read the book when they had time - only one of them actually finished it. I also decided to hire a native English speaker from Upwork to review the content. She provided some great feedback and helped me improve the book.

Recording Screencasts

Just like my first book, I’m using a tiered pricing structure with three packages. The biggest one includes a bunch of bonuses like screencasts and additional resources. The medium package is just like the complete package minus all the video content. Finally, people can decide to buy just the book for $39.

I recorded the screencasts with Quicktime on my Macbook and edited them in iMovie. I’ve since learned how to use Adobe Premiere and will be using it in the future.

Releasing with Gumroad (During A Power Outage)

After around 2 to 3 months of work, Master Ruby Web APIs was finally ready - not perfect, but ready for a first launch.

If you are not embarrassed by the first version of your product, you’ve launched too late.
— Reid Hoffman, founder of LinkedIn

I was definitely embarrassed and was wondering if anyone would pay for it. After all, who am I to teach people?

I launched anyway, fighting off all the doubts and thinking about the next day where I would finally be able to relax a bit. I uploaded everything on Gumroad, shared the link on a few outlets (ProductHunt, Reddit, HN) and sent an email to my complete mailing list to announce the release.

No sales came in the first 30 minutes.

After that, a complete package. Then, a book. Then, another complete package. I was too excited to sleep. I was finally beginning to see the result of the past 3 months of work. I was checking my phone every 5 minutes, and sales kept coming in.

No matter how exhilarating the first 24 hours were, I think it’s important to manage your expectations My “great” might be much lower than what you have in mind. After all, I’m living in Thailand where life is cheap. After one week, and the end of the release promotion, I earned enough to justify the time I spent on the book.

The thing with books is that most of the income will come at the release - the amount needs to be big enough to live until the next project is ready.

Funny story, the day I was launching, there was a power outage in my area - and not a small one. Electricity was out most of the day. I was able to use a friend’s place to spend the night and release the book. Talk about stress!

The Result

I originally wanted to share the amount I earned from the book, to motivate people who want to get some extra income or change their lifestyle. But after reading here and there, I decided that it was maybe not the best approach. If you really want to know how the book did, feel free to contact me.

I got so much more than just money from releasing this book. I acquired new skills, met awesome people and added a new product to my portfolio. :)

The Future

I’m publishing this article two months after the release. Things have calmed down, and I had time to think about what I’m going to do next. It won’t be a book. I’m still planning to write some, but not right now.

In the future, when self-descriptive hypermedia web APIs have taken over the world, we probably won’t need to write out-of-band human-readable documentation anymore.

But we are not there yet.

For now, writing documentation is still a fundamental part of publishing a web API - and your API will only looks as good as your documentation makes it. That’s why I want to share with you 10 ways to create a documentation that is easy to use for developers.

Most of the rules are common sense, but it’s easy to forget some of them.

1. Document all resources

Your entire API should be documented. That means all the developers-facing resources should have clear instructions about their use.

2. Keep your documentation up-to-date

If you don’t follow this rule, there is no point following the others. A documentation that is not up-to-date is pointless, and will only cause frustrations for your users.

Always ensure that new features or changes get documented. This can be made automatic or, just like automated tests, can be a requirement for any pull request. You wouldn’t create a pull request without tests, right?

3. Provide copy/paste examples

Developers like to test before they implement something. Offering an easy way to copy/paste curl requests is a good way of doing that. If developers are logged in, you can even include their API key directly in the documentation making it even easier for them to test your endpoints.

Other tools, like Swagger and Swagger UI integrate that feature in a web page and make it simple to send HTTP requests (as long as your API allows CORS requests).

4. Show expected responses

Developers should be capable of understanding the request flow based only on your documentation. Theoretically, they should even be able to implement a client for your API without actually making any request. This means you need to show them what is the expected output for each documented request.

5. Provide a “Getting Started” guide

The documentation for your API is going to be a great reference for all the features it comes with. Sadly, it’s easy to feel overwhelmed without a simple tutorial to get started.

A “Getting Started” guide should be available for your API to, at the very least, show how to get an API key, write the first request and get a response back.

6. Put yourself in the developer’s shoes

When you’re building a web API, you usually build for other people, not for yourself (of course, there are exceptions). Well, put yourself in someone else’s shoes, forget everything you know about the API and try to make some requests using only the documentation you wrote.

7. Validate your documentation before releasing it

The previous rule is only good to a certain extent. You can do your best to pretend that you don’t know anything about the API, but there’s going to be some stuff that you will miss. Even something you might think is common knowledge could cause a lot of frustration for implementers.

To validate your API, take a pool of developers and make them read the documentation. They should be able to understand how everything is structured using only the documentation, and without asking you any clarifying questions. Ask them to create a small program accessing one resource and do something with the result as a test.

Improve the documentation based on their feedback.

8. Create SDKs for your API

SDKs allow you to abstract the communication with your API, hiding the complexity and the HTTP calls so developers can simply use their favorite programming language to talk with your service.

9. Communicate with your API users

Developers rely on your API and expect it to simply work. If something breaks, they need to know ASAP. That’s your responsibility to tell them when something goes wrong or when changes are coming.

You can let your community know what’s happening using a blog, a newsletter, a changelog or a combination of the three.

If you open your API to a lot of people, you should also have a place for them to chat about it, ask for help, suggest features, give feedback and report bugs. This kind of platform will help you improve your API and make it better using your users’ ideas.

10. Set up a status page

One day, your API will go down for some unknown reason. When it happens, people who rely on it need to know that there is something wrong on your side and that you’re working on fixing it.

A status page is the perfect way to accomplish both of these objectives.

Wrap Up

To go with the great documentation you created, you need to have an awesome web API running in the back. If Ruby is your favorite language to create this kind of application, you will probably be interested by the book I wrote: Master Ruby Web APIs. I just released it and it’s 20$ Off until July, 20. Don’t miss out!

This is a fairly typical request test checking that an endpoint is working as expected. But there is a big problem in there! There are 4 different expectations testing very different things under a very generic name: gets a list of products.

We could fix this test by splitting it into smaller and smarter tests. In the code below, I’ve separated the expectations in 3 different tests and I tried to follow one of the testing motto I love: “One Expectation per test”.

RSpec.describe "Products", type: :request do
# create some products
let(:json_body) { JSON.parse(response.body) }
describe 'GET /products' do
before { get '/api/products' }
it 'gets HTTP status 200' do
expect(response.status).to eq 200
end
it "receives a list of 3 products" do
expect(json_body.size).eq eq 3
end
it "receives the products sorted by 'id desc'" do
expect(json_body.first.id).to eq 3
expect(json_body.first.id).to eq 1
end
end
end

You will notice, however, that the last test actually contains 2 expectations. What the heck? I just said that there should only be one expectation by test! That’s true but in the last test, we are actually testing the same thing with both expectations.

The goal here was to show you that it’s fine to have more than one expectations in one test as long as they are testing the two sides of the same coin. I would still recommend avoiding doing it and stick to the “one expectation per test” principle.

The benefits of writing tests this way are numerous. Not only it becomes easier to read through the tests but when something starts failing, it is much easier to identify exactly the cause. Indeed, you will instantly know which expectation is not working properly and can fix it quickly.

The main drawback with this approach is that it might make your test suite slower. While one expectation per test is perfect for unit testing, it can become a problem for slow integration testing. In those situations, you will need to find the right balance between speed and expectations.

I learned about guard clauses thanks to Rubocop, the super annoying yet awesome code analyzer. I started refactoring my code everywhere Rubocop told me a guard clause would be better.

Why would it be better? Because guard clauses are an awesome way to make a piece of code more succinct and understandable.

Code explains better than words, so let’s take an example. Checkout the method below.

def my_method(variable)
if variable == 'great'
# do something great
else
return nil
end
end

As you can see, this is a relatively common method where we check if the passed parameter matches our expectation. If that’s the case, we ‘do something great’, if not we return nil.

In reality, we can write this code in only two lines with a guard clause. You see, guard clauses are named like this because they protect some code from running unless a condition is met. They are usually used to ensure that the parameters that were passed meet some criteria to avoid running into exceptions or other problems.

Those examples were pretty simple so you could see how easy it is to use guard clauses. For more complex code, they can be used to prevent a bad code smell known as nested conditional. That’s when a method has a bunch of conditions making it hard to read through it and understand the flow of execution.

To have an idea of what a nested conditional nightmare is, take a look at the code below. What do you think?

def pay(invoice)
if invoice.paid?
return nil
else
if invoice.delay_payment?
invoice.set_delayed_payment_date
else
if invoice.amount > 1000
invoice.trigger_manual_payment
else
invoice.pay
end
end
end
end

I personally don’t like it at all! It’s hard to read and understand exactly what’s going on. What about the alternative below?

After digging into REST and various RFCs, I’m really wondering why developers still call their APIs “RESTful”. Who was the first guy who decided to pin “RESTful” on his API? Did he actually read Fielding’s dissertations? I have my doubts…

Disclaimer: I’m not going to tell you to create RESTful APIs. The goal of this article is to make you stop calling your APIs RESTful when they are just HTTP APIs. If you really want to call your API “RESTful”, start by building one.

If you go full berserk with REST (as you should, because there is no middle-ground), you will not find a single web API that respects all the constraints. This means there are not RESTful APIs.

REST constraints define how the World Wide Web works (or should work in an optimal way). Those constraints were put together more than 15 years ago when most of the HTTP requests were sent by browsers with human ready to understand the representations and take decisions. These days, web APIs clients tend not to have the human component anymore. Instead, decisions must be programmed. This usually creates a tight coupling between client and server which can be partially reduced by applying the hypermedia constraint.

Web APIs clients (e.g. programmed iPhone app) are not the same as websites clients (e.g. web browsers) which delegate all decisions to humans.

Most websites and web applications are not actually truly RESTful. Cookies, used by pretty much everyone for sessions, clearly violate the Stateless constraint of REST. At least, nobody calls their website RESTful so people can’t come and say:

REST is a good set of constraints defining the characteristics of the optimal application for a distributed hypermedia system, like the World Wide Web. After all, Fielding put those constraints together so people could improve the World Wide Web and create applications that are scalable, performant, fault-tolerant and extendable.

The more constraints you follow, the stronger your web API becomes and the harder it becomes to create. But, as I said earlier, there is no middle-ground in Fielding’s dissertation. You either follow all constraints and build a RESTful application or you don’t. Period.

What I’m saying here is nothing new. A lot of people have pointed it out before. Sadly, most people still don’t understand REST. Fielding himself said how annoyed he was that REST became the buzzword it is today.

Once again, what is REST?

REST, or REpresentational State Transfer, is an architectural style made up of a set of constraints for distributed hypermedia systems like the World Wide Web.

REST was defined in Roy Fielding’s dissertation. It’s not a standard. It’s a smart guy’s dissertation about how things should be designed in a distributed hypermedia system.

There are 6 constraints in the REST architectural style:

Client-Server

Stateless

Cache

Uniform Interface

Identification of resources

Manipulation of resources through these representations

Self-descriptive messages

HATEOAS

Layered System

Code-On-Demand (optional)

I won’t go into the details of those constraints in this article but there will be one coming soon that explains each constraint with easy-to-understand examples.

Quick note about REST vs RESTful. REST is the name of the architectural style while RESTful is a wrongly and overused adjective for web APIs.

The REST vs SOAP nonsense

People often put REST in opposition to SOAP. Indeed, you can see many articles and Stack Overflow questions with ‘REST vs SOAP’ in the title. The good news is that most of these results are quite old so things seem to be getting better. \o/

What they really want to say is that they are building an API that relies on HTTP instead of a specialized protocol used for web services like SOAP. Basically, they are building an HTTP API.

SOAP actually relies on HTTP (or SMTP) for data transmission, therefore, a SOAP API can be called an HTTP API. Luckily, they are called web services and are slowly disappearing from the surface of the Earth.

By the way, REST is protocol-agnostic so it does not have any close relation with HTTP. You could use any transfer protocol (SNMP, SMTP, etc) and still call your API RESTful (if you are respecting all the constraints of course).

What people think RESTful applications are

I did a bit of research to see what people consider a RESTful application these days and my conclusion is that a lot of people don’t understand REST. I’m not saying that’s your case and I really hope you know what REST really is.

First, developers always associate REST with HTTP. When they say they are building a RESTful API, you can be sure it’s just a basic HTTP API. We’ve seen above that it’s simply not true. Any transfer protocol can be used to create a RESTful API.

Another misconception is the use of HTTP methods to retrieve, create, update and delete entities on the server. This has nothing to do with REST itself and is simply part of the HTTP RFC.

Next, people think that defining nice URIs for resources, like /users or /users/1, falls under REST constraints. REST, just like HTTP or the URI RFC, could not care less how you name your resource identifiers (URI stands for Unique Resource Identifier). All they care about is that they are unique. It could be /MySuperUsers, /fkofekdl or [2001:db8::7]/c=GB?objectClass?one and it would be alright. Obviously, you and I, we wouldn’t like it. We want to understand what is the resource represented by the URI and to do that, we give them good and simple names. That’s a best practice for HTTP APIs and we can make super clean URIs thanks to the use of HTTP methods (GET, POST, etc). No need to call anything /get_users for example since GET /get_users would be quite redundant.

Did I forget anything about how most people see RESTful applications? Please let me know in the comments! From my short research and my personal experience, those are the 3 that came up the most.

In The End, It doesn’t even matter.

You don’t want to apply all the REST constraints? Fine, just don’t call your API “RESTful”. I don’t really care about what you are actually building. On the other hand, I kind of care about overused buzzwords. For some reason, it tends to really annoy me.

No, your API is not RESTful, end of the story. There is no pragmatic RESTful, dogmatic RESTful and no RESTafarian. Those terms are just meaningless to be honest. They were just made up by people who don’t understand REST or HTTP. :/

You’re either building an HTTP API following best practices or you’re building a RESTful API.

The good news is that no one is going to scream at you for building a non-RESTful API: everyone is doing it!

Let’s take an example. We talked earlier about cookies and how they violate REST Stateless constraint. Likewise, a RESTful API should not have any session mechanism where the client state is kept on the server. So if you have /login and /logout in your API, you are breaking the Stateless constraint. If creating a real Stateless authentication system is too much of a pain for you, then don’t. You know what I’m going to say now: just don’t call your API RESTful ;)

You can keep calling your APIs RESTful but at least now you know that you’re wrong: just call it what it is, an HTTP API. Nobody will judge you and you will help stop the buzzword propagation.

Do you really want to build RESTful APIs?

Building RESTful web APIs is not easy. The good news is that you don’t need to be REST-compliant to build awesome APIs. Just look at all the web APIs available today. While they are not RESTful, the businesses behind are still thriving, providing services and making money.

Obviously, they had to compensate the areas where they are lacking and not following REST constraints. Let’s take scalability for example. The Stateless constraint allows an application to grow more easily since the server is not keeping any state of the client. In reality, keeping the client state can often be a requirement. That means that developers need to handle more complex clusters of servers with interconnected stores for client states… It’s more complicated indeed but if it means making more money for a business, I’m guessing they will be fine with the AWS bill.

Your API does not have to be RESTful to be awesome.

So how should you call your API?

Call it what it is and not what it’s not. Web API or HTTP API is probably a good fit. Throw in ‘awesome’ in there if you’ve built something great!

At all my previous jobs, I’ve worked with web APIs. Either as part of a web application or just on their own, acting as backends for mobile games played by millions of people. My problem was the war that’s raging in the web API community on how to do things.

So I decided to dig into it and read as much as I could about a variety of topics: the Internet, HTTP, Web Standards, versioning, resources and a lot of other stuff, including the dreadful REST.

I learned a sh*t load of stuff, things that nobody teaches you at the university and that you’re too busy learning when you have a job (or too lazy…). I had a much better understanding of the web API War.

This API War is happening between two camps, the pragmatic developers who build web APIs for a living in stressful/startup conditions and the dogmatic academic who also build web APIs for a living (I think) but also participate in the creation of web standards. Working on web standards makes you see things within a bigger picture and on a much longer term. Unfortunately, it also tends to take you further from the day-to-day developer lifestyle.

That’s why people always pick a side when they fight over how to build web APIs. Different visions, different goals. But that’s good, it pushes people to take their thinking further and put in question what they know.

I’m not even going to talk about websites but even they are not 100% compliant with the RESTful constraints (think cookies/sessions, for example, that go against the stateless constraint). Plus, websites are just web APIs that outputs HTML; your browser is a software last time I checked, even if it delegates understanding the semantics of the application to you, a smart human.

This introduction ended up longer than planned. Oops. Don’t expect me to tell you who is right by the way, no one knows! Instead, let’s talk about my book and what I’m trying to do with it.

What is it?

So Master Ruby Web APIs. A wonderful name. It’s supposed to teach you how to become a ‘master’ at building web APIs with Ruby. It doesn’t really say what your current level needs to be in order to read it (Can you imagine if I called it ‘From Newbie to Master: A lesson on web APIs, Ruby and the hidden API War’? Actually, it’s not that bad…).

Well, I want anyone to be able to pick up a copy and dive into it. Unfortunately, I don’t want you to fall asleep reading a 5,000 pages manuscript. So it will start with HTTP and Sinatra. A nice and simple combination to review the basics of how HTTP is supposed to be used. But I’m not just going to tell you to follow the HTTP RFC, no, no, no. There are some practices out there that go against HTTP/REST and that are pretty interesting! So we will cover them too.

This first API we will build won’t be RESTful. It will just be a basic HTTP API to dive into HTTP and the best practices to handle versioning, caching, error handling and so on. You will find the pragmatic stuff (it’s easy and it works!) and the dogmatic principles (“It’s the right way.”, or so they say). To be fair, there will also be all the stuff that lies in the middle and that everyone agrees on.

See, I’m not taking sides. I used to. I started on the pragmatic side because that’s the one you find a lot on Stack Overflow and in existing applications. Then I learned more about HTTP, REST, web standards and I switched to the dogmatic side. But I never really applied what I learned. So I decided to stop taking sides. I’m right in the middle and that’s why I think you will like what I’m writing. I will explain why one side prefers one solution and why the other side doesn’t think it’s such a great idea. Don’t worry, to show you that, I will actually build stuff.

Once we will have all the HTTP concepts under control and an overview of how to implement features in different ways, we will build a complete API with the new Rails 5 API module. Still, it won’t be RESTful. I guess it will be kinda-RESTful (trademark pending). We will take the good from both sides and try a few different things.

I’m not going to tell you which side to pick, I’m sure you’re smart enough to do that yourself. But to make a smart choice, you need to know both ways, right?

Anyway, then we will change or re-create our Rails API into something else. Something as REST compliant as possible. Using the latest technologies and hypermedia formats, we will see if we can really build something without any versioning that can adapt and evolve like a website. I can’t tell you yet if we will succeed, you will need to read the book for that. It’s going to be a fun ride, trust me! Or don’t, it’s still going to be fun even without you… :(

Why am I writing it?

I’m going to be super generic and say that “it’s the book I would have loved to have when I started”. Cheesy but true. I still remember my PHP teacher: all you will ever need are GET and POST, the rest is useless. Hmm, ‘kay.

I also want to push people to understand more about web standards and we need them. They are super important for web development but I feel like the most recent generations of developers skip them and have no interest in reading them. But we owe that to Tim Berners-Lee! He created the freaking World Wide Web and made it all free and open. Once again, web standards are super important. Without them, we wouldn’t have HTTP, HTML, CSS, Javascript… Every browser would be different (I mean even more than now) and you would have to write CSS code (or whatever it would be called without a standard) for each one of them! Can you imagine the pain?!

I use the term ‘web standard’ very generally to regroup RFCs, W3C recommendations, ECMA standards and the others. Not very academic, but much easier to read for you.

I’m also trying to open people to REST and building hypermedia APIs in a fun way. Most books about the subject tends to be… as interesting as reading RFCs! Try it out and you will know what I mean. Fun and interesting are my two goals for this book. Oh, you won’t find any academic writing, I don’t have the vocabulary or the patience for that. The way I’m writing it is that I picture you (yes, yes, you RIGHT THERE!) in my mind and try to think how to not bore you to death and make you fall asleep. Let’s hope it works!

Who is it for?

This book is for everyone who has ever worked on a web API or is planning to in the next 10 years. Also, even if it’s about writing Ruby code, it’s mainly about building web APIs so whatever your favorite language is, you will probably learn a few things.

Since we are starting by deconstructing what you know about API development and HTTP, we start pretty low. Beginners welcome! The level will quickly rise however, and I don’t have the word ‘master’ in the title just for fun (or marketing).

My goal is to teach you everything about web APIs!

It doesn’t matter if you think versioning should be in the URL or in the Accept header, the book will cover both and a bunch of others.

It doesn’t matter if the JSON API specification makes you think about XML and triggers your stomach to purge itself. I personally like it and we will talk about it, but we will also be using simple custom JSON documents.

My feeling is that beginners and intermediate developers are the perfect readers. People with more experience might already know what I will share in the book. Whatever you decide, you’ve been warned!

Interested?

Now that this article is written, I can go back to actually work on the book and have fun reading Fielding’s dissertation and the RFCs he authored with other smart people.

If you’ve read until here, that means you are interested and I thank you for your attention! You can subscribe to the newsletter for the book over there. By subscribing, you will get a better discount than the guy next to you who didn’t subscribe (shame on him)!

If you have the soul of a beta tester, let me know! I’m looking for some people to help me review the book so if you think you’ve got what it takes, shoot me an email at thibault(at)devblast.com. It’s a very fair agreement since you get the book for free and, you know, I get you for free. Everyone wins!

The book is expected to be released in the next two months so it’s not that far away! At least, that’s the plan if the word count doesn’t explode along the way…

Thanks for reading, I will be sharing more things about the book soon!

]]>
Mon, 02 May 2016 00:00:00 +0000http://devblast.com/b/stop-calling-your-web-apis-restful-it-doesnt-mean-anything-anymorehttp://devblast.com/b/jutsu-20-bloggy-how-to-test-a-grape-web-api-models-and-controllers
We are getting to my favorite part: automated testing! I used to hate it before and then I had to work on a big legacy application, which luckily had tests. I was so happy to be able to refactor it without breaking anything that now, I simply love writing tests for my applications.

Just kidding, writing tests is a pain in the ass but the usefulness outweigh the pain, by a huge margin, trust me.

Master Ruby Web APIs

The Bloggy series

You can find the full list of jutsus for this series on this page and the jutsu before this one is available there.

Getting the code

You can get the source code to follow this tutorial from GitHub if you didn’t follow the previous jutsu.

Coding Time ¯\(ツ)/¯

Alright, time to finish Bloggy. The tests we are going to write today will be the last thing we’ll do until the next series where we will build a Javascript front-end application to go with Bloggy. When that happens, we will probably tweak a few things and add authentication to the admin controller.

But for now, tests!

Writing tests is an art and most people have their own style. You can write tests in a huge number of ways. My main rules when I write tests is to try to keep them as simple as possible and keep the amount of expectations (asserts) to the minimum: 1. I also like to keep tests isolated and I don’t hesitate to create fake classes and stub (not too much though) for that purpose.

If you have any comments about my testing style, I’d be happy to hear them. Don’t forget to be a civilized person so we can have a nice conversation. ;)

1. Setting up testing environment

We already setup our testing environment in the jutsu 17, when we were doing TDD for the Yumi library. If you didn’t follow that jutsu, head over there, follow the first part where we setup the testing environment and come back here.

Done? Good, let’s go!

2. Writing Rspec model tests

First, we are going to write model tests for posts, tags and comments. Our models are not super complicated so we’re just going to test that they have a valid factory and that they follow the validation rules we defined.

2.0 Rspec introduction

If you don’t know anything about Rspec, here is a quick introduction. Skip it if you’ve already used it in the past.

Rspec allows you to write assertions to ensure that the given input is equal to the expected output.

def multiply_by_2(a)
a * 2
end
it 'returns 6 when param is 3' do
expect(multiply_by_2(3)).to eq(6)
end

Simple right? Don’t worry the first tests in this tutorial are pretty easy too.

Before continuing, let’s go over some important vocabulary:

describe: Define what we are testing. It can be a class or a string.

context: Allow us to group our tests in a logical way. For example, in the previous test, we could make a context from ‘when 3’ (but when integer would make more sense) like this:

context 'when param is 3' do
it 'returns 6' do
expect(multiply_by_2(3)).to eq(6)
end
end

it: Define a test. Give it a name and a block to run.

expect: Similar to assert in other testing frameworks/languages. Will make the test fail if we don’t get what we’re expecting.

I hope this short introduction showed you enough to understand all the tests we are going to write now ;)

2.1 Post Tests

Before we test our models, we want to be sure that the factories we made in the jutsu 17 are good.

Testing that a model has a valid factory is pretty straight-forward. We just build it and use the neat be_valid provided by Rspec.

Obviously, it’s valid because we provide the slug and title. Next we are going to build the validation tests.

Here is the test that checks if the post is invalid without a slug:

it 'is invalid without a slug' do
expect(build(:post, slug: nil)).to_not be_valid
end

See how we use FactoryGirl build method to build a post and pass a hash as a second parameter? Well this hash will override values in our default factory. Instead of creating a new factory, I like to use this feature because it makes the test very easy to read.

We use build and not create here because we don’t actually need to save the record in the database. Using build makes the tests run much faster because there are no communications with the database.

Here is the full testing file for post. Create the folder spec/models and the file spec/models/post_spec.rb before putting the following content in it. Read the whole content to get a good understanding of what we’re doing too!

# spec/models/post_spec.rb
require 'spec_helper'
describe Post do
it 'has a valid factory' do
expect(build(:post)).to be_valid
end
describe 'validations' do
it 'is invalid without a slug' do
expect(build(:post, slug: nil)).to_not be_valid
end
it 'is invalid without a title' do
expect(build(:post, title: nil)).to_not be_valid
end
it 'is invalid with a duplicated slug' do
create(:post)
expect(build(:post)).to_not be_valid
end
end
end

Run the specs with rspec spec/models/post_spec.rb to see if everything works:

2.2 Tag Tests

The Tag tests are pretty similar to the ones we just wrote. Create the file spec/models/tag_spec.rb and put the following inside:

# spec/models/tag_spec.rb
require 'spec_helper'
describe Tag do
it 'has a valid factory' do
expect(build(:tag)).to be_valid
end
describe 'validations' do
it 'is invalid without a slug' do
expect(build(:tag, slug: nil)).to_not be_valid
end
it 'is invalid without a name' do
expect(build(:tag, name: nil)).to_not be_valid
end
it 'is invalid with a duplicated slug in the same post' do
post = build(:post)
create(:tag, post: post)
expect(build(:tag, post: post)).to_not be_valid
end
end
end

2.3 Comment Tests

And finally the Comment tests goes into spec/models/comment_spec.rb:

# spec/models/comment_spec.rb
require 'spec_helper'
describe Comment do
it 'has a valid factory' do
expect(build(:comment)).to be_valid
end
describe 'validations' do
it 'is invalid without an author' do
expect(build(:comment, author: nil)).to_not be_valid
end
it 'is invalid without a content' do
expect(build(:comment, content: nil)).to_not be_valid
end
end
end

Run the specs with rspec spec/models/comment_spec.rb to see if everything works:

Alright, let’s create the folders spec/requests and spec/requests/api, and the file root_spec.rb inside. Here is the content of this file. I put comments to explain everything so don’t just copy/paste it, read it ;)

# spec/requests/api/root_spec.rb
require 'spec_helper'
# Specify which class we want to test
describe API::Root do
# Rack-Test helper methods like get, post, etc
include Rack::Test::Methods
# required app method for Rack-Test
def app
OUTER_APP
end
# We are going to specifically test the /status
# endpoint so we use describe here
describe 'GET /status' do
# We define contexts depending on the media type
# in this case, we will use the media type application/json
context 'media-type: application/json' do
# This will be called every time before each following test
before do
# Set the header to application/json
header 'Content-Type', 'application/json'
# Make the actual request to /api/status using GET
get '/api/status'
end
# Define our first test. Since we're using a media type
# not supported, we expect 415
it 'returns HTTP status 415' do
expect(last_response.status).to eq 415
end
# The endpoint should also returns a JSON document
# containing the error 'Unsupported media type'
it 'returns Unsupported media type' do
expect(JSON.parse(last_response.body)).to eq(
{"error"=>"Unsupported media type"})
end
end
# For this context, we use the correct media type
context 'media-type: application/vnd.api+json' do
# We use a different approach here. See below for explanation.
# Basically we have our two asserts in the same test
# I kinda prefer the first approach but wanted to show you both
it 'returns 200 and status ok' do
header 'Content-Type', 'application/vnd.api+json'
get '/api/status'
expect(last_response.status).to eq 200
expect(JSON.parse(last_response.body)).to eq(
{ 'status' => 'ok' })
end
end
end
end

One thing to note in this test file. In the first context, I used only one assert per test while in the second context, I just one test with 2 asserts. I just wanted to show you the difference, there are pros and cons for each:

First approach (1 assert per test):

You’re only testing one thing. If your test start to fail, you can easily identify the failing test.

It will take longer to run and if you have a huge set of tests, it will take your tests suite longer to run.

Second approach (2 asserts in one test):

Faster to run for huge tests suite.

You have the whole request tested in one test.

Harder to identify why a test is failing

Does not follow best practices

One could argue that those asserts test the same thing because we are just testing the response. However, when building APIs that follow the hypermedia path, it’s important to not limit yourself to the response content. The headers are quite important and deserve their own tests.

For the rest of this jutsu, I use the first approach because I find it simpler to read and because Bloggy is not a huge application with a lot of tests :)

Alright, so we are done writing the API::Root tests. Let’s continue our journey with the Posts controller tests!

3.2 The Posts specs

Create the folder spec/requests/api/v1 and add the file spec/requests/api/v1/posts_spec.rb inside. Here is the content for this file. Copy/paste it if you want but then READ IT because I put a bunch of comments to explain everything.

# spec/requests/api/v1/posts_spec.rb
require 'spec_helper'
describe API::V1::Posts do
include Rack::Test::Methods
def app
OUTER_APP
end
# Define a few let variables to use in our tests
let(:url) { 'http://example.org:80/api/v1' }
# We need to create a post because it needs to be in the database
# to allow the controller to access it
let(:post_object) { create(:post) }
before do
header 'Content-Type', 'application/vnd.api+json'
end
# Tests for the endpoint /api/v1/posts
describe 'get /' do
it 'returns HTTP status 200' do
get '/api/v1/posts'
expect(last_response.status).to eq 200
end
# In this describe, we split the testing of each part
# of the JSON document. Like this, if one fails we'll know which part
# is not working properly
describe 'top level' do
before do
post_object
get '/api/v1/posts'
end
it 'contains the meta object' do
expect(json['meta']).to eq({
'name' => 'Bloggy',
'description' => 'A simple blogging API built with Grape.'
})
end
it 'contains the self link' do
expect(json['links']).to eq({
'self' => "#{url}/posts"
})
end
# I got lazy and didn't put the whole JSON document I'm expected,
# instead I used the presenter to generate it.
# It's not the best way to do this obviously.
it 'contains the data object' do
expect(json['data']).to eq(
[to_json(Presenters::Post.new(url, post_object).as_json_api[:data])]
)
end
it 'contains the included object' do
expect(json['included']).to eq([])
end
end
# I want to test the relationships separately
# because they require more setup and deserve their own tests
describe 'relationships' do
# We need to create some related models first
let(:tag) { create(:tag, post: post_object) }
let(:comment) { create(:comment, post: post_object) }
# To avoid duplicated hash, I just use a method
# that takes a few parameters and build the hash we want
# Could probably use shared examples instead of this but I find
# it easier to understand
def relationship(url, type, post_id, id)
{
"data" => [{"type"=> type , "id"=> id }],
"links"=> {
"self" => "#{url}/posts/#{post_id}/relationships/#{type}",
"related" => "#{url}/posts/#{post_id}/#{type}"
}
}
end
# We need to call our let variables to define them
# before the controller uses the presenter to generate
# the JSON document
before do
tag
comment
get '/api/v1/posts'
end
# The following tests check that the relationships are correct
# and that the included array is equal to the number of related
# objects we created
it 'contains the tag relationship' do
id = tag.id.to_s
expect(json['data'][0]['relationships']['tags']).to eq(
relationship(url, 'tags', post_object.id, id)
)
end
it 'contains the comment relationship' do
id = comment.id.to_s
expect(json['data'][0]['relationships']['comments']).to eq(
relationship(url, 'comments', post_object.id, id)
)
end
it 'includes the tag and comment in the included array' do
expect(json['included'].count).to eq(2)
end
end
end
# Tests for the endpoint /api/v1/posts/1234567890
describe 'get /:id' do
# The post object is created before the request
# since we use it to build the url
before do
get "/api/v1/posts/#{post_object.id}"
end
it 'returns HTTP status 200' do
expect(last_response.status).to eq 200
end
# Repeat the same kind of tests than we defined for
# the index route. Could totally be in shared examples
# but that will be for another jutsu
describe 'top level' do
it 'contains the meta object' do
expect(json['meta']).to eq({
'name' => 'Bloggy',
'description' => 'A simple blogging API built with Grape.'
})
end
it 'contains the self link' do
expect(json['links']).to eq({
'self' => "#{url}/posts/#{post_object.id}"
})
end
it 'contains the data object' do
expect(json['data']).to eq(to_json(Presenters::Post.new(url, post_object).as_json_api[:data]))
end
it 'contains the included object' do
expect(json['included']).to eq([])
end
end
describe 'relationships' do
let(:tag) { create(:tag, post: post_object) }
let(:comment) { create(:comment, post: post_object) }
def relationship(url, type, post_id, id)
{
"data" => [{"type"=> type , "id"=> id }],
"links"=> {
"self" => "#{url}/posts/#{post_id}/relationships/#{type}",
"related" => "#{url}/posts/#{post_id}/#{type}"
}
}
end
before do
tag
comment
get '/api/v1/posts'
end
it 'contains the tag relationship' do
id = tag.id.to_s
expect(json['data'][0]['relationships']['tags']).to eq(
relationship(url, 'tags', post_object.id, id)
)
end
it 'contains the comment relationship' do
id = comment.id.to_s
expect(json['data'][0]['relationships']['comments']).to eq(
relationship(url, 'comments', post_object.id, id)
)
end
it 'includes the tag and comment in the included array' do
expect(json['included'].count).to eq(2)
end
end
end
end

That’s it for the Posts controller tests. Now let’s see what we got for the Comments controller.

3.3 The Comments Specs

You’re probably an expert tester by now! The following tests follow the same logic that we’ve seen before so it shouldn’t be too complicated.

Create the file spec/requests/api/v1/comments_spec.rb and put the following code in it. Once again, the code is commented.

3.4 Testing!

Awesome, everything works correctly! Now anytime we make a change to our API, we can re-run the tests to ensure that we didn’t break anything.

The best practice here is to actually setup a flow where your tests run every time you push some code to your repository (before it gets deployed) using some CI tool like CircleCI for example.

3.5 Writing the admin tests

I’m not going to show you the tests for the admin controller. I’d love to have you write them! It’s the perfect exercise to finish this jutsu. Not just this jutsu actually, the whole series about Bloggy!

What’s next?

This tutorial was the last one in the Bloggy series where we built an API from scratch using Grape, Mongoid and the JSON API specification - what a journey!

I originally wanted to include the jutsus to build the front-end in this series but I think it will go into a different one. We will obviously reuse the API we just built but since the main focus will be Javascript, it should be separated.

Our API still works with the media type application/json! Since the JSON API specification requires using application/vnd.api+json, we need to update our API.

Since I’ve decided that we won’t be supporting application/json anymore, we also need to change how we expect the requests to look like. The JSON API specification luckily specifies how those are supposed to be formatted.

That’s a problem. Since we are going to change the HTTP verb from put to patch for our updates, we shouldn’t replace the whole resource anymore, only the specified fields. So we need to have something like this where nil parameters are ignored:

comment.update!(params)

But since we are not using Rails or the Strong Parameters gem, we are going to get an exception from Mongoid saying that the params are not safe. The thing is that Grape already provide us with parameters validation in the following form:

So what can we do? Luckily, there is a little gem called hashie-forbidden_attributes that will prevent this exception. Obviously, we need to be carefully but we will be using Grape to validate the parameters so everything should be fine.

That’s it, we’re done updating the controllers. Our endpoints are ready for the future front-end application we will create in the next series of jutsus. But we are not completely done with Bloggy yet: in the next jutsu, we will write automated tests to ensure that we never break anything in the future!

3. What did we skipped?

To be honest, Bloggy is not totally compliant with the JSON API specification. There are things that I didn’t cover in the series either because it would make things too long or because I just go lazy… Sorry I’m also human! :)

Here is the list of what Bloggy doesn’t support and that you can implement if you want:

We didn’t implement all the correct HTTP status code when a resource is correctly deleted (204 No Content) and we simply went with Grape default 200 OK. Responding with 200 is actually fine but we then need to responds with top-level meta data and Yumi doesn’t allow for cherry-picking which top-level keys we want so we didn’t do it. Maybe a feature to add for you ;)

Our JSON documents contain links to access related resources or relationships but we did not implement them in our API.

Belongs To

Yumi only supports has_many relationships which means presenting a comment, for example, wouldn’t come with its parent post as a related resource. Adding the belongs_to relationship is actually not that hard and I encourage you to do it yourself ;)

What’s next?

This series is almost finished. We built a complete Grape API from scratch with its own JSON API implementation. But no application is complete without automated tests and that’s exactly what we are going to do in the next jutsu.

Master Ruby Web APIs

The Bloggy series

You can find the full list of jutsus for this series in this jutsu and the jutsu before this one is available there.

Getting the code

You can get the source code to follow this tutorial from GitHub if you didn’t follow the previous jutsu.

Coding time!

Alright, time to start using Yumi inside Bloggy. In this jutsu, we are going to create our presenters that will inherit from Yumi::Base. The good news is that it’s going to be pretty easy because all the hard work has already been done in Yumi!

1. Updating the application file

First, we need to make a few changes to the application.rb file.

Here is the list of changes:

Add the META_DATA constant. That’s the hash we will pass to Yumi in our presenters to represent our API meta data.

That’s it for the application.rb, let’s move on to the presenters. It’s going to be pretty fast so don’t get too excited!

2. Adding Presenters

With all the time we spent making Yumi, the presenters should not be hard to implement. And indeed, we just have to create Ruby classes, inherit from Yumi::Base and call a few methods before having functional JSON API presenters.

2.1 Post

First, the Post model. I’m not sure if there is anything to say, it’s pretty simple. We are actually just using the class methods we defined in Yumi.

Create the file app/presenters/post.rb and put the following content in it.

3. Calling our Presenters

We now have functional presenters and the only step missing is to actually use them in our controllers. Let’s fix that right now.

3.1 Posts

We already know how to use our presenters so we can just update our controller actions. To do so, we instantiate the Post presenter with the base_url (given by our little helper from earlier) and the current post.

# app/api/v1/posts.rb
module API
module V1
class Posts < Grape::API
version 'v1', using: :path, vendor: 'devblast-blog'
resources :posts do
desc 'Returns all posts'
get '/' do
Presenters::Post.new(base_url, Post.all.ordered).as_json_api
end
desc "Return a specific post"
params do
requires :id, type: String
end
get ':id' do
Presenters::Post.new(base_url, Post.find(params[:id])).as_json_api
end
end
end
end
end

Try it out! Start your server with shotgun config.ru and access http://localhost:9393/api/v1/posts to have this beautiful JSON document in front of your eyes!

And that’s it! We don’t have any controller for Tags so we can skip that.

Note that in our JSON, related and included resources have a related and/or self links pointing to endpoints that we don’t have for comments and tags. To follow the JSON API specification, we should actually have a controller for tags and more actions for comments in order to access the individual resources and the relationships. You can add them as an exercise ;)

4. Manual Testing

I’m getting bored of having to manually test everything…if only there was a way to automate all that :troll:.

Of course there is a way and we’re going to do it very soon! But for now, here are a few cURL requests you can run to test your endpoints.

Client Posts controller cURL Requests

Start your server with shotgun config.ru to run the following queries.

The End

We’re pretty much done with our JSON API implementation. We skipped a few things to be honest because it was just too much. I hope that what we saw motivated you to try out JSON API by yourself and find out more about what the specification has to offer.

Before wrapping up the API and starting the series about the front-end, we need to add two more things. Currently, the request payload that we handle are not compliant with the JSON API specification. Let’s change that and ensure we only allow one media type (application/vnd.api+json) in Bloggy. After that, we will add automated tests in order to avoid regression and be able to sleep at night easily.

This is the third jutsu in the series ‘Building a blogging API from scratch with Grape, MongoDB and the JSON API specification’. We are going to implement the JSON API specification we studied in the previous jutsu.

To do this, we are going to create a library named Yumi that will take care of generating the JSON document for us. I also want to show you how to do some TDD so we’ll write the first class using the red/green/refactor flow. Unfortunately, I couldn’t do that for each class because it would make this jutsu way too long.

By following this tutorial, you will learn:

How to do some basic TDD development

How to write a Ruby library from scratch

How to isolate responsibilities to make them easier to test

How to write an implementation of the JSON API specification

Master Ruby Web APIs [advertisement]

Mandatory mention about the book I’m currently writing: Master Ruby Web APIs. If you like what you’re reading here, take a look and register to get awesome benefits when the book is released.

The Bloggy series

Getting the code

You can get the source code to follow this tutorial from GitHub if you didn’t follow the fifteenth jutsu.

Implementation Time

Let’s get started with the implementation.

First, if you want an easy way to debug something in your code, don’t forget to include the gem pry-byebug in your Gemfile. After that, a simple binding.pry will stop the execution of the server and give you a console to interact with the code at that specification breakpoint. It will also add a few more commands like step, next, finish and continue.

It’s a bit long but it contains all the information we need to display a post and access the related resources. If we were building something like a CRM with a lot of lists, it would be super easy to automatically call the given url instead of hard-coding it in the client.

However, for our blog we don’t have any dedicated view for tags or comments, only posts. That’s why I decided to use a compound document to include everything related to a post in just one document.

This JSON document is what we want to output from our API. Currently, we use Grape default formatting which just calls to_json on the models and only shows the post attributes. We have a lot to do to get what we’ve seen above.

The Idea: The Yumi library

To build this JSON document, we’re going to build a generic library called Yumi. In this library, we will have a Base presenter class from which our API presenters will inherit.

Note: Yumi is the Japanese term for a bow. ‘Cause you know, we’re basically shooting JSON documents.

To give you an idea of how we will use it in Bloggy, here is our future Post presenter:

Creating Yumi

We are going to create Yumi inside our project, in the folder app/yumi.

I believe the best way to create a library is not necessarily to create a brand new project. It’s better to make it inside an existing project (that’s what the lib/ folder is for in Rails) before extracting it to a gem. Plus, it’s easier for a tutorial to just have one project.

Navigate to the root of your application folder and run the command:

mkdir app/yumi

And update the application.rb file to load the content of this folder:

To make Yumi, we will create a bunch of classes that will each take care of generating a specific part of the JSON API document. For example, one class will be responsible for generating the hash that list the attributes. Another one will take care of the links.

Isolating responsibilities like this will make it super easy for us to write tests for each one of them.

Note that since this is a tutorial, we cannot make this library complete - it would take too long and bore you to death. Instead, I focused only on the features we really need. We will review what’s missing at the end, feel free to add the features you want ;)

1. Setting up a testing environment

We are going to follow a TDD approach to build the first class of Yumi. Before doing this, we need to setup a testing environment with Rspec, Rack-Test, Factory Girl and Mongoid Cleaner. Note that Factory Girl and Mongoid Cleaner won’t be used in the following tests but will be needed in the future when we write the specs for the Bloggy API.

1.1 Include the gems in your Gemfile

First, we simply need to update our Gemfile and add the following gems. Here is a quick description for each one of them:

1.2 Setup Rspec

This should create the spec/ folder and the spec/spec_helper.rb file. If you’re missing them, just create them manually.

1.3 The Spec helper file

Below is the content for the spec/spec_helper.rb file updated with everything needed to make it work within our Rack application. Checkout the comments if you don’t understand something.

# spec/spec_helper.rb
# We need to set the environment to test
ENV['RACK_ENV'] = 'test'
require 'ostruct'
require 'factory_girl'
require 'mongoid_cleaner'
# We need to load our application
require_relative '../application.rb'
# Those two files are created later in the jutsu
# but we can already include them
require_relative './factories.rb'
require_relative './support/helpers.rb'
# Defining the app to test is required for rack-test
OUTER_APP = Rack::Builder.parse_file('config.ru').first
# Base URL constant for our future tests
BASE_URL = 'http://example.org:80/api/v1'
RSpec.configure do |config|
# Load the helpers file required earlier
config.include Helpers
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
# We put this to use the create & build methods
# directly without the prefix FactoryGirl
config.include FactoryGirl::Syntax::Methods
# Setup Mongoid Cleaner to clean everything before
# and between each test
config.before(:suite) do
MongoidCleaner.strategy = :drop
end
config.around(:each) do |example|
MongoidCleaner.cleaning do
example.run
end
end
end

1.4 The factories file

Next we create the file spec/factories.rb and put the following content in it. This file contains a bunch of factories for the Bloggy models.

We’ll come back to them later in the tutorial, when we actually use them.

1.5 The helpers file

Finally, here is the content for the spec/support/helpers.rb file. This little module will allow us to write our tests faster by avoiding repeating the same thing in each test. As you can see below, it gives us shortcuts to get the response body as a Ruby hash or convert a symbolized hash to a stringified hash.

1.7 Checking that everything works

Let’s see if we did everything correctly.

Run the rspec command and you should see the expected output without any error. If you do see an error, try to understand what’s wrong and fix it. If you can’t, just leave a comment and I’ll see what I can do. ;)

We’re done setting up our testing environment. Now it’s time to start writing some tests and some code!

2. The Attributes presenter class

The Attributes presenter is responsible for generating a hash of attributes for the specified resource. It will take a resource, a presenter and the list of attributes as parameters.

2.1 The Skeleton

For now, however, it’s not going to do anything. We’re just going to write an empty skeleton so we can start writing tests for it. Create the folder app/yumi/presenters before adding the file attributes.rb inside.

2.4 Adding a few let

Now we can get started for real. Sorry for all the preparations. We are about to write the tests for the Yumi::Presenters::Attributes class but before that we need to define a few let that we will use in our tests.

If you don’t know what’s a let, it’s an elegant way to define variables for your tests. To give you an idea, defining the following let:

let(:variable_name) { 'variable_value' }

Is equivalent to something like this:

def variable_name
@variable_name ||= 'variable_value'
end

All let definitions are wiped between each test.

In a real use-case, the Attributes class will receive Ruby classes as parameters. To mimick that, we use OpenStruct because it makes easy to create objects from hashes. Those objects respond to calls with the dot notation (.) which makes them behave like regular class instances.

With those let definitions, we have our options hash that will be passed to the class and that contains the attributes, the resource and the presenter.

The presenter is kinda useless for now, but it will be needed soon. I included it already to avoid having to change this part of the spec later in the tutorial.

2.5 Our first test

Finally, our first test! Here we are testing the to_json_api method and we basically want it to output a hash of the list of given attributes associated with the values of the given resource.

# spec/yumi/presenters/attributes_spec.rb
# describe & let
describe '#to_json_api' do
it 'outputs the hash with the resource attributes' do
expect(klass.to_json_api).to eq({
description: "I'm a resource.",
slug: 'whatever'
})
end
end
# Rest of the file

2.7 Fixing it

We can’t leave that test fail, that wouldn’t be professional. So let’s fix it! We just need to implement enough code to make it pass. To do this, we just have to loop through the @attributes and call the method of the same name on the resource object.

Here is the code:

# app/yumi/presenters/attributes.rb
module Yumi
module Presenters
class Attributes
def initialize(options)
@options = options
@attributes = @options[:attributes]
@resource = @options[:resource]
end
# Takes the given list of attributes, loops through
# them and get the corresponding value from the resource
def to_json_api
@attributes.each_with_object({}) do |attr, hash|
hash[attr] = @resource.send(attr)
end
end
end
end
end

2.8 Re-running the tests (GREEN)

Awesome, it’s working! Normally, we’d do some refactoring here but I don’t see what to change in the code we wrote.

2.9 Adding the override

Unfortunately, there is a feature missing from this. We don’t want Yumi users to be stuck only with their resource attributes. Maybe they also want to define something in their presenter class or override one of the resource value.

Let’s add a test for this. We are also going to use contexts to keep this test from the one we already wrote because they depend on a different set of parameters.

As you can see below, we override the let(:presenter) with a new OpenStruct that contains the same key than the resource we defined (description). When klass will be called, it will use this definition of the presenter when building the options variable.

# spec/yumi/presenters/attributes_spec.rb
# describe & let
describe '#to_json_api' do
context 'without overrides' do
it 'generates the hash only with the resource attributes' do
expect(klass.to_json_api).to eq({
description: "I'm a resource.",
slug: 'whatever'
})
end
end
context 'with overrides' do
let(:presenter) { OpenStruct.new({ description: "I'm a presenter." }) }
it 'outputs the hash with the description overridden' do
expect(klass.to_json_api).to eq({
description: "I'm a presenter.",
slug: 'whatever'
})
end
end
end
# Rest of file

Boom, huge fail as expected. Our first test is still passing but the new one is failing hard.

2.11 Fixing it

Luckily, we can fix this code pretty easily. First let’s add the @presenter instance variable that will get a value from the options parameter. Then we just need to check if the given presenter can respond to the attribute or not. If it can, we will get the value from it else we’ll get it from the resource.

2.12 Run the tests (GREEN) \o/

And yes, it works! We implemented the Attributes class the way we wanted it and we did it in the TDD way. Congratulations!

A quick break

The bad news is that we still have 8 classes to write for Yumi… And that means we cannot use TDD to write them all because it would take forever.

Honestly, this jutsu grew way bigger than I thought (7000+ words…), actually way too big to stay interesting. So I decided to extract all the code and only explain what each class does while adding links to the GitHub repository. Feel free to check the files and read the comments in each one of them.

2. The Links presenter

Like the Attributes class, the Links class only takes a hash named options in parameters. But this hash contains all the data needed to build the links for our resources.

From the given options hash, we will extract:

The base URL

The links wanted for this resource

The plural name of the resource

The actual resource

With those, we will generate the links that could look something like this:

3. The IncludedResources presenter

The IncludedResources class is responsible for generating the array of included resources that will be available at the top-level of our JSON document. To do so, it will need:

The base URL

The resource

The resource relationships defined in the presenter

The instances of this class use a hash named included_resources to keep the resources in the returned array unique. The key for each resource is the association of its type and its id so we’re sure we cannot have duplicates.

8. The Base class

And the last one! This is the actual base class from which our future presenters will inherit. It contains the public API of our library with the 3 methods as_json_api, as_relationship and as_included.

It takes 3 parameters which are:

The base URL, needed to build the link

The resource

An optional prefix when instantiating a presenter to call the as_relationship method

This class is responsible for creating the options hash that will be passed around and that contains all the required variable for each other class. After that, its job is just to call the appropriate class and define the top-level layout of the JSON document.

Master Ruby Web APIs [advertisement]

Want to learn how to build awesome web APIs with Ruby? I’m currently writing a new book titled Master Ruby Web APIs that will show you exactly how to do that. Take a look ;)

The Bloggy series

You can find the full list of jutsus for this series in this jutsu. It’s also the tutorial before this one so don’t hesitate to read it!

Understanding hypermedia APIs

If you don’t know anything about the semantic web, REST and hypermedia APIs, this article [Coming Soon] will definitely help you grasp those concepts.

An overview of the JSON API Spec

In the next jutsu, we will implement the JSON API specification in Ruby by creating a library. Before we can do that, we need to understand the fundamentals. The best way to do this is to read the full specification here but I will go over some of the basics here to save you some time.

Come on. It might look a bit scary but it’s not much more complicated than the JSON documents your APIs output everyday. You will soon like it!

We are not going to use all of JSON API features in Bloggy so I will only talk about what you need to know for now. I really recommend reading the full specification to get a better understanding of it.

Media Type

The JSON API specification is identified by the media type application/vnd.api+json. You can find more information there.

Top Level

As you can see above, the top level attributes are:

meta :a meta object that contains non-standard meta-information.

data: the document’s “primary data”.

errors: an array of error objects.

links: a links object related to the primary data.

included: an array of resource objects that are related to the primary data and/or each other (“included resources”).

Some of these attributes are optional, feel free to checkout the specification for the details. In Bloggy, we are going to use meta, data, links and included.

Meta

In meta, we will put some information about the Bloggy API like its name or a quick description. This is human-readable and not meant for a computer.

Relationships + Included

Finally, related resources will be included as relationships and listed in the included list. The included list is only used for compound documents where the related resources are shipped with the main resource. There are other ways of doing this to avoid loading huge JSON documents. However, for Bloggy, I want to load all the tags/comments right away to keep it simple.

Even if that would be fine for tags to be loaded that way in a real application, I’d recommend not including the comments and side-loading them instead. Take a look at the specification to learn how to do that.

I recently released the latest project I’ve been working on. It’s called YourSetup and it’s available here in beta. I’ve been making web APIs for mobile games for the past year at Playlab and I didn’t get the chance to do some good full-stack web development. I kinda missed it so I thought I would create something from scratch by myself. I love challenges and this one was a very exciting one!

What’s YourSetup

I built niche websites with affiliate links in the past which means I kind of know the affiliate marketing world and how it works. That’s why I wasn’t surprised to see the same kind of links in the description of YouTube videos or on Twitch streams. Those links allow these people to make some extra cash by recommending what they use.

I really like the idea that people can make a living by recommending the stuff they use and love.

I’m also personally a gamer. I play mostly MMORPG games (Blade&Soul NA recently) and I thought it would be great to see what equipment the gamers I like use to play games with. I like to see nice and clean gaming setups and the effort people put into having an awesome gaming environment. Plus, if I see something I really like in a setup, I want to find out where I can get it.

From this, the idea behind YourSetup was born.

YourSetup would be a place for people to share their setups by simply taking a picture of it. They could then add pins on the picture to help people get the same gear. If they want to use affiliate links, that’s up to them!

I told myself it was a cool idea that would be a great side project for me to work on and refresh my front-end skills. I decided to use Ruby on Rails to get a MVP ready ASAP.

Note: If you don’t know what are affiliate links, it’s just links provided by companies to purchase their products. If people buy stuff using your links, you will get a small commission from the sale.

Lesson 1: Elastic Beanstalk is awesome… except for some small stuff where it isn’t that awesome.

With Elastic Beanstalk, you can quickly deploy and manage applications in the AWS cloud without worrying about the infrastructure that runs those applications.

EB is basically a layer added on top of EC2 to make it easier for people to deploy any kind of web applications as long as it’s written in Java, Node.js, Python, PHP, .NET, Ruby or run inside a Docker container.

Why Elastic Beanstalk?

I basically had 3 options to deploy YourSetup.

Heroku

From Scratch on Digital Ocean / Linode / EC2

Elastic Beanstalk (running on EC2)

I didn’t want to go with Heroku because of the very high pricing when you need to scale up. I was also too lazy and busy to set up everything from scratch on a VPS. Scaling would also have been an issue since I didn’t have any mechanism to handle it for me.

The solution was pretty obvious as you can see. With Elastic Beanstalk, you get the power of running your application on virtual private servers (EC2) but all the configuration is done for you. Adding more servers can be done automatically depending on how you configure your EB application. You can also do it manually in just a few clicks!

When you start using Amazon Web Services, it makes sense to use more than one service since they all work very well together.

Database

For the DB, I wanted to use PostgreSQL. That’s all I needed to tell Elastic Beanstalk. During the configuration of my application, I simply indicated that I wanted to use PG and a RDS instance was created for me.

Background Jobs

I decided to use Sidekiq to handle the processing of the pictures in the background. To do this, I needed a Redis instance. Of course, AWS has a service for that: Elastic Cache. You can either pick Memcached or Redis and I went with Redis. Connecting EB with EC wasn’t actually that easy. I tried a few things using .ebextension configuration files before finding out that I could just link them through the web interface in a few steps. Duh!

File Storage

Everyone knows S3 right? I don’t even know any other service that does the same thing because I’ve always been happy with AWS S3. For YourSetup, I needed a place to store the setups pictures and S3 was the perfect place for that.

Issues

The main issue I faced on the way was running out of memory during deploys. Usually while compiling assets, the deploy would crash and tell me that the process had run out of memory. Damn!

For some reason, I was running a t1.micro instance. I’m not sure why I had this because I don’t remember picking it. Anyway, once I upgraded to a t2.micro, the problem went away.

The other thing I’m always a bit worried about with AWS is the pricing. I’m still afraid to wake up one day with a $1000 bill to pay. Luckily, AWS have some notifications when you reach a specific billing threshold to react ASAP. So far, I didn’t pay much since I qualified for the free AWS tier. I have to pay for the staging server though.

Pros & Cons

Elastic Beanstalk is awesome.

It’s easy to use. Setup the application with eb init or through the web interface and enjoy using the eb deploy command after that.

You can run one application for free (including DB, caching, and file storage)

Adding or removing servers can be done in a few clicks.

You can SSH to the servers if needed.

Elastic Beanstalk can also be a pain.

I always had issues with the AWS documentation. It seems I can never find what I’m looking for. I mainly used external tutorials to get everything working.

Some configuration found online are not working for the latest stack which is ruby 2.2 (Puma). Be careful when using configurations from Gist or Stack Overflow since they might not be up to date.

I had some issues understanding the .ebextensions system at first. It’s
actually quite simple, you can basically put YAML configuration files in there
to do some stuff when your application is deployed.

Lesson 2: Paperclip > Carrierwave (IMHO)

Let’s talk about pictures upload and processing! YourSetup lets users upload pictures of their setups so that was a pretty important part. Instead of re-inventing the wheel, I just went with an existing solution: Carrierwave.

I’ve used both Paperclip and Carrierwave in production applications in the past. I like the way Carrierwave encapsulates the uploaders into their own class so I went with it.

At first, it was great. I had my uploaders ready and working in local. Then I started working on uploading the pictures to S3 and processing them in the background.

I tried to find existing solutions and found carrierwave_backgrounder and carrierwave_direct, two gems that seem to do what I needed. I tried to integrate them both but I couldn’t get them to work properly! I’m not sure why but after wasting half a day trying to figure ir out, I decided to switch to paperclip + delayed_paperclip + sidekiq and got everything working in less than an hour.

From now on, I will simply use Paperclip anytime I need to handle pictures upload and processing.

Lesson 3: JQuery is a pain in the a**

I worked on a few SPA applications in the past 3 years - mostly using Angular.js and React.js. For YourSetup however, I settled on a regular Rails 4 application (with Turbolinks). HTML is generated on the server and JQuery is used to dynamically modify the page.

While working on YourSetup and creating some JQuery components (for the pinning system for example), I realized how much I didn’t miss manipulating the DOM at all! Using Javascript/JQuery directly feels a bit cumbersome. Having to manipulate the DOM, make Ajax calls and update manually the content of each div/span was annoying to be honest. Writing SPA felt like a breeze compared to that. I guess I just lost the habit of writing Javascript in that way!

After a bit of refactoring using CoffeeScript class syntax, I was able to have clean components that are now pretty easy to change if I have to.

JQuery is still an awesome tool that I will keep using but now, I honestly prefer writing Javascript using SPA technologies.

Lesson 4: Use Slim/SCSS/Coffeescript

I just love those 3 technologies: Slim <3 SCSS <3 CoffeeScript. They just make me save so much time!

I’m not sure if you’re into this or if you still enjoy writing ERB and CSS but I would really recommend you to give it a try.

Slim just make it so fast and easy to write templates. SCSS gives you variables and mixins. Just that should be enough to convince you to use them. I can change the whole theme of YourSetup by changing a few variables and I love that!

CoffeeScript is another story. I don’t really have a preference between pure JS and CS. I use both depending on the situation. The thing I love about CoffeeScript though is the class syntax. It makes it so easy to write Javascript classes without worrying about prototype!

Lesson 5: If you need something, AWS probably have a service for you

Another lesson related to AWS. If you need something, they probably have it. Don’t hesitate to take a look at all their services. I’m personally thinking about switching to AWS CodeCommit (instead of Bitbucket) and AWS CodePipeline (instead of CircleCI).

By signing up, you also get one year of free usage for almost all the services. That means you can give it a try without risking anything! Even when you have to start paying, AWS is still pretty cheap compared to the alternatives.

To actually test the email flow, there is always the awesome letter_opener ruby gem made by Ryan Bates. Any time an email is sent from your application, it will simply pop it up inside a new tab in your browser. That’s perfect to feel the flow in local before pushing anything to production.

Lesson 7: Don’t forget Exception reporting & Logging

Once your application is live, you will need two important tools to keep track of what’s happening.

You will need a place to:

Record and save exceptions

Access the logs

To do those 2 things, I was looking for platforms with free plans since I’m not sure YourSetup will pay for itself. Until then, free plans are good enough.

I didn’t have any issues so far and I’m super happy with what they provide for free!

The End

I hope you enjoyed reading what I learned while working on the MVP for YourSetup. If you have 5 minutes, please check it out and let me know what you think. You can also apply for the Beta, I’m still looking for beta testers!

In this fifteenth jutsu, we’re going to do something special. This is going to be the first article of a series that will teach you how to build a blog from scratch using Grape, MongoDB, Ember.js and a JSON format: JSON API.

This first part will be about creating a basic Grape API with MongoDB backing it up. Later on, this API will become an hypermedia API.

Tools

We’ll be using a set of awesome tools to build this blogging system. I hope you will learn a bit along the way ;)

Grape

Grape is an “opinionated micro-framework for creating REST-like APIs in Ruby”. We will use it to build the endpoints of our web API and send back the JSON data to the client.

MongoDB

MongoDB is a NoSQL document database. It will be used to store the data of our blog.

JSON API

JSON API is a specification for building APIs in JSON. I want to show you how to stop making custom JSON every time you build a new API and start following one of the universal specifications. This will be very useful when we create the Ember.js application since we will be able to use an existing adapter to receive the data.

Ember.js

Ember.js is a frontend Javascript framework to ‘create ambitious web applications’. We will use it to create the frontend of our blog. In another jutsu, we will see how to make it SEO-friendly.

The Project

So we’re going to use this set of technologies to build a simple yet awesome blogging engine from scratch. There won’t be a user login system at first but we will add it in a future jutsu. For now we’ll focus on having the following in our API: posts, comments and tags.

Let’s see how we’re going to define those entities and the endpoints that will let us access them.

Database Collections

Since we are using a NoSQL database, we will be focusing on documents and embedded documents and avoid relationships that are not necessary. We actually only need one document in which we will embed both tags and comments. Here is an example of how one post will look like:

We basically embed the list of tags and the list of comments inside a post. Like this, each post is isolated and retrieving the data is super simple.

Endpoints

For our API, we need two sets of endpoints: the admin part and the client part. In the admin part, we should be able to create, write, update and delete posts. In the client side, we only need to retrieve posts (many or just one) and create/update/delete comments.

Admin

I’m going to list the admin endpoints here. Those endpoints will be used through an admin interface in the future to manage blog posts.

Posts

Here are the admin routes for the Post entity.

GET /admin/posts: List of posts (index)

GET /admin/posts/1: Get one post (show)

POST /admin/posts: Create a post (create)

PATCH /admin/posts/1: Update a post (update)

DELETE /admin/posts/1: Delete a post (destroy)

Client

Now let’s see the endpoints we need to present to the public part of our blog. People need to be able to get the list of posts, get a specific post and comment stuff.

Posts

Here are the client routes for the Post entity.

GET /posts: List of posts (index)

GET /posts/1: Get one post (show)

Comments

Here are the client routes for the Comment entity.

POST /posts/1/comments: Create a comment (create)

PATCH /posts/1/comments/1: Update a comment (update)

DELETE /posts/1/comments/1: Delete a comment (destroy)

That’s all we need for our little blogging web API. How about we get started and build it? :)

Versioning

Our API will be versioned by adding a prefix in the URL. I feel that it’s much easier for people to understand that way in a tutorial. We will only make a v1 for our blogging API as you will see in the next steps.

Build it!

Time to get our hands dirty. We’re first going to setup the application and the dependencies we need. Then we will create our models (Post, Comment, Tag) and finally add all the endpoints we need, both for the admin part and the public part.

1. Create the application

Let’s create our application. We are not creating a Rails application so we cannot just use some kind of generator. Plus I want to show you how to do it from scratch.

Let’s create a new folder, move inside and create a Gemfile. We will then use this Gemfile to define what we need and use the awesome Bundler to install everything.

mkdir grape-blog && cd grape-blog
touch Gemfile

For now, we just need the grape gem. Here’s the content for the Gemfile file:

# Gemfile
source 'https://rubygems.org'
gem 'grape'

Now a quick bundle install will give us what we need to start coding.

Our application is going to look a bit like a Rails application with an app/ folder containing models/ and api/. It will basically look like this:

We need an entry point for our application. For this, we’re going to create a file named application.rb where we will require stuff, define the base Grape API object and tell Rack how to mount our application.

If you’d like, you can use the racksh command to run something like rails console for our Rack application. You will be able to test the models by creating, updating and deleting them.

4. Adding the client endpoints (C)

Models are ready, we can implement our API endpoints. We will be storing our controllers in app/api/v1/. We won’t follow the Rails conventions of adding _controller at the end of every controller file. We will just use the plural version of the models: posts.rb, etc.

I know it’s preferred to use headers to store the API version but since this is a tutorial and we will be using cURL, I prefer to keep it simple and easy to understand.

Posts

If you remember, we wanted the following routes for the Post entity:

GET /posts: List of posts (index)

GET /posts/1: Get one post (show)

Well, let’s create them with Grape! We need to create a file named app/api/v1/posts.rb with the following content. This is the simplest controller we will create which is why we’re starting with it.

# app/api/v1/posts.rb
module API
module V1
class Posts < Grape::API
version 'v1', using: :path, vendor: 'samurails-blog'
resources :posts do
desc 'Returns all posts'
get do
Post.all.ordered
end
desc "Return a specific post"
params do
requires :id, type: String
end
get ':id' do
Post.find(params[:id])
end
end
end
end
end

That’s all we need from the posts controller serving the list of posts to the client. For now, we’re letting Grape convert our objects to JSON. We will come back to this in the next Jutsu and implement the JSON API specification instead.

Comments

The comments controller is a bit more complicated. If you don’t remember, here is the list of endpoints we need to implement in this controller:

POST /posts/1/comments: Create a comment (create)

PATCH /posts/1/comments/1: Update a comment (update)

DELETE /posts/1/comments/1: Delete a comment (destroy)

Let’s add it now. Create the file app/api/v1/comments.rb with the following content:

5. Create the Admin endpoints (C)

We are only going to create one controller for the admin part. That means we won’t have any comment moderation or anything like that… Come on, I cannot fit everything in this article! I will come back to it and create a new Jutsu if you guys are interested.

For now, let’s add our admin controller: app/api/v1/admin/posts.rb

Quick reminder of the list of endpoints that we need for this admin controller:

Final Test

Now start up your server and use the following cURL requests to check that everything is working correctly. In the Jutsu 17, after implementing the JSON API spec (in Jutsu 16), we will write automated tests for this web API.

CAPTCHAs are an awesome way to protect your forms from automated submissions using Bots. The only problem? They suck.

CAPTCHA Systems suck!

Think about it. You’re trying hard to convert people and get them to signup on your website. Asking them to calculate the result of 2 plus 2 or recognize some characters is a great way to send people away. How many times have you submitted forms with a CAPTCHA to realize that you weren’t able to differentiate ‘b’ and ‘lo’ in a distorted image?

Google is here to the rescue

Fortunately, Google released a new CAPTCHA system that only requires people to click on a checkbox. Yes, that’s right, a simple click!

Wait, how does this work?

Honestly, I have no idea and Google is not going to tell us. It’s probably based on examining users’ behavior on past websites, analyzing cookies and so on. Anyway, it looks great and it works!

Here’s a quick screenshot of the CAPTCHA:

Now, it’s time to build stuff with it ;)

Let’s build something!

In this Railsjutsu, we’re going to build an application with a form to create messages. To avoid spammers and bots, we’ll integrate Google ReCaptcha.

1. Setup

Our application is going to be super simple. It will only contain one controller/model and the corresponding views.

Let’s quickly generate the application.

rails new recaptcha_jutsu

2. Create a Controller

Now that we have an application, we will scaffold a Message entity. Run the following command to generate the model, the controller, the views and the tests.

rails g scaffold Message name:string email:string content:text

And don’t forget to run the migrations.

rake db:migrate

We also need to define the root path of our application. To do this, we have to change the routes.rb file:

Now let’s run our server with rails server. If you head over to http://localhost:3000, you should be able to see the new message form. Feel free to create as many new messages as you want. We could actually create a bot to fill this form and submit it.

That’s exactly what we’re trying to prevent so let’s see how we can use Google ReCaptcha to prevent it.

3. Adding Google ReCaptcha

Google ReCatpcha is pretty easy to add on its own. All you need to do is go to Google’s website (here), click on ‘Get ReCaptcha’, register a website, copy the code into your application and that’s it!

But there is actually a simpler way for us, lucky Rails developers. Of course, there is a gem: recaptcha.

Let’s use it in our application.

4. Adding the recaptcha gem

We first need to edit the gemfile, add the following and then run bundle install.

gem "recaptcha", require: "recaptcha/rails"

To work properly, we need to set the API Key provided by Google. You should be able to find it there if you don’t have it yet.

In your applications and in production, you should use some environment tool to handle secret keys but in this simple example, I’m just going to put it in an initializer.

Create a file named config/initializers/recaptcha.rb and add the following inside:

That’s it for our form. Don’t forget to play with the CAPTCHA, everything should work fine.

6. Checking the CAPTCHA result in the controller

We need to change the create action in the MessagesController to check if the CAPTCHA was correctly validated. To do this, we just need to call the method named verify_recaptcha provided by the recaptcha gem.

When creating new web applications, there is something I’ve always struggled with in the past.

It’s creating and testing emails.

So in this Railsjutsu, I want to show you how you can simplify your email creation workflow in development. With the following gem and some nice Rails features, you will be able to customize how your emails look and check when they are sent.

Introduction

Letter Opener is a super useful gem built by Ryan Bates. It allows you to send emails in your development environment. It won’t send it to your email client though, it will just pop a new tab in your browser with the email. Sweet right?

Let’s build something!

Setup

So let’s get started. We’ll build a very basic application that will send an email when we access a specific endpoint.

Let’s create a new application.

rails new letter_opener_jutsu

Now let’s add the gem to our Gemfile in the development group.

gem 'letter_opener', :group => :development

Followed by a quick bundle install.

Configuration

Now we need to change the delivery method for development in config/environments/development.rb:

config.action_mailer.delivery_method = :letter_opener

And that’s it for the configuration. Now let’s add a controller with one action that sends an email.

Creating a controller

Let’s create a new file in app/controllers named home_controller.rb with the following content.

The Result

Everything is ready, let’s give it a try. Start your application and head over to http://localhost:3000.

And boom! You should see a new tab opening in your browser with the following inside:

Wicked!

Designing your email

But wait! You don’t have to repeat the same action over and over again just to see how your email looks like. Letter Opener is more to see that the right stuff is sent at the right time. To design your email, you can just use am ActionMailer feature: the Preview!

When we generated our mailer earlier, we actually got the following file created test/mailers/previews/home_mailer_preview.rb. We can just add a method to this class and we’ll be able to visualize our email!

Let’s add a method named welcome that will just send our welcome email. If we had any parameter, like a user for example, we could just pass the first user for example with HomeMailer.welcome(User.first).

Now we can simply access the provided url (http://localhost:3000/rails/mailers/home_mailer) and we will see our welcome method. Click on it and you will be taken to your email! Now you can super easily create it and visualize it.

Before Rails 4.1, I was using the gem mail_view to do this kind of stuff. Luckily, it got merged into Rails and is now the ActionMailer::Preview!

Keeping track of the sent emails

Before wrapping up, just a quick note about another neat little gem that lets you keep track of all the emails that were sent. The gem is called Letter Opener Web and will give you a web interface to browse all the emails sent from your application.

Wrap Up

That’s it for this Railsjutsu, I hope you learned a few things along the way ;)

Ready to setup a static website for your blog? You are in the right place!

Introduction

Here’s a quick reminder of what you need to know about this option:

Price: FREE

Difficulty: Medium

Knowledge: Git, Markdown, GitHub

Required Tools: GitHub account, Internet Browser, Text Editor

And here are the pros and cons for this solution:

Pros

Totally Free

Super fast (only static files)

Easy to make changes (edit, commit & push)

Cons

A bit of tech knowledge is required

Need to pay for a domain name (to avoid the url myblog.github.io)

Have to use Disqus for comments

Tool Descriptions

To complete this tutorial, you will need to use the following tools. Showing you how to use some of them is out of the scope of this article so don’t hesitate to read the linked resources before continuing.

Git: Git is a Version Control System widely used in the software engineering world to allow teams to work on the same source code. It is not limited to code however and can be used for anything requiring version control, articles for a blog for example. Learn it in 15 minutes here.

GitHub: GitHub is one of the most famous Git repository hosting service. Nothing complicated once you know Git.

Jekyll: Jekyll: “Jekyll is a simple, blog-aware, static site generator.” From plain text files written with markdown (or other markup languages), it will generate a static website for you. We’ll learn how to use it in this tutorial.

Markdown: Markdown is a simple markup language that let people focus on writing and not formatting. Learn how to use it.

Build it!

Here’s how we’re going to do it. First, we’ll create a GitHub account and a repository to host the content of our website. Then, we will generate our website in local using Jekyll (after installing it). The next logic step is to push our local version to GitHub to get our website online. Finally, we’ll improve the default static website generated by Jekyll. Let’s go!

1. Create a GitHub account and a new repository

Head over to Github and create a new account if you don’t have one already.

Choose the free option.

Check your inbox for the verification email and verify your account. Then go back to Github and create a new repository by clicking on ‘New repository’.

Fill in the information and click on create. You need to use the format YOUR_USERNAME.github.io to make it work.

Click on Create. You will then be taken to a page to get started on your new repository. Copy the given URL and save it for later.

Next we’re going to initialize Git in your directory, so move inside of it with cd YOUR_WEBSITE_NAME.

Run the following commands to start versioning your static website with Git.

git init
git add .
git commit -m 'Initial Commit'

Next we’ll create a Gemfile. Why? Well, if you work on your website/blog from other computers, you will need to re-install Jekyll multiple times. The easiest way to do this is simply adding a Gemfile to the project that will contain the dependencies (i.e. github-pages).

Create a file named YOUR_WEBSITE_NAME/Gemfile and put the following inside:

source 'https://rubygems.org'
gem 'github-pages'

Then run bundle install. Let’s commit the new files (Gemfile and the newly generated Gemfile.lock).

git add . && git commit -m 'Add Gemfile'

Before we push our new blog to GitHub, let’s try it in local and write an article.

4. Running Jekyll in local

It’s pretty easy to run Jekyll in local, just run the following command from your website/blog folder.

bundle exec jekyll serve

Now if you access http://localhost:4000, you should see the following:

Congratulations, you now have Jekyll up and running… in local!

5. Pushing it live

We did before so it shouldn’t be too hard. Just run the two following commands and everything should be pushed to Github correctly. Don’t forget to replace YOUR_USERNAME with your actual Github username.

6. Configuration

Now that we have a running website (mine is available at samurails.github.io), let’s customize it.

Start the Jekyll server with jekyll serve if it’s not already running.

First, let’s open _config.yml. You should see something like this:

# Site settings
title: Your awesome title
email: your-email@domain.com
description: > # this means to ignore newlines until "baseurl:"
Write an awesome description for your new site here. You can edit this
line in _config.yml. It will appear in your document head meta (for
Google search results) and in your feed.xml site description.
baseurl: "" # the subpath of your site, e.g. /blog/
url: "http://yourdomain.com" # the base hostname & protocol for your site
twitter_username: jekyllrb
github_username: jekyll
# Build settings
markdown: kramdown

Change the content of all the fields to whatever you want (they’re pretty self-explanatory), restart the server and check http://localhost:4000/. You should see everything updated correctly.

7. The About section

Now that our blog is configured, let’s change the About section with some actual information. To change it, we’re going to modify the file about.md. Currently, the content should be the following:

---
layout: page # ---> Type of the page (page or post)
title: About # ---> Name of the page
permalink: /about/ # ---> Path of the page
---
This is the base Jekyll theme. You can find out more info about customizing your Jekyll theme, as well as basic Jekyll usage documentation at [jekyllrb.com](http://jekyllrb.com/)
You can find the source code for the Jekyll new theme at: [github.com/jglovier/jekyll-new](https://github.com/jglovier/jekyll-new)
You can find the source code for Jekyll at [github.com/jekyll/jekyll](https://github.com/jekyll/jekyll)

Leave everything between the two ---. Those are meta-data used by Jekyll to generate your website. You can update the rest with actual info about you. Here’s the one I made for samurails.github.io.

---
layout: page # ---> Type of the page (page or post)
title: About # ---> Name of the page
permalink: /about/ # ---> Path of the page
---
Hi, I'm Thibault and this is a fake static website. My real website is available [over there](//samurails.com).

And here’s the result:

8. Writing our first post

Alright, our static website is ready! Now we just need to add content. There’s already an article but let’s remove it and create a real one. Posts have to be created in the folder _posts/ and need to be formatted as YEAR-MONTH-DAY-title.md.

Let’s create one now, I will call mine 2015-11-13-my-first-post.md.

Next we need to define the meta-data of our post and add a bit of content:

What to do next?

Since our new website is static, we don’t have a database to store our comments. Do not worry, there is a solution. Simply use Disqus! All you need is signup and add a bit of Javascript and you will have a comment system in your blog!

Hi there. Today I want to show you how to easily setup a website to share whatever you want with the world. It can be educational or just fun, that’s up to you. Since you’re on Devblast, some of the options offered in this article are a bit technical. Don’t worry though, you can also jump directly to the second option which does not require any technical knowledge.

If you already know how to setup websites using things like Jekyll or Wordpress, you won’t learn anything new in this article ;)

Why you should have a website/blog

I wrote an article about why everyone should have a (programming) website/blog and the benefits it provides. You can read it here.

Let’s get started!

Pick your favorite solution!

I want to give you a few different options before showing you how to set them up. If you’re not a tech person, just go with option 2, Wordpress <3 Arvixe. It’s the easiest one to setup and will just require moving your mouse around.

Here are the 3 options with their prices and their difficulties. I’ve personally used them all but I’ve settled on using Wordpress for most of my websites with both Arvixe and Digital Ocean.

1. Static website with Jekyll and Github Pages

Price: FREE

Difficulty: Medium

Knowledge: Git, Markdown, GitHub

Required Tools: GitHub account, Internet Browser, Text Editor

With this solution, everything is free. You will be relying on GitHub entirely to have your website available on the web. This is a great solution for tech blogs and is usually picked by software engineers because of the minimalist design and the familiar tools used (Git, Github & Markdown).

Your website will just be a folder on your computer with all the articles inside as text files (or markdown files). The whole folder needs to be versioned using Git and pushed to GitHub to be made available online.

Here is a quick summary about each tool:

Jekyll: “Jekyll is a simple, blog-aware, static site generator.” From plain text files written with markdown (or other markup languages), it will generate a static website for you.

Git: Git is a Version Control System widely used in the software engineering world to allow teams to work on the same source code. It is not limited to code however and can be used for anything requiring version control, articles for a blog for example.

GitHub: GitHub is one of the most famous Git repository hosting service. It can be used for free as long as the projects are public. For a blog, people can read online freely anyway so it doesn’t need to be private.

Markdown: Markdown is a simple markup language that let people focus on writing and not formatting. Formatting is done using pre-defined symbols easily inserted while focusing on typing, and not clicking around.

2. Wordpress <3 Arvixe

Price: $4-$7/mo

Difficulty: Easy

Knowledge: Wordpress, CPanel

Required Tools: Arvixe account, Internet Browser, Text Editor

This option is widely used by non-technical people because of its simplicity. I have to admit that I also use it for some websites because it’s just super easy to use. This option uses the overused Wordpress to quickly setup a website.

In 5 minutes, you can get a functional website with a custom domain name (which is free!).

The main tool you will need for this is actually Wordpress. Lucky you it’s very easy to use. If you don’t know yet (have you been leaving under a rock?), Wordpress is a CMS created with PHP that lets you setup a website and manage its content without any technical skill. By using themes and plugins, you can truly create the website you want. All is left once setup is actually writing stuff!

Arvixe is one of the many web hosting companies that exist and the one I personally recommend because of its reliability and affordable price. I personally use it for some of my websites but not for Devblast (I actually use the third option to host Devblast).

3. Wordpress <3 Digital Ocean

The most complicated solution which requires a good knowledge of Git, SSH, server administration and more. You should have some experience as a developer to be able to set this up without issues. If you’re not a tech person, go back to the previous solution. ;)

Pros

Total control

Faster website (Even if it’s a VPS, you’re sharing less than with shared hosting)

If you’ve been developing with the web for any time, you’ll undoubtedly be aware of at least the 404 and 500 error responses. These are part of the two response classes which constitute errors - 40x and 50x. The rest demonstrate successful requests.

All web applications have to support these error messages. They are, after all, responses to requests. You can get good responses (10x / 20x / 30x) and erroneous responses (40x / 50x). The key for us is to make sure we catch the erroneous responses and direct them to our own error pages.

The way Rails handles errors is through a middleware hook called exceptions_app. This captures any exceptions coming from Rails, allowing the middleware to create an appropriate response. In short, it’s responsible for keeping your web server online if a problem does occur (as opposed to making it crash):

This middleware [exceptions.app] rescues any exception returned by the application # and calls an exceptions app that will wrap it in a format for the end user.

All the tutorials you find on how to create custom error pages hook into exceptions_app, allowing you to “divert” the user in the way you want. The “quality” of your error handling is dependent on what you do after you’ve caught the error. This is what we are to discuss:

Thus, any time you want to interject your own logic to the exception handling process, you have to override the exception_app middleware hook; pointing it to your own exception handling infrastructure.

There are two ways to do this:

Send the exception to the routes (which then refers onto a specific controller/action)

Invoke a controller directly

Let’s explore both methods (they’re very similar):

1. Routes

If you want to have basic error response pages, you’ll be best sending to your application’s routes.

This is the most common form of error handling, as it does not require a lot of customization:

Gems

There are a number of gems which provide this functionality.

One of the more popular, and most effective, is called exception_handler. This uses the “controller” method above but with several extensions, including a database component (to store the errors) and an email notifier.

Scopes are a great Rails tool to keep stuff DRY and well organized. It’s not complicated though, it’s just a set of pre-defined queries that can easily be chained to build complex queries. Let’s see how to use them efficiently and what to do when they’re not enough anymore.

Basics

Let’s start with the basics. We’ll use a sample model named Article to illustrate what scopes allow you to do.

This model has the following attributes:

title (string)

content (text)

published (boolean)

author_name (string)

On your homepage, you only want to show published articles of course. So in your action, you would use the following code to ensure that.

def index
Article.where(published: true)
end

You will probably need to re-use this code somewhere else so it would be better to define it in the model directly. Plus, it has to do with querying data so it kinda belongs in the model and not the controller.

I often see weird stuff in Rails applications. One that I always find weird is when people put stuff that belongs to the domain of their application inside the /lib folder. Let’s talk about why most of the stuff inside lib doesn’t belong there.

Ruby on Rails architecture

First, let’s quickly go over the Rails architecture. I’m sure you know it very well but still, I want to clarify a few points.

The /app folder contains all the logic used directly by the application: models, controllers, views, mailers and so on.

The /lib folder, as the name implies it, is meant to contain libraries. We both know that in Ruby, libraries are packaged as gems 90% of the time (I love to make up statistics). So what is this folder supposed to be used for then? Well, it’s not complicated. It’s for libraries that are not packaged as gems but could be.

The rest of the folders in a Rails application contain everything that does not belong to the business logic. Database schema and migrations, configuration, tests… The stuff that allows the application to run correctly but not the application itself.

The /app folder

Everything that is directly related to your business logic should be put inside the /app folder. What if you want to create a PORO (Plain-Old Ruby Object)? Well you can put it in app, it belongs there. You can put it in the models folder except if you prefer to keep stuff organized. In that case, create a new folder! People do that all the time with services, observers, presenters, decorators and so on. It’s not because Rails doesn’t have those by default that you cannot create them. Rails is your b**, do whatever you want with it!

What you should put inside this folder:

Your models, controllers, views and mailers.

Any other entity you create (class, module) that holds some business logic.

What you should not put inside this folder:

Configuration, migrations, tests (obviously).

Generic entities (class or module). For example, a class to perform a bunch of generic calculations on an array (median, etc) should be in /lib. Why? Because it’s a generic feature that could easily be extracted to an awesome gem usable by other people.

The /lib folder

Now that you know what to put inside the /app folder, you also know what to put in /lib. All the generic logic you create to do some calculations, transform images or deal with authorization (don’t re-create though, use CanCanCan).

It doesn’t have to be just ruby classes. It can be models, controllers and views as long as it’s generic enough. Now you can put them inside an engine, give it a cool name, package it as a gem and share it with your friends. Congratz!

Once in a while, you should clean up your /lib folder. You should be able to extract a bunch of stuff from there and package them as gems. Note that you don’t necessarily have to. I understand that extracting code means another project to maintain and update. It’s a nice way to give back to the community though.

Stop putting stuff in /lib

I wrote this article because way too often, I see stuff inside the /lib folder that contains important application logic. The default folder structure generated by Rails is great but you can go further! If you need decorators or presenters, just create new folders in the /app folder!

If you don’t know about it yet, there is a cool thing named DCI that suggests using services to implement the interactions between objects. Take a look!

Everything in this post is just my opinion, if you think it’s a bunch of ‘bs’, you can tell me what you think in the comments. I think it’s all about style and if you’re happy with the way you organize your code, good for you!

I recently attended a conference where one of the speakers asked the audience if they knew the difference between gems and engines. I was very surprised to see that nobody knew the difference! Well except me, thanks to my work with engines in modular applications and the work I did for my book Modular Rails.

So let me ask you, do you know the difference between gems and engines? If you do, this article might be uninteresting for you. If you don’t, you should really read what follows because understanding the difference between them is really important, especially if you’re planning on creating your own libraries.

What’s a gem?

Gem is just a fancy term for a packaged Ruby library. A library is just a bit of code providing a set of functionalities to anyone who integrates it in its code.

The only thing you need to know to understand the difference with an engine is that a gem is pure Ruby code.

What defines a gem:

Gemspec

Lib folder

Can be packaged and pushed to rubygems servers

Can be used in any project simply by referencing the name (once pushed to Rubygems servers)

Creating a gem

Creating a gem is pretty easy. All you need actually is a lib folder containing a file named my_gem.rb and a my_gem.gemspec file. Once you have this, you can use gem build my_gem.gemspec to build the packaged gem. This package can then be published to rubygems servers or installed locally with gem install my_gem-x.x.x.gem. Finally, if you want to publish your gem publicly on rubygems servers, you can use gem push my_gem-x.x.x.gem.

Once pushed to public servers, you can easily install it with gem install my_gem.

Note that you can also use Bundler to generate a gem with a nice file architecture by using bundle gem my_gem. The steps to package and install are the same than above.

Now let’s talk about engines.

What’s an engine?

Engines are actually gems. All engines can be gems (if packaged) but not all gems are engines.

Engines are a Ruby on Rails feature. That’s where the difference lies. They are meant to work within a Ruby on Rails application which means that they can contains Rails-specific entities: models, controllers, views, migrations and so on.

They are basically minimalist Ruby on Rails applications that can’t run on their own: they need to be integrated inside an existing Ruby on Rails application to work.

Creating an engine

To package and install an engine, you can use the same commands than for gems.

Building:

gem build my_engine.gemspec

Installing in local:

gem install my_engine-x.x.x.gem

Pushing to rubygems servers:

gem push my_engine-x.x.x.gem

Mountable vs Full

There are two options when creating an engine: mountable and full. Mountable means that you will mount your engine inside your Ruby on Rails application at a specific path, like /my_engine for example. It comes with folders for assets and controllers. A ‘full’ engine however is not meant to be mounted inside an application and is more there to provide new entities to an existing Ruby on Rails application. It won’t be encapsulated with namespacing and will just be an extension of the main application. Note that even after the creation, a full engine can easily be changed to be mountable vice versa.

Wrap Up

Gems are pure Ruby libraries while engines can contain Ruby on Rails features. Engines can still be packaged as regular gems though but will only work inside a Rails application.

In this article, I want to share how one of my typical days looks like. If you’re not interested in reading the random story of a random developer, stop right here and go back. I warned you ;)

This ‘typical’ day is a bit (a lot?) generalized and I probably never actually lived through this exact sequence of events. If you want to become a software engineer this will give you a glimpse of how one of our days actually looks like.

Who am I

Before we get to my usual day, let me introduce myself. My name is Thibault Denizet and I’m a French guy currently living in Thailand. I’m currently working at Playlab. Before getting to the active life, I studied a master in Bordeaux, France, at Ingesup. I’ve started development about 6 years ago but I’ve only been working full-time as an engineer for the last 3 years.

In my free time, I write articles for my website Devblast. I also wrote a book about creating modular applications (a.k.a Component Based Rails Applications) so if you’re into that kind of things, don’t hesitate to check it out.

Where do I live

As I said earlier, I live and work in Bangkok, the capital of Thailand. It’s a great city to be in and the tech scene keeps growing. It’s great to see the changes! More and more developers are needed, so if you’re looking for a job and you like Asia, come and give it a try!

I came here for the first time 5 years ago and I’ve came back a few times to do internships since. Finally, 2 years ago I completely moved to Thailand and I am absolutely not regretting that decision! I love it here. Life and people are both great and I get to do what I like: build stuff!

Who do I work for

This is an important part to understand the following sample day. I work for a company called Playlab where I’m currently a backend software engineer. Playlab is a mobile game company. You might have heard about the game Juice Cubes if you like match-3 games. Well that was Playlab!

The backend team’s job is to create APIs for the mobile games, deal with operation tasks and produce usable analytics. We use a wide range of tools including Ruby on Rails, pure Ruby, Node.js, PostgreSQL, Cassandra, Docker and so on!

Playlab is a great place to work where the APIs need to handle millions of users. Lots of challenges and an awesome environment!

A typical day

Enough with the presentation! Time to go through my day… Enjoy the ride!

07:45

I usually wake up between 7:45am and 9am, depending on my laziness. Since we have flexible hours, it’s alright to show up at 10am after a late evening (out partying of course!).

I’ve never been a morning person, so I do the bare minimum and just go to work! I use the BTS, Bangkok’s Skytrain, to get to the office. Unfortunately, the station is a bit far. No worries, I can jump on a taxi motorbike and get there in 5 minutes. Plus it’s super cheap (like half a buck). Oh and it’s super dangerous!

09:00 - Starting the day

Once I arrive at the office, I get a freshly mixed fruit juice full of fruits and vegetables including carrot, guava, tomato, beetroot, pineapple and apple. That’s my energy cocktail and a great way to start the day.

I then hop in the lift and I’m finally at the office. Let’s boot up and check emails. Of course, there’s nothing interesting since the whole company is using HipChat for communication. There’s not much use for emails except for automated reports and the likes.

We’re following Scrum and using Jira to keep track of who’s doing what. We used Trello until recently and I really liked it. Unfortunately, no burn down chart and estimate field made us move over to Jira.

So after the uninteresting emails, I will usually check Jira and see what people are working on: it’s always good to know what your colleagues are doing! It allows me to find out when there’s a pull request waiting for review and that’s usually my next step!

Pull request reviews are an important part of the development workflow at Playlab. Not only does it make the code better, it also makes the whole team better!

Next up, I will actually start working. It will usually be a coding task related to one of our micro-services or something to change in our analytics system. It mostly involves Ruby but we are not limited to it. We just pick the best tool for the job. Whatever the task is, I will usually start by a basic draft of my code to figure out the best way to do it. Then the way will just reveal itself. Before actually writing the code, I will write some specs.

Tests are super important. I didn’t write any tests a while back and I don’t know how I manage to not destroy everything. Also, the bigger your team grows, the more important specs become. You cannot refactor or update code that you don’t know if you don’t have a failsafe. Tests are this protection and ensure that you are not breaking the application. Writing them before or after doesn’t matter, just write them!

So after having created a few Ruby classes (I love to use POROs everywhere), wrote my specs, refactored and made sure I was happy with my code, I will just push it to Github and create a Pull Request with a clear description. People are usually notified in HipChat automatically when someone pushes something or create a pull request but it’s always good to remind people who have an interest in the PR.

Alright, that was a lot of stuff for an hour because I wanted to explain exactly what I’m doing. I can’t say much about the actual coding because it changes everyday!

10:00 - Fully awake

10 comes by and catches me in the middle of making some changes in my code based on some comments on my pull request. Nothing huge but there were indeed a few optimizations that could be made to improve the code.

That’s also the time when most of Playlab’s employees arrive (flexible hours ftw) so I will usually have a chat with some members of the backend team or notify a game producer of some changes he requested at the coffee machine.

11:30 - Daily Standup

We are following the Scrum methodology to measure and improve the team. I’m not really convinced about the whole Scrum thing to be honest. I’ve been working with it for a while but I’ve never been able to make it work perfectly: we always end up on some form of Scrum-but. I’m simply not sure it’s actually helpful. It might be because we’re working on many projects at the same time that relate to different things: operations, analytics, services… Let me know if you have some experience with Scrum and what’s your feeling about it!

One thing I find good about Scrum however is the daily standup meeting. That’s great to hear what people are working on and if they are having any trouble. It’s quick and helpful!

12:00 - Free Lunch

When noon clocks in, it’s time for lunch. And you don’t want to be late at Playlab. Everybody rushes to the kitchen and grab some of the delicious thai dishes cooked by the cook. We’ve got rice (welcome to Thailand) and 2 to 3 Thai dishes. There’s also a salad bar.

After lunch, there’s a lot of available activities: taking a nap, playing ping-pong, playing PS4… or just going back to your computer!

13:00

After the break, it’s time to start working again! We planned a Group Code Review at 1 so it’s time to head over to one of the meeting rooms and talk… about code!

Group Code Review are one-hour-or-less meetings where all the team members review a new project/feature/big change. It’s usually a walkthrough so everyone gets up to speed about the specificities of this project. Some good ideas usually come out of those meetings in order to improve the project.

14:00

The task I created this morning has been approved by some members of the team so it’s time to merge! It’s first going to be merged from the branch I created for this feature to development. We’re using continuous integration which means that as soon as I merge into development, the code will be pushed to staging and ready to be tested by the platforms team. To pull, test and push the code automatically, we’re using CircleCI.

CircleCI is also responsible for building the Docker container in which the application runs. Docker is a great tool, check it out!

Since my code is now live in staging, I’m going to move my task in Jira to the staging column. I will then notify someone in the platforms team that the feature is available in staging and that they can test it when they have time.

15:00

I have to wait a bit for the feature to be tested but don’t worry, I have plenty of other tasks. When I’m about to start one however, one of the game producers comes to bug me about a fix to his game’s analytics. We’ve made the change already and it will be reflected in the data the next time our analytics pipeline is run (the next day). He asks me a few more questions and we spend a bit of time chatting about some of the analytic results.

16:00

It’s my lucky day! The platforms team already notified me that the feature is working as expected and that the Q/A team is currently testing it. I should be able to push it to production the following day, simply by merging development into master. Yay continuous integration.

17:00

I finally have time to start working on a new task which involves creating a Dockerfile for one of our Ruby on Rails micro-services. Dockerfiles are used to generate the Docker container and have to be written before the application can be pushed to our servers. I’m not usually working on operations related tasks (we have people just for that) but we recently started to spread the knowledge in the team in an effort to bother the ops guys less, especially for simple things.

So yeah, I’m creating a Dockerfile. It’s probably not the most exciting stuff ever but it’s important and we just have to do it one time. Plus, I can reuse pieces from other dockerfiles so it’s not that hard. Once it’s ready, I just update the circle ci config in the project to define where the application should be pushed and that it should build a Docker container. The application is now available in staging and I can start the service with a quick fleetctl start myservice.service!

18:00

Alright! My day is over, I will push the new application to production tomorrow. It’s time to go home so I just jump again on a 30 baht motorbike taxi, take the BTS and get to my condo. That’s where my second day starts.

Once I get home, I put on my Devblast hat and start to write articles! But first, I like to check analytics to see the traffic and get some motivation. I will also answer to any email I received and check the comments on Devblast.

19:00

Nothing very interesting at that time on the tech side. I will usually have dinner (like a bami moo deng) and watch some TV Shows.

[บะหมี่แห้งหมูแดง - Bami Moo Deng

20:00

For the following two hours, I will keep working on Devblast. It could be a new article for the blog, an email for the newsletter or a new book (like Master Ruby Web APIs). It varies depending on the day and I keep track of all my tasks in Trello.

22:00

After a hard day of work both at the office and at home, it’s time to relax. I will usually grab my iPad to read some articles or a book. Maybe I’ll just play some games like Super Smash Bros or this amazing mobile game called Dungeon Link that got me completely addicted!

I also like to build stuff. These days, I’m having fun with my Arduino kit but I also enjoy building Gunpla and playing around with Lego bricks! That might sound childish but it’s a great way for me to get some time away from the computer and actually build something real (as opposed to softwares… :p).

I like to read some fiction before going to bed. These days I’m enjoying the great Dune written by Frank Herbert.

00:00

Time to sleep! See you tomorrow for a new adventure.

The End

Well that’s it. That was a ‘typical day’ for me as a software engineer living and working in Bangkok. Let me know if you liked it in the comments! If you hated this article, let me know why so I can keep improving ;)

Want more?

If you like to read about the crazy daily life of web developers, checkout CommitStrip! It’s an amazing website full of funny web comics related to programming.

What is an API

In computer programming, an application programming interface (API) is a set of routines, protocols, and tools for building software applications. An API expresses a software component in terms of its operations, inputs, outputs, and underlying types.

Basically, you’re building stuff so you or other people can build more stuff on top of it.

In the case of a programming library, the API is the way you interact with it. It’s the ‘interface’ that defines how you ask for something and how you set something. Some APIs are beautiful, others are not. That usually means they are either well-conceived, easy to use and properly documented or the complete opposite: hard to understand and cumbersome.

What is a Web API

A web API follows the same idea. Extend the concept we defined for a library to a web application. You’re basically building something for other people to consume in mobile applications, javascript applications or other web applications. The main difference is that the communication is happening through HTTP (mostly).

A lot of known platforms provide APIs to integrate with them. For example, Facebook offers ways to query for a user information or his friends by using the right security details.

Understand the difference between web APIs and web services

You know I like to use Wikipedia, so here are the entries for those two terms.

Web services

The W3C defines a Web service generally as a software system designed to support interoperable machine-to-machine interaction over a network.

The W3C Web Services Architecture Working Group defined a Web Services Architecture, requiring a specific implementation of a “Web service.” A Web service has an interface described in a machine-processable format (specifically WSDL). Other systems interact with the Web service in a manner prescribed by its description using SOAP (Simple Object Access Protocol) messages, typically conveyed using HTTP with an XML serialization in conjunction with other Web-related standards.

Web API

A server-side web API is a programmatic interface to a defined request-response message system, typically expressed in JSON or XML, which is exposed via the web—most commonly by means of an HTTP-based web server.

The Difference

Basically, web services are a standard defined by W3C with a specific set of rules. Web services are often known to rely on WSDL, SOAP and XML.

Web APIs are much simpler. Just do it the way you want it. There are no standards. However web APIs usually use the HTTP protocol to communicate, can follow the REST style and exchange data with XML or JSON. Again, there are no standards but it’s been proven to be a great way to build a web API in the past years.

Why build a Web API

A lot of scenarios can require a web API. Here are a few examples:

Persistence for mobile applications

Since mobile applications are run inside sandboxes and cannot access durable persistence, it is often required to build a web APIs to do this for them. Saving a user’s details on the server side gives a better user experience by allowing the use of multiple devices and no data loss when a phone is reset or broken.

Mobile application with interactions between users

Another use case for a web APIs would be to create interactions between users. Like in a social media or a dating application. To be able to match all those people, you need them in the same place and that’s not going to be inside a smartphone. That’s where a web API comes into play.

Mobile application for an existing web platform

This one is quite obvious. If you currently have a web platform, like Facebook for example, and you wish to have the same features inside a mobile application, you will need to add a web API to your platform.

Javascript SPA

Singe page applications built with javascript are always meant to work with a backend.

Why use Ruby to build a web API

Ruby is a great programming language. It might not be the fastest kid around but it’s still a great choice to build a web API. Not only it’s great to code in Ruby, there is also a lot of great tools to build web APIs specifically. From testing to routing, everything is covered and you will be able to pick the right tool for your needs.

There are other options though. Python and Node.js are too other good choices. If you prefer a compiled language, C# and the .net framework comes with a lot of nice utilities designed to create web APIs (ASP.NET for example).

I will mainly be talking about Ruby APIs in this article and the following ones because that’s simply my favorite tool.

Available tools/frameworks

As I said earlier, there are a lot of tools to build web APIs with Ruby. In this section, I’ll talk about a few frameworks available.

Grape

Grape is a micro-framework providing a way to build lighweight REST-like API by using a simple DSL. If you don’t need a heavy framework like Rails, Grape could be the best choice for you!

Rails-API

Rails

Finally, you can just use Ruby on Rails to build a web API. Don’t think it’s overkill just because you’re not dealing with HTML. You still need to implement all the logic somewhere and Rails conventions will help you keep stuff organized and clean. However, there are a few things you can do to not use things included in Rails that you don’t need. For example, consider inherit from ActionController::Metal (doc) and only load the modules that you need.

So you’re a developer. Great! You’re having fun at the office coding from 9 to 5/6, maybe work on a few open source projects too. But do you have a blog? Blogs are really amazing tools for developers.

Not only you can become a better developer, you can also earn some extra money. Having an active and dynamic blog shows to the world that you have something to say. If you say it well, people will see you as an authority which can lead to a lot of interesting propositions.

Learn by teaching

Writing about programming and other technical stuff is an amazing way to learn and improve your skills. If you don’t want to end up looking like a fool, you need to do a proper research, write clean code and make your articles easy to understand. Basically, you’re learning in the best way: by doing.

Getting stuff done is hard though. Especially when it’s in your free time. Just writing a sample application to test this awesome new technology is cool but I find it boring. Plus, you don’t always understand what you’re doing.

Now, add the fact that you need to explain it to all the people who read your articles.

If you can’t explain it simply, you don’t understand it well enough. Albert Einstein

I love this quote because it’s simply true. By trying to explain it to people, whatever the format (text, video, podcast), you will need to totally understand it.

Learn by sharing

After having finished an article, you will have a much better understanding about the subject. Now share it with a few smart folks and wait for the comments.

You will get tons of useful feedbacks from people who have more experience than you. And there’s always someone with more experience. This happens to me recently when I wrote my 10 Ruby Tricks article. The comments on the post and on Reddit improved the article by pointing out mistakes or misunderstanding I had. They also contain tons of valuable information.

Finding a job

Presenting yourself at a job interview and saying you have an active technical blog or website is a great plus. People can easily check your articles and your past work and see how you think. A GitHub account with at least a few repositories and a blog full of articles can make the difference between you and another candidate.

It also shows that you have experience writing technical articles. That means you can write for the company’s technical blog, produce amazing documentation and provide clear explanations.

It also shows initiative and recruiters love that.

Freelancer gigs

People who liked your articles might contact you which could lead to landing a freelancing job. If you’re using platforms like Upwork (formally Odesk), you can include your blog in your profile. Your potential clients will be able to see what you’ve done, even if they don’t understand anything about coding! If they do, don’t forget to also have a nice GitHub account ;)

Obviously, you don’t always have to write about technical stuff. It’s your blog and you’re free to make it whatever you want! Want to give tips to other freelancers? Make video tutorials about getting higher rates? Totally up to you!

Make some extra income

By having a blog, you have an indirect relation with your readers. Those could become your clients if you offer them something they really need. Here are a few examples:

Warm Up

Just get started already. There are so many great platforms available to have a blog up and running in 5 minutes. Want to use static files? Go with Jekyll. Prefer to have an admin panel? Wordpress is your friend!

This post contains the various resources I use as a software engineer and writer.

NOTE: This page is outdated. I’m currently putting together an updated resource list.

Disclosure: You should know that some of the links in this article are affiliate links and that I will earn a commission if you end up using the services. There is no additional cost for you so it’s a good way to say thanks if you enjoy my articles ;)

Interview with Paysa

Checkout my interview with Paysa on making the most of a career in Software Engineering!

Gear

My mobile workstation: I love my Macbook Pro Retina 13. Why 13 inches? For me, it’s the best size to move it around while being able to put it on a desk and plug an external screen.

My home workstation: Custom-built computer that I originally put together for gaming. I stopped playing games a few months later so I reconverted it to a Hackintosh. That wasn’t easy but it was totally worth it. I love having access to the command line and Photoshop on the same machine. Plus it’s more powerful than most iMac for a third of the price so I can still run most available games.

Reader: iPad mini. I love its size and its weight. I can bring it anywhere with me and do all my reading on it. That goes from reading Science-Fiction (Foundation, Dune, …) to Fantasy (The Farseer Trilogy, Game of Thrones, …) to work-related books (Ruby, Publishing and so on).

I’m also an avid reader of manga and comic books. The iPad feels that need too. The Marvel app and the Marvel unlimited programs are amazing!

I’m still using an iPhone 5S but I might switch to Android someday… ;)

Programming

I’ve been trying to switch to Vim for a long time but I always end up back with Sublime Text. I simply love it!

I dislike the default terminal included with OS X so I use iTerm 2 instead. (Solarized theme, zsh, oh-my-zsh)

Writing

I also do all my writing in Sublime Text. I mostly write in Markdown so I just have to install the MarkdownEditing plugin and it turns Sublime Text into an awesome text writer. The distraction free mode is also amazing to get stuff done. Super useful for me who likes to delay the writing part as long as possible!

To put together ebooks or PDF from my Markdown writing, I use the Softcover gem. It’s an incredible tool. I also had to pick up a bit of LaTeX to format the generated PDFs the way I wanted.

Research

I use Pocket and Evernote extensively to organize my notes and the things I want to read. I have so many things in Evernote now that I couldn’t stop using it even if I wanted to!

Hosting

Devblast is hosted on a VPS from Digital Ocean. Great hosting company with great prices. Originally, it was on Arvixe which I’m still using for other websites and project.

Blog

Samurails (Devblast’s predecessor) was, like one third of the Internet, running on Wordpress. Yikes PHP, I know. But it’s an awesome platform to use as long as you don’t have to dig in the code… Anyway, let’s stay on the great platform part. I’m actually using a free theme from Colorlib named Sparkling but I’ve been thinking of switching to one of the ‘Elegant Themes’ themes. I’m already a paying user (only $69 per year for 87 themes!!) and I love having this huge library to pick from when I want to create a new website for myself or for my friends. The plugins are also super cool and I started to use some of them on Samurails (like the cool-looking sharing sidebar).

Payment Platforms

That part is mostly about Modular Rails and how I receive the money when someone buys the book. First, I picked Gumroad to handle the selling process because of their clean and easy checkout experience. Then I receive the funds in Payoneer and transfer the money to a bank account outside of the United States.

Music

I always listen to music when I’m coding (with Spotify). It helps me focus and cut the ambient noise from interfering with my thinking. I don’t have a specific taste in music and I listen to a wide range of styles. Most of them are rock or alternative rock. I really enjoy listening to Imagine Dragons, Fall Out Boy, Queen, The Script and Linkin Park (from the teenage years x)).

Books

I quickly talked about it earlier, but here’s the list of books I love or that I’m currently reading. Speaking of books, don’t forget to checkout my book Modular Rails!

Want more?

If I forgot something or if you want me to add something about another topic, just let me know in the comments ;)

1. Create a hash from a list of values

2. Lambda Literal ->

Introduced quite recently and the new way recommended to define scopes in Rails, the -> sign, a.k.a Lambda Literal, allows you to create lambda easily.

a = -> { 1 + 1 }
a.call
# => 2
a = -> (v) { v + 1 }
a.call(2)
# => 3

3. Double star (**)

The double star is a neat little trick in Ruby. See the following method:

def my_method(a, *b, **c)
return a, b, c
end

a is a regular parameter. *b will take all the parameters passed after the first one and put them in an array. **c will take any parameter given in the format key: value at the end of the method call.

See the following examples:

One parameter

my_method(1)
# => [1, [], {}]

More than one parameter

my_method(1, 2, 3, 4)
# => [1, [2, 3, 4], {}]

More than one parameter + hash-style parameters

my_method(1, 2, 3, 4, a: 1, b: 2)
# => [1, [2, 3, 4], {:a=>1, :b=>2}]

4. Handle single object and array in the same way

Sometimes you might want to give the option to either accept a single object or an array of objects. Instead of checking for the type of object you’ve received, you could use [*something] or Array(something).

Let’s assign two variables. The first one is a single digit and the second one is an array of digits.

stuff = 1
stuff_arr = [1, 2, 3]

In the following example, I use [*...] to loop through whatever is given.

[*stuff].each { |s| s }
[*stuff_arr].each { |s| s }

Same in this one but using Array(...).

Array(stuff).each { |s| s }
Array(stuff_arr).each { |s| s }

5. Double Pipe Equals ||=

The Double Pipe Equals is a great tool to write concise code.

It’s actually equivalent to the following:

a || a = b # Correct

And not this one, as a lot of people think:

a = a || b # Wrong

The second one doesn’t make sense because there is no point reassigning a if we already have it!

This operator can be used to create methods like this in your classes. I love to use it for calculations.

def total
@total ||= (1..100000000).to_a.inject(:+)
end

Now you could have other method calling total to get the total value but it will only be calculated the first time.

6. Mandatory hash parameters

This one was introduced in Ruby 2.0. Instead of just defining a method that takes a hash in parameters like this:

def my_method({})
end

You can specify the keys that you are waiting for and even define default values for them! a and b are mandatory keys.

def my_method(a:, b:, c: 'default')
return a, b, c
end

We can try to call it without giving a value for b but it won’t work.

my_method(a: 1)
# => ArgumentError: missing keyword: b

Since c has a default value, we can just call the method with a and b.

my_method(a: 1, b: 2)
# => [1, 2, "default"]

Or with all of them.

my_method(a: 1, b: 2, c: 3)
# => [1, 2, 3]

All we are doing is passing a hash and using some visual shortcuts but obviously, you can also pass a hash like this:

hash = { a: 1, b: 2, c: 3 }
my_method(hash)
# => [1, 2, 3]

7. Generate array of alphabet or numbers

You might want to generate a list of numbers or put the entire alphabet inside an array. Well, you can use ruby ranges to do this.

8. Tap

Tap is a nice little method that improves code readability. Let’s take the following class as an example.

class User
attr_accessor :a, :b, :c
end

Now let’s say you want to instantiate a new user and assign a value to each of its attributes. You could do it like this:

def my_method
o = User.new
o.a = 1
o.b = 2
o.c = 3
o
end

Or you could use tap to do it like this.

def my_method
User.new.tap do |o|
o.a = 1
o.b = 2
o.c = 3
end
end

Basically, the tap method yields the calling object to the block and returns it.

9. Default value for hash (Bad trick)

By default, when trying to access a value not defined in a hash, you will receive nil. You can actually change this at initialization.

EDIT: Don’t do this unless you know what you’re doing. Checkout the comments below for a complete explanation.

In this first example, we define the default value to be 0 so when a[:a] is called, we’re getting 0 back and not nil.

a = Hash.new(0)
a[:a]
# => 0

We can pass anything to the Hash initializer. Let’s try with a hash!

a = Hash.new({})
a[:a]
# => {}

Or a weird string:

a = Hash.new('lolcat')
a[:a]
# => "lolcat"

10. heredocs

I personally dislike seeing heredocs that break the code flow and indentation. Since EOT takes into account the leading spaces, you usually have to stick the content to the left like this:

def my_method
<<-EOT
Some
Very
Interesting
Stuff
EOT
end

But there’s a trick to avoid that. By using the gsub method with a short regex, you can automatically remove the leading spaces which allows you to keep your indentation consistent.

def my_method
<<-EOT.gsub(/^\s+/, '')
Some
Very
Interesting
Stuff
EOT
end

I hope you enjoyed those little tricks and I’m sure you already knew some, if not all, of them. Let me know if you have other Ruby tricks that should be added to this list! If you want to learn about one big Ruby on Rails trick, checkout Modular Rails ;)

Vagrant is a tool that allows you to create sharable and reproducible development environments. Here’s a complete overview of how to use it with your Ruby on Rails applications.

What is Vagrant?

To make development environments easy, Vagrant offers a way to encapsulate everything you need to run a specific application inside a virtual machine. Every developer will work using this same virtual machine that, in most cases, will be as close as possible to the production environment.

Even with your application running inside a virtual machine, you can simply edit the source code in local with your favorite editor and the changes are instantly reflected inside the virtual machine.

3 reasons to use Vagrant

Vagrant is a great tool to manage development environments. Here’s why you should use it.

Once the Vagrant configuration is written for a project, there is nothing else to do for people who work on it. Simply get the project folder, run the vagrant command to generate the specified environment and that’s it.

3. No more ‘It works on my machine’

Vagrant can be used to generate exactly the same environment that is used in production. That means no more problems when developing on OS X and pushing to a Linux server. Just setup Vagrant to use the same Linux distribution than your production server and you’ll be fine.

Install Vagrant

Installing Vagrant is quite easy. You will also need Virtual Box to run the virtual machines (there are other options available but Virtual Box is free).

Create a sample Ruby on Rails application

To show you how simple it is to use Vagrant, we’re going to generate a Ruby on Rails application.

rails new vagrant_jutsu && cd vagrant_jutsu

Now let’s initialize Vagrant for this project. The following command will add a file named Vagrantfile where we can define the configuration for Vagrant.

vagrant init

Let’s add a box!

Create a box

So first, what’s a box? It’s simply a virtual machine with a specific operating system that can be duplicated. When setting up Vagrant for a new project, the box specified in the configuration will be copied to create the virtual machine for your current project.

You can see a list of boxes available here: https://atlas.hashicorp.com/boxes/search

And we can easily add one with the following command. I have to warn you though, it’s going to take a while.

vagrant box add ubuntu/trusty64

For this jutsu, I’m using an Ubuntu virtual machine as you can see in the command.

[

Update the Vagrant config

We’re getting to the juicy part: the configuration! Vagrant comes with a lot of options so you can make it work the way you want.

Here’s a basic configuration that you can use for this jutsu. You can find more details about the Vagrantfile configuration here.

In this one, we specify that we are using the box named ubuntu/trusty64 and that we want to bind anything running on port 3000 inside the virtual machine to the port 2000 on our host.

Source Code

Conclusion

As you’ve seen throughout this jutsu, working with Vagrant won’t change much of your workflow but it will provide a great way to be sure everyone has the same environment and that it’s the closest possible to production.

Checking that emails are correctly sent on your development machine can be hard since you often don’t have a functional SMTP server and you don’t want to send emails everywhere anyway. How to ensure that your emails are correctly sent and at the right time? Letter Opener is here for you.

Letter Opener is a nice little gem created by Ryan Bates that will allow you to preview sent emails in your browser. Let’s see how it works!

The Project

To learn how to use Letter Opener, we’re going to create a super simple Rails application. We’ll install the gem, configure it and then create an email that will be sent every time we access the main page of our application.

Versions used

For this jutsu, I used the following version of Ruby and Ruby on Rails.

Ruby: 2.2.0
Ruby on Rails: 4.2.0

1. Generate a Rails application

First, let’s create a new application. Navigate to your projects folder and run the following command.

rails new letter_opener_jutsu

2. Install Letter Opener

Then we need the Letter Opener gem. Since we’re only going to use it in development, we can specify the development group.

gem "letter_opener", :group => :development

Don’t forget to bundle.

bundle install

3. Config Letter Opener

We need to tell our Rails application to use Letter Opener in development. To do this, we can simply add the following line to the development environment file: development.rb.

6. Preview it!

Access http://localhost:3000. A new tab should be opened in your browser showing the email that we just created.

[

7. Work on your email

Letter Opener is great to see when emails are actually sent and if everything looks correct inside each email. However, when desiging an email, there are better and faster ways to preview your email.

When we generated our mailer, Rails also created a file named user_mailer_preview in the test folder. In this file, we can create one method for each of our emails to preview them super easily in the browser.

This is actually a feature from the mail_view gem that was integrated in Rails 4.1. If you use an older version of Rails, you can simply add the gem to your application.

Modular Rails was finally released on Thursday last week. It was a very interesting experience for me to publish my first book and I want to share with you the whole story. How and when I started the book, what problems I encountered and much more. This is a long post so you might want to save it for later ;)

The story behind Modular Rails started over a year ago, in 2013.

FYI, Samurails was the name of Devblast before I decided to re-write it from scratch and rebrand it ;)

The Idea

If you’ve read Modular Rails, you know that I started working on modular applications around two years ago. A year later, I started to research about alternative and passive income that could complete my full-time job salary. I ended up on Nathan Barry’s website. I think he had just published one of his books and he was sharing how much his book had been a life changer. I was pretty impressed and super interested.

People were eager to learn what Nathan had to teach, the stuff that he learned while he was working as a designer. So I thought if he could do it, maybe I could too. Easier said than done.

I started to think about different topics for a book like learning Ruby on Rails (useless trying to top The Rails Tutorial). But then, I realized there was one thing that I was doing everyday that wasn’t really available anywhere on the Internet: modular applications. When I created my first modular application, I spent hours reading code from different projects, learning how Rails engines worked, how to build gems and so on. So maybe I could share it and people would want to learn it!

I didn’t have much to lose anyway. In the worst case scenario, I would end up having wasted my time and that’s it.

Lazy is good

But I didn’t start. I never got to actually work on the book even after having defined the plan and what I would be talking about. I just let it rot. For almost a year, I didn’t do anything. I even stopped posting stuff on my website. At that time, it was still named thibaultdenizet.com. I think it was around November 2013. I just focused on other stuff for a while.

Fast Forward 6 months

Samurails

When I had spent enough time slacking, I decided to checkout my blog and see if it was getting some traffic. I was really surprised to discover that I was getting around 200 people per day. I was even more surprised to find my series of articles about Single Table Inheritance ranking at the first spot on Google!

Maybe I should write more articles and tutorials since people seemed to like them. The problem was that I didn’t really like the layout of the site and I didn’t want to use my name as the domain name anymore. The blog wasn’t about me, it was about Ruby on Rails. I remembered one of my friends who mentioned to me the name Samurails a few years back. I asked him if he was using it and if I could use it for my website. He agreed and I quickly bought the domain name and setup a 301 redirection from thibaultdenizet.com.

The style still had to change. I didn’t like it. What I like is the orange color. It’s actually my favorite color! I had to use it on Samurails. I was totally in the Flat UI thing at that time so I found a nice Wordpress theme from Colorlib and set it up. The last step was to find a nice logo. So I started to look for some images on BigStock photo and found this awesome artist who was making amazing icons. I found some cool looking samurai head, changed a few things and I ended up with the current logo:

I also rebranded my tutorials and called them jutsus to match the name of the website. I wrote a few more jutsus before the idea of writing a book came back to my mind…

Authority

I went to Nathan Barry’s website again and see what he was up to. I found out he wrote another book: Authority, a book that shows you how to self-publish your own book. I instantly bought it and started to read it. It’s less than 200 pages but it’s packed with invaluable information. I loved it and finished it super fast. There are some success stories included in the book that will give you a motivation boost too!

This was around September 2014.

The Name

I was looking for a name but couldn’t find something awesome so I settled on ‘Building Modular Applications with Ruby on Rails’. Jeez. That’s an annoyingly long name but whatever: it delivers the message. Now that I had a name, I was ready to setup a landing page to start collecting emails from interested people.

Create a website for the book

I created a sub domain and put a simple HTML page with some Bootstrap style. Got a Mailchimp account and started collecting email addresses. I had a lot of work in my full-time job at that time and I didn’t want to start working on the book if nobody wanted to buy it. So I waited around two months before starting to write the book and I was able to collect some email addresses during that time.

Start writing

In November 2014, the time had come! I redefined the plan for the book and started to write the first two chapters: The Modular Way and Modular Rails. At that time, they were named Introduction to Modularity and Modularity with Ruby on Rails (I did a lot of renaming right before the book was published). These two chapters came quite easily. There wasn’t much code to show and the chapters were quite short.

Stop writing

After writing the first two chapters, I didn’t do anything for a month. Then December went by. I went back to France for Christmas and didn’t work on the book at all.

No more slacking, fix a release date

It was around mid-January when I decided that I had to stop lying to myself. I would never finish the damn book unless I work on it everyday and commit to it in front of everyone who was waiting for it. I created a page on Samurails where people could see the progression of the book and see what I was doing everyday. I committed to work at least 2 hours per day. But that still wasn’t enough to ensure that I will ever finish it. I know myself and I’m a professional procrastinator. So I set a release date. And a short one because people have been waiting for the book long enough! Once again, this was mid-January and I fixed the release date on February 26.

I had a lot to do.

Work my ass off

For the following month, I spent most of my evenings and at least a full day each week-end (I still needed to have a lazy day to reboot) working on Building Modular Applications with Ruby on Rails. I hated the name. Anyway, I started to work on chapter 3 (which is now 4). First, I built SamuraiCRM and kept notes of everything that I was doing. I also committed the source code very often. Then I took my notes and structured the chapter 3. It took me a while to put all the source code, step by step, together. Then I had to test all the steps one after the other to be sure that everything was working correctly. The last step was to add some explanation before and after each piece of code. I repeated the same process to write the chapters 4 and 5. After that I had to retest everything from chapter 3 to chapter 5. That was very annoying to do but essential to be sure that the steps and the flow were error-free. The last chapter was easier to write since it’s a lot of theory with just a bit of practice.

The first draft of the book was ready 2 weeks before the release. But I still had so much to do!

Formatting & Editing

The fun part started after finishing writing the book. I wrote it using Sublime Text with the great MarkdownEditing package. I love using Sublime Text to code and it’s great to be able to use it to do my writing too. I first wrote my book as a collection of markdown files:

00_intro.md

01_introduction_to_modularity.md

02_rails_and_modularity.md

…

Since I wanted to be able to share it easily with some of my friends, I decided to use Google Doc. I took each chapter, paste it in the Wordpress backend of Samurails and got the HTML result with Samurails style. Then I just had to copy each blog post generated from Samurails to Google Doc. Each chapter got its own file because Google Doc cannot really handle huge documents. Get over 30 pages and it will start lagging like crazy.

Once each chapter was is in its own Google Doc, I started to ask some of my friends to review the book. I also read it entirely, changed a few things and retested all the code. I also did a lot of editing and formatting and improved the look of the source code in the book by putting each code example inside a 1x1 table. The release was approaching and the book was almost done. I only planned to provide the book as a PDF at that time and the PDF generated by Google Doc looked good. Getting that PDF was quite hard. However, after merging all the chapters into one Google Doc, it was super slow. Exporting as a PDF only worked 1 out of 10 times so it was a pretty annoying process to download it.

The nightmare starts!

Then, the shit hit the fan! I was playing with my Google Doc PDF when I realized that copying and pasting the code samples was breaking the layout and removing all the spaces. Holy cow. Time to try some other exportable format available on Google Doc.

After trying the PDF, I tried the docx file. I opened it with Pages and I thought it looked alright. I could export to PDF: the copy/pasting wasn’t perfect but I could live with it. The problem was the table of contents. It had no links to each section! It’s apparently a bug in the last version of Pages… Great!

How about OpenOffice files? I gave it a try. Nope, nothing good came out. When exporting to PDF, the result was not what I wanted.

I’ve always hated regular word processor like Word, OpenOffice and Pages. I like Google Doc for the sharing capabilities but I’ve learned my lesson. I don’t recommend using any of those tools to write a programming book.

I was getting a bit desperate. I had 2 days left before the release. I was sleep deprived and ready to give up and delay the release. I was ready to do anything, even switch back to markdown and redo all the formatting. So I checked out Pandoc once again but I was too stressed to dig in the documentation and spend hours understanding how to get what I wanted.

Maybe Leanpub or Gitbook could be my savior. I tried both but wasn’t convinced at all. I don’t like the idea of not having complete control and not knowing what is going on. I couldn’t even find how to change the style of the generated files!

I was hitting the bottom of desperation. Just trying out everything. Nothing was working. Since all the generated PDF sucked, I thought maybe I should provide other formats like EPUB or even a static HTML website… But how to do that?

The Solution

Then I remembered The Rails Tutorial. I checked how the book was written and I discovered the magnificent Softcover. An amazing gem that generates a book folder where you just have to write your book. I was so happy to find Softcover. I could write each chapter in its own markdown file and define the order inside some configuration file. Plus, there is a free ebook written by Michael Hartl himself that shows you how to use it. It shows you how to use Softcover, how to generate EPUB, MOBI and PDF and how to style them.

The best thing about Softcover is the way you write the book. First, you start a web server with softcover server that gives you access to a HTML version of your book available at http://localhost:4000. Now you can just go work in your markdown files and the website is automatically refreshed!

The only problem was that my original markdown files were outdated so I had to use the Google Doc content to create the new markdown files… and reformat everything! It took me hours to do it. I didn’t sleep much in order to have everything ready for the release date.

Softcover is also a publishing platform but I planned to use Gumroad from long time ago and already set up everything. So I used Softcover to generate PDF, EPUB and MOBI and style them. And then I realized you couldn’t share easily the HTML version. Indeed, the HTML version was meant to be push to Softcover and made available online. I didn’t want that. I wanted people to have a static website that they can access anytime and follow my book chapter by chapter. It was also much easier to copy source code from a web page than from the PDF.

To generate a static version, I simply used wget. This little tool is just so powerful. I ran the Softcover server and wget the entire thing with the following command:

wget -rkp -l6 -np -nH -N http://localhost:4000/

And that’s it! I had a good looking static website ready to be packaged. Finally, I was able to make everything in time. Plus, it was better than what I originally planned for since I had more formats: HTML, PDF, EPUB, MOBI.

Define packages

Writing the book is just the first part. Then you need to prepare the book for the release. Nathan Barry recommends to have different packages including other formats (video, case studies, …). It was really hard for me to find what I should add to the higher packages but finally I decided on the following:

The Source Code

Screencasts

Case Study

Interview

Fixing the prices was also a challenge. I find it very hard to assign a value to a knowledge that you already have. You really need to think about the value for someone who doesn’t know anything about what’s in your book. I ended up with the following prices: $39, $79 and $149.

Changing the name

A bit before all the troubles that you’ve read about above, I realized that I hated the name. Too long to type, couldn’t even fit it in a tweet with other details. So lame!

I had to rename it. And then I found it: Modular Rails. It was just so simple and such a great summary of what was the book about. I loved it, submitted to some of my friends and they loved it too. ‘Building Modular Applications with Ruby on Rails’ was killed.

Make the screencasts

Making the screencasts was hard. I didn’t have much time left but I wanted to include at least 5 screencasts. I made a list of different topics and picked the ones which provided the most value for the less effort (20/80!). I ended up having the following screencasts:

The Modular Workflow

Create a Private Gem Server

Clean your Modules with Decent Exposure

Configure your Models

Create a Linking Module

I didn’t have much experience making screencasts (and I still don’t!) so I just did the way I felt was the best one. I wrote a list of the steps to follow in the videos and just use Quicktime to record my screen. The good thing with screencasts is that you can edit anything wrong. You can pause for 30s thinking about the best way to explain something and just cut it in the editing process. That’s awesome! I used iMovie to edit the screencasts. I really enjoyed making the screencasts for Modular Rails, it taught me a lot and I definitely want to produce more for Samurails!

Force friends to read the book

It’s important to have some feedback before you release a book. So I -forced- politely asked some of my friends to review the book and tell me what they thought about it. I also asked some quotes from them to put on the website.

Release the book

Finally, the time came to release the book. I wanted to release it at 9pm UTC +7 (Bangkok Time). Unfortunately, I couldn’t. Everything was ready but I forgot to take something into account.

The time to upload 5 screencasts to Gumroad. The screencasts were ready since the day before so I could have uploaded them. I just didn’t realized it would take me more than 2 hours to upload everything… The book was finally released around 11pm Bangkok time.

After pushing the updated website for the book, I shared it on Hacker News and Reddit. Then I sent a newsletter to the people who were waiting for the book!

The Result

I’m happy to stay that I sold more than one copy of Modular Rails! I was really surprised when I sold my first Complete Package. Thanks to everyone who bought Modular Rails and I hope you learned a lot with it ;)

Conclusion

Writing Modular Rails was a very enlightening experience. That’s why I’m already thinking about my next book. I actually have 3 different topics and each of them could become a very nice book. I just need to decide which one is the best and get started on it. But first, I want to work on Samurails. I want to provide more jutsus and start making screenjutsus!

1. What is modularity?

Modularity is about isolating the functionalities of your application into independent and interchangeable components. With Ruby on Rails and my approach, it implies creating modules as Rails engines and build your application bloc by bloc. Ruby on Rails applications are usually monolithic.

2. Why would I want to build a modular app?

The main advantage of a modular applications is to have reusable and interchangeable components. For example, you could create a forum engine for one app and reuse it in another one. Of course, you can write more specialized engines adapted to your business.

3. When should I use modularity?

4. I’m building my first Rails application. Should I make it modular?

I don’t think it would be a good idea. Building modular applications requires a good understanding of Ruby and Rails. Create a few regular Rails applications before you checkout modularity and see if it fits your needs.

5. What is Modular Rails?

Modular Rails is the book I’m currently writing where I exposed everything I’ve learned in the past years about building modular applications with Ruby on Rails. You can subscribe to my newsletter below to get the latest updates. If you want to learn more about the book progression, checkout this page.

6. How should I use Git with my modular app?

The best way to organize your modular application is by separating everything in different repositories. Each module should have its own repository just like the parent application. This setup allows different teams to work on different modules and branches easily while sharing a common parent application.

7. How to reuse my modules easily?

The easiest way to share and reuse your modules is to package your Rails engines as gems. You can then push them to RubyGems and easily add them to your Gemfile.

8. What if I want to keep my modules private?

You can! And it’s not even hard. Instead of pushing your modules to RubyGems, you can push them to your own private RubyGems! It can easily be setup on a cheap VPS, making your gems available easily and privately. You can still use the Gemfile to get them by adding one line at the top specifying your private gem server.

9. How to version my modules?

The best way to version your modules is to follow the Semantic Versionning. You should give it a read, but here’s the summary:

Given a version number MAJOR.MINOR.PATCH, increment the:

MAJOR version when you make incompatible API changes, MINOR version when you add functionality in a backwards-compatible manner, and PATCH version when you make backwards-compatible bug fixes.

Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format.

10. Is it hard to push a modular application live?

Is pushing a Ruby on Rails application which has a few gems in its Gemfile hard? Because that’s basically what you will be doing once you packaged your engines as gems. A modular application can be pushed very easily to Heroku or to any kind of VPS/Server.

11. Which hosting provider can I use for my modular application?

Any hosting provider supporting Ruby will be fine!

12. How can I learn more about modularity?

Well, you can start by reading the series of article I wrote. And you can read my book Modular Rails if you want to keep learning!

13. Still have some questions in mind?

Now that you know more about Modular Rails Architectures, I want to show you how you can build a very simple modular application. If you like it, don’t hesitate to subscribe to my newsletter below to learn when my book ‘Modular Rails’ (recently renamed) will be released.

This is the fifth article in the Modular Rails series. Here are the other posts:

The Idea

We’re going to build a very simple web application: A Todo List! To create this app, we will first generate a Rails application that will act as our parent app. Inside, we will generate a ‘Todo’ engine. Let’s go!

Getting started

First, let’s generate a new Ruby on Rails application:

rails new ModularTodo

The next step is to generate an engine!

cd ModularTodo && rails plugin new todo --mountable

We will also create an ‘engines’ folder to store the engines (even if we just have one!).

mkdir engines && mv todo ./engines

Engines, just like gems, come with a gemspec file. Let’s put some real values to avoid warnings.

Monolithic vs Modular

Creating a modular application is quite different from building a traditional Ruby on Rails application.

Regular Ruby on Rails applications are monolithic apps. They are self-contained applications that will do what you programmed them for. Note that this is not a bad thing. Ruby on Rails is known for its fast prototyping that will let you create a MVP (Minimum Viable Product) fast and easily.

Now, let’s talk about modularity. There are many ways to make a modular application. After all, the main principle of modularity is to build something with a set of modules.

These modules can be micro-services for example. But that’s not the approach I want to talk about in this article and in my book. What I want to teach you is how to build a modular Ruby on Rails application composed of a set of Rails engines as your modules.

Now that we know the difference between monolithic and modular applications, let’s see how to organize our app!

Nota Bene

By using engines as modules, you could say that we are still deploying a monolithic application. That’s true, but you can still extract, add or export modules easily. If you need to, you could even extract one engine and run it in a new application as a micro-service. That’s the power of what I want to show you!

Modular Architectures

There is not just one way to organize your code. Here, I’ll go over three architectures that I’ve personally played with. I’m sure there are more and if you have any suggestions, I would be happy to talk about them with you!

As we said earlier, we are going to separate a monolithic application in small modules. But what should we put in these modules? Since we will be using Rails engines, we can put models, controllers, views, migrations, tests and so on. Basically everything that you will find inside a Ruby on Rails application.

But how do we organize all that? Should one module have all the models? Or should one module have a model-view-controller silo?

Approach 1 - Three Tier Modules

You should be familiar with the three tier architecture. If not, here’s a definition from Wikipedia:

‘Three-tier architecture is a client–server architecture in which the user interface (presentation), functional process logic (“business rules”), computer data storage and data access are developed and maintained as independent modules, most often on separate platforms.’ - Wikipedia

Since the views are so tied to the rest of the application in Ruby on Rails, a good way to follow this pattern is by using an API and a Javascript frontend application.

The idea is to separate the application into the following modules/engines:

This engine contains an API allowing external applications to connect to it through RESTful URLs. This engine depends on the Engine 1.

Engine 3 - Javascript application

The Javascript application should be built with the help of a frontend javascript framework such as Angular.js. The Javascript code can be contained inside the main Ruby on Rails application. Another way, which I personally prefer, is to create this application as a standalone by using tools such as Yo, Grunt and Bower.

Here’s a schema of this architecture:

This architecture can be optimized based on your needs. For example, you could put the second engine code (API) directly inside the parent application. You could also separate the Engine 1 into smaller engines. Keep reading to learn more about other architectures to find the perfect one for your needs!

Approach 2 - Hybrid Component Based

This approach is the first one I tried when I started to work on modular applications. With time, I realized that it’s not the best solution. The idea is to have a couple of engines representing the minimal logic of your application. You can then plug new engines on them and add more features.

With this architecture, the ‘core’ of your application will be composed of at least two engines. Let’s call them Data and Presentation. The Data engine contains the Models and the Migrations. The Presentation engine includes the controllers and the views.

Now, you can start adding more modules which will depend on Data and Presentation.

Feature 1 engine (models + controllers + views)

Feature 2 engine (models + controllers + views)

Feature 3 engine (models + controllers + views)

That might look abstract, so to give you something more concrete, here’s how your Gemfile might look like with this architecture:

Approach 3 - Full Component Based

The Full Component Based architecture is a refined version of the previous example. In this one, we remove the Data/Presentation engines and the separation of the models, views and controllers into different engines. Instead, each engine encapsulates all the components required to make itself work. That means each engine is a micro Rails application containing models, controllers, views and specs.

Core (models + controllers + views)

Feature 1 (models + controllers + views)

Feature 2 (models + controllers + views)

…

In this case, the Core could be run alone inside the containing application and would offer only limited features. For example, we could simply include the minimum code for users to be able to login and access an empty dashboard. We can then add completely encapsulated features to the core to improve our application.

This is a very good solution to build modular applications with Ruby on Rails. We will build an application of this type in Modular Rails.

Here’s a diagram of this architecture:

Want to learn more?

You can continue reading about modularity with this article where I show you how to create your first modular application.

You can also checkout the book I wrote about modular applications : Modular Rails.

Don’t hesitate to subscribe to my newsletter in the form below or on the book website to receive a free sample of the book.

Now that you know more about the different use cases of modularity, let’s talk about how we can create modular applications with Ruby on Rails. Rails comes with a nice feature known as engines that let you create mini Rails applications. You can then easily use these engines as gems inside a regular application. Let’s talk about this engines thing!

This is the second article in the Modular Rails series. Here are the other posts:

Quick overview of Rails engines

As said earlier, Engines are small Rails applications that can be used to add functionalities to the application hosting them. The class defining a Ruby on Rails application is Rails::Application which actually inherits a lot of its behavior from Rails::Engine, the class defining an engine. We can say that a regular Rails application is simply an engine with more features.

Engines are also close to Plugins. Plugins are not really used anymore since Rails 3.0 but the command to generate an engine is actually the same used to generate a plugin.

The command looks like this:

rails plugin new my_module --mountable

Mounting an engine

An engine cannot live on its own so you need to mount it inside a regular Ruby on Rails application. Don’t worry, it’s super simple! All you have to do is this:

In this example, we mounted the SuperEngine engine at the root of your application. That’s what you want if your application is logicless. However, if your Rails application has some content, you probably want to do the following:

Now the Forum engine can be accessed by going to /forum but the root (/) will ignore the engine and find the root path in the mother application.

Namespacing

Engines can and should be namespaced. That means that 2 models with the same name, one in an engine and one in the host application, won’t clash. When generating an engine, everything is automatically namespaced: tables, models, controllers. If you generate an engine named Core and a User model, the User table will be core_users and your model will be Core::User.

As you will be able to read it in the book, I recommend going one step further and adding another level of namespacing. If you plan to create a lot of engines and want to avoid any future conflict, you can just namespace with your project or company name at the first level and then use the engine name as the second namespace.

Engines in the wild!

Even if you’ve just discovered engines, you’ve probably been using them for a while. One of the most famous authentication gem is actually an engine. Of course, I’m talking about Devise! Basically, any gem that will provide you with some Rails-related component such as migrations, controllers, views or models is usually an engine packaged as a gem.

There are also some open source modular applications such as Spree. Spree is an open source e-commerce solution built as a modular application with Ruby on Rails. With their solution, it’s possible to either use all the modules or just pick the ones you need! Awesome!

It’s been a while since my last post and I haven’t published any Jutsu in a while… No good!

Let’s talk about it.

So you might be wondering why. Or maybe you know. Of course, that’s because I’m focused 200% on Building Modular Web Apps with Ruby on Rails! I decided to keep away all distractions for now and writing a bit everyday. Which is far from easy. Life happens, friends want to go out for a drink, girlfriend want to see a new love movie, Facebook, 9gag, youtube… so many distractions, so little time.

So to counter that, I bought a paper calendar with a big box for each day where I can draw a cross if I hit my objective: spending at least 1h per day writing the book or working on the CRM app. That’s a known trick that I learned from Nathan Barry and his 1000 words a day rule. The idea is to create an unbreakable chain. If you’ve spent 100 days doing something everyday, you don’t want to break it! But it’s not that easy. In the last 10 days, I had to skip 2 days because of unplanned stuff. As I said, life, stuff, blabla.

Oh, you know Nathan Barry, don’t you? That’s thanks to this guy that I started writing my book. And you can too! But maybe you don’t know how to? Then take a look at Authority. That’s the book Nathan Barry wrote for self-publishers that contains everything you need to know. And it actually works. Nathan published 3 books and had a lot of success.

So let’s go back to Building Modular Web Apps. The chain thing is good, but it’s not foolproof. How can I add more constraints? How about I make the calendar public with all the time I spent everyday working on the book. I think that’s a great idea! I’m gonna create a new page where you can see what I did each day, just like commits :) I will also reveal a temporary table of content so you can all see the progression.

No more slacking, no more excuses.

Let’s make it even more fun… and stressful. Yeah, I’m gonna set a release date.

Building Modular Web Apps with Ruby on Rails will be released on: 26/02/2015

I just released my first screencast about Ruby on Rails. It’s something I’ve been wanting to do for a while but always postponed. To avoid delaying more, I decided to create a short screencast to see what I could do.

That was pretty fun! I still have a lot to improve but I’m currently learning more about screencasting and video editing.

Anyway, here is the first Screenjutsu: Rails debugging with Pry-byebug!

Learning Ruby on Rails is a long journey. Due to the Ruby on Rails motto, conventions over configuration, you need to learn about a lot of hidden stuff.

I still remember the first time I had to work on a Ruby on Rails application. I didn’t even know Ruby at that time. That was a disaster. After fighting my way through the code I figured out how to do what I was supposed to do. But I didn’t understand how I did it. I didn’t get how all the pieces fitted together.

I didn’t understand what was Ruby on Rails and how it worked exactly. Fast forward a few years and a hell lot of lines written, I’m quite confident with my Ruby code. Enough to write a book about the subject. What I want to share with you today is the list of best resources to learn Ruby on Rails. I didn’t know about those great books and platforms when I started but I wished I’d known them.

The resources I’m going to present you can take you from knowing nothing about programming to knowing everything about Ruby on Rails. That’s a huge step! What you are currently doing doesn’t matter. You could be a Python developer or a professional wrestler. Whatevs. By using the platforms I’m gonna show you, you can become an expert in Ruby on Rails. But hold on a minute. I’m not saying it will be easy. You will need to be dedicated as learning a programming language is not the easiest thing in the world. Lucky us, it’s not the hardest either!

The best way to become an expert is to experiment and create your own applications.

Railscasts is a great website containing over 400 screencasts about Ruby on Rails and its ecosystem. You can access a lot of the videos for free but to access all of them you will need a subscription. Don’t worry, it’s only $9 a month! The screencasts are really great and Ryan Bates, the author, is a dedicated Rubyist who has published numerous gems as you can see on his Github account.

Unfortunately, Railscasts has not been updated for more than a year. Ryan apparently burned out producing so much high quality content. Let’s hope he is well and enjoying life and coding. If you’re looking for an alternative, you can check the RubyTapas screencasts!

Treehouse - $25 with 2 weeks Free Trial

Videos are a great medium to learn if you ask me. By following a set of videos you can learn so much! Why? Because you can see how a Ruby on Rails expert codes and how his coding environment looks like. How he do it, how he think about a problem… Well that’s exactly what Treehouse is offering you. A cheap and simple way to make you an expert programmer wherever you’re coming from! And what’s best than a video to show you a websites that’s going to teach you coding through videos?

[embed]https://www.youtube.com/watch?v=GEYQiMCWRW4[/embed]

Treehouse is a great platform that have helped people quit their job and start a career as a developer! That’s how powerful it is.

The Rails Tutorial is another great resource to learn everything about Ruby on Rails. The most awesome part is that it’s available here for free! If you’re ready to invest a bit of money, you can also buy the book for offline reading. There are also more pricey options that come with a set of amazing screencasts.

In The Rails Tutorial, you will learn how to build a complete Ruby on Rails application. Everything is covered: hosting, authentication, authorization, database… Basically, everything you need to know ;)

GitHub - Free

Finally, a good way to learn how to code… is to read code! You will need to know the basics but reading the code of Ruby on Rails itself or of well written gems will teach you a lot about the Ruby coding style. You just have to absorb this knowledge and implement it in your own code.

Now you’re ready to learn Ruby on Rails! It will be a challenging and fun journey ;)

]]>
Sat, 13 Dec 2014 00:00:00 +0000http://devblast.com/b/learn-ruby-railshttp://devblast.com/b/angular-js-cors-get-post-put-delete
I’ve received requests to talk about PUT and DELETE calls on my article about CORS with Angular.js. So here it comes!

If you don’t have the code yet, you can get it from Github. Don’t hesitate to read the original article for the setup details.

Let’s get started!

The Headers

To allow Get and Post calls from our angular.js application, we used the following code in the sinatra app:

The View

Remember the ugly view that we created to start our GET and POST calls? Let’s make even more hideous! We are just going to reuse the POST style and change the ng-model name and the function called on click.

]]>
Thu, 11 Dec 2014 00:00:00 +0000http://devblast.com/b/angular-js-cors-get-post-put-deletehttp://devblast.com/b/sti-keeping-subclasses-file
I recently received a comment on my STI tutorial asking how to keep all the subclasses in one file. Indeed, creating one file for one line of code is a bit overkill but that’s the way Rails works: Conventions over configuration.

However, I thought it was interesting to talk about 2 ways to avoid creating new files.

We had to split the subclasses in different files to use Rails autoloading. Without it, the classes Lion, Meerkat and WidlBoar were not available until we made at least one call to Animal. Let’s see how we can keep everything in the same file.

1. Autoload

Here’s the code we want to fix. If you use the following, start a rails console and try to access Lion, you will get an undefined error.

See what we did there? Now Rails will autoload the module Savanna which contains our parent class and its subclasses. Main inconvenient: you will have to add the module name before your subclasses when you use them:

Savanna:Animal
Savanna::Lion
Savanna::Meerkat
Savanna::WildBoar

If you don’t like to have a lot of files when using Single Table Inheritance, you can use these methods. However, I would still recommend splitting your subclasses in different files, especially if you plan to add some code inside them.

In the first post of the modularity series, I shared with you what building a modular Ruby on Rails application means in terms of project organization. In this article, we’ll go over a few use cases that could use a bit of modularity.

This is the second article in the Modular Rails series. Here are the other posts:

Before we go over a few examples of modularity uses, I want to talk about the reusability of the engines you will create.

The idea is that instead of building a monolithic application, you will build your own Devise and Active Admin gems/engines. Like this, you will have a catalogue of engines that you can reuse in different applications.

For example, you might end up with:

An User engine that deals with user creation and login

An Admin engine to represent your admin panel

A Payment gateway engine

These engines could be added to various Rails applications and customization could be added on top of it, directly in the parent app or in new engines.

For a task management application, you might do the following :

Add your User, Admin and Payment engines

Create a new engine to contain the Task feature

And you would have your new app ready in no time! That’s the power of modularity.

Web Agency & Freelancer

As a web agency or a freelancer, you probably build a lot of Ruby on Rails applications. And a lot of them probably share the same logic and features. By creating a set of engines, you will reduce the amount of work for each project. You will still have to do some customization obviously, but you will save a lot of time!

Since your client’s projects will share the same engines/gems, it’s easy for you to provide bug fixes and improvements for ALL your clients at the same time.

Generic Application

Another good case scenario for modularity is a startup creating some kind of generic application with a layer of configuration. That probably sounds abstract so let me give you an example of such an application. Take the Stack Exchange network. If you’re looking to build something like that, then modularity is your best friend. You would probably have a set of modules present in every application in your catalogue. Then, you’d have some specific modules added on top of them to customize the application for a specific niche. Maybe for one application, you want a rating system, for another one you want to have commentable questions and answers and so on. All that can be achieved by building modular applications and using Rails engines as modules.

The Spree e-commerce project is an open-source project built in a modular way that let you create and customize e-commerce applications. Check it out!

Extendable Application

Spree is also built in a way, just like Wordpress, that allows users to create extensions/addons/plugins. By creating a modular application from the start, you will have to think about extending your own code in your future modules. That means thinking about hooks and things like that. That’s all about ‘eating your own dog food’. You’re building for yourself but also for everyone else who want to provide additions to your software.

Hybrid Application

Obviously, you don’t have to go all-in. By using gems like Devise or Active Admin, you’re basically already using modules inside your application. The idea is to separate the rest of your application in the same kind of module and make them reusable. The good thing is that you don’t have to do it for all your application. Find the pieces that you could reuse for other apps, and extract these small bits one at a time. Don’t hesitate to make this code open-source if you think it can be useful to other people!

In this post, I want to talk about hosting. I want to tell you, in my humble opinion, who is the best hosting provider for Ruby on Rails applications.

There are many options to host your Ruby on Rails applications, from cheap to very expensive. Some hosting provider have terrible platforms and services but some of them offers very nice services for an affordable price.

Best way to host your app

First, if you want to host a Ruby on Rails application, avoid shared hosting. This kind of hosting is good enough if you just want to host a simple blog but even for this, I’d recommend picking a Virtual Private Server instead. Getting a VPS gives you much more control on what’s going on in your hosting.

Plus, you can completely avoid the super slow FTP! SSH and SCP to the rescue.

That’s why for your Ruby on Rails applications (and any other kind of web app actually), I recommend a good VPS provider like Digital Ocean.

Digital Ocean

Note: A Droplet is a VPS in Digital Ocean’s jargon.

Samurails (now Devblast) has been hosted on Digital Ocean since the beginning and I never had to complain about it. The support is super fast to answer any question and problems get fixed quickly. I used to have a $5 droplet (first price) but it started to show its limitations when the traffic to Samurails increased. A few MySQL crashes pushed me to bump to the $10 plan and I didn’t run into any problems since. I added 2 small Rails applications since and everything runs well.

A $5 droplet is perfect for a simple website or blog. If you want to be safe however, you should use a $10 or $20 droplet to run your Ruby on Rails application. With a bit of tuning, you can get the most out of the droplet’s specs for a very affordable price! Seriously, that’s the price of 2 cups of coffee for a full month!

If Digital Ocean sounds interesting, you can use the following link to get $10 in credits (your first month or first 2 months for free!).

To stay transparent, I want you to know that this is an affiliate link so if you start using Digital Ocean after clicking on this link, I will receive a small commission. It didn’t affect the writing of this article and even without it I would still recommend Digital Ocean to anyone! This is a really great provider.

]]>
Thu, 16 Oct 2014 00:00:00 +0000http://devblast.com/b/best-hosting-provider-ruby-rails-appshttp://devblast.com/b/ruby-fizzbuzz-fibonacci
Ninth article in the Prepare for a Ruby job interview series. In this one, we’ll study two algorithms that are asked quite often in interviews : FizzBuzz and Fibonacci!

FizzBuzz

FizzBuzz is very often asked in an interview and apparently a lot of people cannot do it. The idea behind FizzBuzz is :

> "Write a program that prints the numbers from 1 to 100\. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz".

You should try it by yourself before checking the result. It really shouldn’t be hard. Here’s my solution :

]]>
Sun, 05 Oct 2014 00:00:00 +0000http://devblast.com/b/ruby-fizzbuzz-fibonaccihttp://devblast.com/b/big-o-notation-complexity-ruby
Tenth and last article in the Prepare for a Ruby job interview series. In this one, we’ll take a look at the Big O Notation and what is Algorithm Complexity.

Big O Notation and Complexity

Big O Notation tells you how complex is an algorithm depending on what you feed it. The important thing to understand with the Big O notation is that it only cares about the worst case scenario.

Here are a few examples of different complexities.

O(1)

O(1) means that the execution time of an algorithm is constant. You can pass 1 item or 1 million items, it will still take the same time to run.

def first_element_is_red?(array)
array[0] =='red' ? true : false
end

O(n)

O(n) means that the execution time of an algorithm will grow linearly depending on the input size.

Remember when I said the Big O only cares about the worst case ? In this example, we could find the value in the first iteration… or not find it at all, which would be the worst case. That’s why this algorithm has a complexity of O(n).

O(n^2)

O(n^2) means that for each increment of the input size, the speed of the algorithm will double.

If you want an example of this, we can simply write an algorithm that looks for duplicates in an array. Note the nested loop that increase the execution time since for each element, we have to loop through the whole list.

def duplicates?(array1)
array1.each_with_index do |item1, index1|
array1.each_with_index do |item2, index2|
next if index1 == index2
return true if item1 == item2
end
end
false
end

O(log n)

O(log n) is harder to explain. If I was to show you a graph, we would have a quick growth at the beginning, that tends to get slower in time if you increase the size of the input.

I recommend reading more about Big O notation and algorithm complexity, those were just a few examples to get you started ;)

I hope you enjoyed this series of articles. Don’t hesitate to check my Jutsus if you want to learn more about some specific gems ;)

]]>
Sun, 05 Oct 2014 00:00:00 +0000http://devblast.com/b/big-o-notation-complexity-rubyhttp://devblast.com/b/random-ruby-tricks-info
Eighth article in the Prepare for a Ruby job interview series. In this article, we will go over some random Ruby tricks and information.

The 4 ways to call a method

object = Object.new
object.object_id

object.send('object_id')

object.send(:object_id)

object.method(:object_id).call

Symbol vs String

Symbols are unique immutable entities as opposed to string which are mutable.

If you define a method at the top level scope, it goes to Object

One liner method declaration

]]>
Sun, 05 Oct 2014 00:00:00 +0000http://devblast.com/b/random-ruby-tricks-infohttp://devblast.com/b/8-best-books-learn-ruby-rails
If you are planning to learn Ruby on Rails or if you are still on the learning journey, books should be an important part of the process. Some people like screencast, other only learn by coding pet projects.

I like to read books and apply what I’m learning in small projects. If you’re like me, you will like this article. I’ve put together a list of the 8 best books to learn Ruby on Rails from my own digital library.

I ordered the list in the way I advise you to read them.

Getting Started with Ruby

First, you should start by learning everything about Ruby by reading Programming Ruby 1.9 & 2.0.
It will give you a great base about everything related to the Ruby programming language. Then, I’d recommend Eloquent Ruby to perfect your style and learn how to write clean code.

Focusing on Rails

Once you’re familiar with Ruby, you can start learning Ruby on Rails and build your first web applications. To do so, you can read Agile Web Development with Rails 4 which will teach you everything about the Rails framework.

Sharpening your skills

Now that you know how to code in Ruby and you are familiar with Rails, I’d recommend reading Design Patterns in Ruby and Rails AntiPattern. Those 2 books will show you the best ways to organize your code by using proven Design Patterns.

Don’t forget the Tests!

To complete your Ruby on Rails education, you should study the best way to write tests, and one of the best books to do that is The RSpec Book.

The next level

The last 2 books I want to talk about are not centered on Ruby or Rails, they are more about general programming knowledge. You should totally read them if you haven’t yet. I’m talking about Code Complete and The Pragmatic Programmer. Two great books that every programmer should have on his bookshelf!

Don’t hesitate to checkout my book, Modular Rails, to learn about a different way to build Ruby on Rails applications.

Programming Concepts

Class

Classes are the blueprint from which objects are created. They hold data and have methods that interacts with that data.

Object

An object is an instance of a class. Everything in Ruby is an object (Even classes which descend from the Object root class!).

A bit more about this root class :

Object is the default root of all Ruby objects. Methods on object are available to all classes unless explicitly overridden.

Atually Object inherit from BasicObject, a blank class :

BasicObject is the parent class of all classes in Ruby. It’s an explicit blank class.

BasicObject can be used for creating object hierarchies independent of Ruby’s object hierarchy, proxy objects like the Delegator class, or other uses where namespace pollution from Ruby’s methods and classes must be avoided.

Module

A Module is a collection of methods and constants. The methods in a module may be instance methods or module methods. Instance methods appear as methods in a class when the module is included, module methods do not. Conversely, module methods may be called without creating an encapsulating object, while instance methods may not.

Modules can be used as a namespace mechanism. They cannot be instanciated, as opposed to classes. They can be used as mix-ins to add logic to a class (Multiple Inheritance)

Method vs Function

Many languages distinguish between functions, which have no associated object, and methods, which are invoked on a receiver object.

In Ruby, all methods are true methods and are associated with at least one object. If you declare a method without being inside a class, the method will automatically be added to the Object class.

The only functions you will find in Ruby are proc and lambas that we’ll see later.

Level of accessibility

There are 3 levels of accessibility for a class method in Ruby :

Public : Can be called from outside the class.

Protected : Can be called from outside only by the defining class or its subclasses.

Private Can be called only from inside the defining class by the definind class or its subclasses.

Class method vs instance method

A class method is a method defined on a class. You can define one like this :

class Document
self.do_something
end
end

or

class Document
class << self
def do_something
end
end
end

And you can call it like this :

Document.do_something

An instance method is a method available on an instance of a class. You probably already know how to create one :

class Document
def do_something
end
end

And you need to instantiate an object before you can call it :

Document.new.do_something

Class variable vs instance variable vs module variables

Class Variables are defined with @@. A Class variable is shared between all instances and children.

Inheritance

Inheritance is a relation between two classes. A child class inherits all the features of its parent class. Methods from the parent can be overridden in the child and new logic can be added.

Usually, inheritance is used to specialize a class. See the following example :

class Document
def initialize; end
# logic to deal with any document
def print
# logic to print any kind of document
end
end

class XmlDocument < Document
# logic to deal with any document
def print
# logic to print a xml document
end
end

A class can only inherit from one class as opposed to c++ where multi-inheritance can be done (not always for the better).

You can however replicate a certain form of multi-inheritance through the use of modules as mix-ins :

module Presenter
def to_html; end
end

class XmlDocument < Document
include Presenter
# can call the method to_html
end

Encapsulation

Encapsulation is the packing of data and functions into a single component.

Encapsulation means that the internal representation of an object is hidden from the outside. Only the object can interact with its internal data. Public methods can be created to open a defined way to access the logic inside an object.

Encapsulation reduce system complexity and increase robustness by decoupling its components.

]]>
Sat, 04 Oct 2014 00:00:00 +0000http://devblast.com/b/ruby-inheritance-encapsulation-polymorphismhttp://devblast.com/b/ruby-splat-operator
Seventh article in the Prepare for a Ruby job interview series. In this article, we’re going to talk about *, A.K.A the Splat operator, which is a great tool as we’ll see.

The splat operator is a very nice trick that let you do many things. Let’s see what!

1. When used in a function arguments, it will collect all the remaining arguments in an array.

6. Flatten an array

]]>
Sat, 04 Oct 2014 00:00:00 +0000http://devblast.com/b/ruby-splat-operatorhttp://devblast.com/b/ruby-blocks-procs-lambdas
Sixth article in the Prepare for a Ruby job interview series. In this article, we’re going to talk about the Blocks in Ruby : Procs and Lambas.

Proc and Lambda are anonymous function that can be moved around in your code as variable.

pr = Proc.new { |a, b| a + b }
p pr.call(1, 2)

l = lambda { |a, b| a + b }
p l.call(1, 2)

The main difference between those is that a return statement in a proc will behave like a part of the calling method (and return from it) :

]]>
Sat, 04 Oct 2014 00:00:00 +0000http://devblast.com/b/ruby-blocks-procs-lambdashttp://devblast.com/b/include-vs-extend-ruby
Fourth article in the Prepare for a Ruby job interview series. In this article, we will study Include and Extend and see the differences between those two.

There is a big difference between include and extend in Ruby. Let me show you some code to explain it :

]]>
Sat, 04 Oct 2014 00:00:00 +0000http://devblast.com/b/include-vs-extend-rubyhttp://devblast.com/b/overview-loops-ruby
Fifth article in the Prepare for a Ruby job interview series. In this article, we’ll take a look at the main loops in the Ruby language.

While

As in most programming languages, While will repeat the block passed until the condition is met.

x = 0
while x < 100
p x
x +=1
end

p x +=1 while x < 100 # one-liner

Until

Opposite of While.

x = 0
until x > 50
p x
x +=1
end

p x +=1 until x > 50 # one-liner

Each

Each is the main loop that you’re probably using all the time as a Ruby developer.

[1, 2, 3].each do |i|
p i
end

For

Since each is more widely adopted I don’t recommend using for, but here’s how to use it :

Next

Break

]]>
Sat, 04 Oct 2014 00:00:00 +0000http://devblast.com/b/overview-loops-rubyhttp://devblast.com/b/duck-typing-ruby
Third article in the Prepare for a Ruby job interview series. In this article, we will see what is Duck Typing.

This is the first Samurails giveaway! I’m sure you hate that popup in Sublime Text reminding you that you should buy it. Let me give you a way out with this giveaway. If you enter, you will get a chance to win a license for Sublime Text!

After entering your email address below, share on Twitter and Facebook for additional entries. The more your friends and followers enter, the more entries you receive. Good Luck!

]]>
Tue, 30 Sep 2014 00:00:00 +0000http://devblast.com/b/sublime-text-licensehttp://devblast.com/b/rails-antipatterns
Hi! This is my first review. I thought I would start with a book that really helped me when I was trying to get better with Ruby on Rails.

What is it about

Rails AntiPatterns, as the name implies, is all about the bad code that we write everyday in our applications, without even realising that it stinks. Starting with the models, the author will show you the things that you SHOULD NOT DO followed by the correct way to do it.

The book contains antipatterns about :

Models

Domain Modeling

Views

Controllers

Services

Third party code

Testing

Scaling and Deploying

Databases

The book is very easy to read with lots of interesting facts about Ruby and Rails. I definitely recommend it to anyone working with Ruby on Rails who isn’t sure if his code is the best he can write.

Who should read this book

This book is addressed to people between the beginner and intermediate state. However, even more advanced developers should take a look, ‘just in case’, to be sure they are following the best practices.

Who should not read this book

Intermediate and advanced Ruby on Rails developers who already know everything about best practices.

Today we’re going to talk about versioning. How to version your models to be more specific.

Versioning my models ? What is that ?

It’s simple. For example, if you have a document that many people can edit, like a Google Doc, you better keep the previous versions of the file. Just in case someone does some s* on it. That’s exactly what we’re going to do in this Jutsu ! Let’s get started.

The project

The web app we will create is a simplified version of Google Docs. Very, very simplified. You will have a list of files that anyone can edit, based on a very simple authentication system. You will be able to see all the previous versions of the file, and who changed it. You will also be able to rollback to a previous version of your choice. To do all this, we’re going to use the PaperTrail gem.

Setup the app

In this guide, we won’t build the app from scratch like usually. Instead, you can pull the code from Github.

Listing the previous versions

Now, let’s see what we can do with that! First, we’re going to add the list of versions for a specific document. We’re going to need a way to easily get the name of someone who authored a version. For that, we need a helper method and a method in the User model :

Now you can udpate any document a few times (create one if you don’t have any yet).

You should see the list of versions growing !

Add Diff & Rollback

So, you’ve probably noticed the two empty links named ‘diff’ and ‘rollback’. You probably already know what we’re going to do with those. Clicking on diff will show us a new page with the difference between the clicked version and the current version. Rollback will simply change the current object to be like the clicked version. Let’s go!

First, we’re going to update the edit document view to add action to the links :

If you try to diff a version, you will get a missing template exception. However, you can already rollback to a previous version! Pretty cool, huh!

All we need for the diff to work now, is a view. We could build one by ourselves, but let’s not reinvent the wheel. We’re going to use the very nice gem Diffy. Diffy gives us an easy way to diff content (files or strings) in Ruby by using Unix diff.

Diff with Diffy

Add the gem to your Gemfile :

# Gemfile
...
gem 'paper_trail'
gem 'diffy'
...

bundle install and restart your server.

Since we will be using the same diff logic for the name and content of a document, let’s create a helper method :

Basically, we just tell Diffy that we want to generate html if there is any difference between the 2 strings. We also want to have the diff info (number of lines changed, etc) and the + and - that everbody likes!

Now the actual diff view is pretty simple to build. We’re going to create it in app/views/versions/ :

Very nice! Now, our app is missing one very important feature. A way to bring back documents from the graveyard! Who never deleted something by accident ? But before we do that, I want to show you how you can use your own version classes.

Custom Version Class

Why would we want to create custom classes to handle the versions of our models ? Well, with this approach, you can have a version model and table per model you want to version. Since you’re using different tables for each of your model, you won’t have one huge table that contains versions for this or that. Plus, you can add some specific field to a specific Version model by using metadata as we’ll see soon.

Adding a custom version class is actually quite easy. First, we need to generate a migration :

Try the app and see if everything is still working. Of course, you won’t have the versions that you had before because we changed the table!

Bring back Documents

To be able to bring back documents, we need to show all the deleted documents. We’re going to add a route to access all the deleted documents. Here is the whole route file. We are also adding a route to undelete.

Rails.application.routes.draw do
resources :documents do
collection do
get :deleted # <= this
end
resources :versions, only: [:destroy] do
member do
get :diff, to: 'versions#diff'
patch :rollback, to: 'versions#rollback'
end
end
end
resources :versions, only: [] do
member do
patch :bringback # <= and that
end
end
resources :sessions, only: [:new, :create] do
delete 'logout', on: :collection
end
root to: 'documents#index'
end

The actions in our controllers :

# app/controllers/documents_controller.rb
...
# Get all the versions where the event was destroy
def deleted
@documents = DocumentVersion.where(event: 'destroy')
end
...

Now try it! Delete a document and it will appear in the list of deleted. You should be able to easily bring it back too. The app is pretty much done, but I’d like to share with you 2 more features of PaperTrail.

MetaData

PaperTrail gives us a way to save additional information in each version. In our case, we’re going to save the author name (even if we can get it with the whodunnit id) and the number of word in the content.

Remember when we created the migration for you custom DocumentVersion model ? We’re going to use those!

Who needs 100 versions ?

The last trick I want to show you is a way to limit the number of versions you save. We probably don’t need the 100 previous versions, 10 to 30 should be enough. You can define that in PaperTrail configuration :

When you first create a Rails app, you can just follow the conventions provided by Ruby on Rails and your development will be smooth and nice. But after months, or years, your app can become cumbersome.

And now it’s :

Hard to maintain.

Hard to improve.

Hard to test.

Your app has just become a pain in the a.**

From this point, you’ve got a few choices.

You could just give up, but I’m sure you’re braver than that. You could also divide your web application in a set of different applications and APIs, but that sound like a lot of work. Or maybe you can rewrite your app in a more modular way.

Note that if you’re just starting to build your application/framework/library, you might want to start clean by building it with modularity in mind. Keep reading. ;)

First, what’s modularity ?

Modular programming is a software design technique that emphasises separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality. Conceptually, modules represent a separation of concerns, and improve maintainability by enforcing logical boundaries between components.

Basically, it’s all about isolating the functionalities/features of your application into independent and interchangeable components.

Let me give you an example of a real life Ruby on Rails application. We’re going to use a CMS, like Wordpress, as an example.

In a regular monolithic application (as opposed to modular application), we’d probably have the following files (with a very simplified architecture) :

As you can see, we put the user system inside the Core engine. The Core, as the name implies, contains the minimum logic for our app to run. We can then add features on top of it by extending its controllers, models and views inside the Post and Comment engines. The engines are loaded through the Gemfile of the main Rails application.

Want to remove the comments from your blog ? You can just remove this engine from the Gemfile. Your app will still be working perfectly fine since the Comment engine was completely encapsulated. The main app and the other engines will still be working correctly.

That’s the basic idea behind modularity.

Advantages

Using Rails engines in this way come with a set of advantages. Here are a few of those :

You can easily add or remove feature since those are completely isolated.

Reusability. The core that I show you before can easily be reused in any application. Same can be said for some feature engines.

Each engine includes its own tests, so each feature is tested separately.

]]>
Mon, 22 Sep 2014 00:00:00 +0000http://devblast.com/b/introduction-modularity-ruby-railshttp://devblast.com/b/poro-json-presenters
I’ve talked about Active Model Serializers here and Jbuilder there. Now, I’d like to share with you how you can serialize your models in JSON without using any external gem, just Plain Old Ruby Objects.

We’re going to build yet another simple Ruby on Rails application that will generate JSON for TV Shows and their episodes.

PORO Presenters

Now it’s time to create our JSON presenters. To do that, we’re going to create a folder called ‘presenters’ under ‘app’. For each model, we will create a model presenter to format the JSON. We’re going to build those presenters on top of ‘as_json’.

First, we need a parent presenter to remove some redundant code from the children :

The End

As you can see, implement your own clean JSON builders is not that hard. However, I would recommend using great gems like Active Model Serializers or Jbuilder to build your JSON. This article is more for knowledge purposes. If you have very specific needs, you can now build your own JSON building solution based on this tutorial.

Want faster JSON ?

Source Code #2

]]>
Wed, 03 Sep 2014 00:00:00 +0000http://devblast.com/b/jbuilderhttp://devblast.com/b/active-model-serializers
These days, people are crazy about single page applications. And for good reason ! But building this kind of application requires a backend that can communicate through JSON. Let’s see how we can do that with Rails.

We are going to build a simple API that will return artists, their albums and their songs. Now, the question is how should we generate our models’ JSON.

We could use Rails’ method ‘to_json’ to simply produce a JSON of our models’ attributes. But that means no control over what we are sending. We could also add a ‘as_json’ method to our models, but this means that our models have to handle their presentation layer. What ? Who said Separation of concerns ? If we want to code clean, the presentation layer should be handle by some kind of ‘presenter’ class, not by the model directly. Here comes Active Model Serializers !

Active Model Serializers lets us define ‘serializers’ classes that can handle the JSON generation for your models. Let’s see how !

The End

Active Model Serializers allows you to separate your presentation logic to simple ruby objects. It then detect if the model has a serializer and generate a json with it. If the model does not have any serializer, the whole record will be serialized through Rails.

Source Code #2

I’m sure you’ve already seen pages taking forever to load… Not the best user experience huh ! This usually happens when you imported a big file or upload a picture. Those are usually long tasks that should be run in the background to keep the user experience smooth.

Here are a few examples :

Import and process large quantity of data

Make calls to external services

Sending lots of emails

Processing pictures

‘More super long tasks…’

Now that you know what we are talking about, let’s see how to avoid this kind of things in Rails !

Now, go the homepage and click on the link… and nothing happens for 5 seconds ! Thanks to Turbolinks, you won’t even see the page loading. I’m sure you agree that it’s a pretty bad experience for a user.

Delayed Job to the rescue !

Simply change

# app/controllers/uploads_controller.rb
@doc.format

to

# app/controllers/uploads_controller.rb
@doc.delay.format

and try again ! Wow, it’s instant now ! Not so fast, the document was not actually formatted, we have one thing to do first. Open a new terminal/tab/split and run

It’s working ! If you’re wondering, yes, you have to run this rake task all the time when working with Delayed Job, including on your server. But no worries, there are easy ways to manage that as we will see later.

BTW : If you want to check your jobs in rails console, the model is Delayed::Job. With that, you can list them, delete them, dance with them or whatever is on your mind.

Now we’re going to improve the user experience by letting him know that we are formatting the file and update the page when it’s done. To do that, we’ll simply use some long-polling javascript.

Run_at : Date to run the job at. Give it a Proc to have a date defined by the moment the job is picked up by DJ.

Queue: With queues, you can setup different group of jobs. You could have the jobs of ‘queue1’ processed by one process and ‘queue2’ by another. You can run specific queues like this :

QUEUE=queue1 rake jobs:work

or

QUEUES=queue1,queue2 rake jobs:work

Let’s talk about running Delayed Job in production, first on a dedicated server, then on Heroku.

Run on your server

To run Delayed Job on your server, you will have to add the gem ‘daemons’ to your Gemfile. Don’t forget to ‘bundle install’. Now you can run :

bin/delayed_job start

or in production :

RAILS_ENV=production bin/delayed_job start

If you want to stop it, just replace ‘start’ by ‘stop’. The logs are available in ‘log/delayed_job.log’. You can check more options here.

Run on Heroku

To use Delayed Job on Heroku, you will have to use some Workers.

After pushing your code, you will need to run the following command if you don’t have any worker.

heroku ps:scale worker=1

The worker should start processing the tasks.

Note that running Delayed Job on Heroku in that way is far from cost effective since you will pay for a worker 24/7 even if you process 2 tasks per day. The solution to this problem is Workless which will hire or fire workers based on your needs. I am planning to write a tutorial about Workless, since the use of multiple queues can become tricky !

The End

Now, it’s time to speed up your application by setting in background everything that belongs there :)

As a Ruby or Rails developer, you should know the people who built the tools you are using everyday.

So here are a few of the biggest influencers and hackers of the Ruby/Rails community. Please, note that this list is not complete, just let me know if you think someone else should be added. ;)

Ruby

Yukihiro “Matz” Matsumoto

Well, he had to be here. Yukihiro Matsumoto, a.k.a ‘Matz’, a.k.a まつもとゆきひろ, is the chief designer of Ruby. He currently works at Heroku as a Chief Architect of Ruby. He wrote ‘Ruby in a Nutshell’ and co-authored the acclaimed ‘The Ruby Programming Language’. Also, he is a Mormon.

Yusuke Endoh

Yusuke is one of the developer working on Ruby. He is also a freaking magician with Quines. You don’t know what is a Quine ? Well, from Yusuke’s own words, it’s simply a program that prints itself. Sounds simple right ? Not that much ! Here is one of his awesome quine, the Qlobe! He also loves esoteric programming languages or ‘esolang’ !

If you like Quine, this one is a pretty cool on. It prints himself through 11 programming languages !

Akira Matsuda

Akira is an active committer on both Ruby and Rails. He authored great gems such as the excellent Kaminari. He also organize a very nice meetup every week in Tokyo ! If you happen to be in Japan, you should drop by on Tuesday evening ;)

Rails

David Heinemeier Hansson

Who doesn’t know David Heinemeier Hansson ? After all, he is just the creator of one of the most awesome web development framework ever : Ruby on Rails \o/ You already know that he is a very active member of the Rails community (o rly?), he also speaks at various events and wrote a few books including Agile Web Development with Rails. During the day, he is CTO at Basecamp (previously 37Signals). He is also a racing driver and a hobbyist.

Yehuda Katz

Yehuda Katz is working on so many awesome projects that the only way he can do it is probably because he doesn’t need to sleep or his days last more than 24 hours. I mean, he is a core team member of Ruby on Rails, JQuery AND Ember.js. That would be fine if he didn’t also run a company called Tilde Inc., but yeah, he does ! The rest of the time (if there is any left…), he travels around the world and talk about open source and web standards.

Aaron Patterson aka Tenderlove

Aaron is a bright unicorn in the darkness. When the night fall, he suits up to defeat the smelly code, but not without the help of his two cats ! When he is not contributing to Ruby, Rails and a bunch more, he actually works at AT&T Interactive. Funny fact, he can also read & speak japanese, quite an achievement !

]]>
Wed, 02 Jul 2014 00:00:00 +0000http://devblast.com/b/people-you-should-know-as-a-rails-developerhttp://devblast.com/b/ruby-ruby-on-rails-inject
We’re going to talk about Enumerable#inject! Inject is super cool and if you don’t use it in your code, then you should start. Really.

Just moved to Thailand…

The truth is that I have been quite busy for the past 2 weeks. First, I came back to Thailand after 3 weeks in France of “semi-holidays”.

The jet lag was hard on me this time and it’s been even harder since I had to work the day after. I actually tried to beat it this time following some advices from this website. It didn’t really paid off…

I tried to reduce my sleep time to be super tired during the flight (sleeping 5/6 hours for 3 days) but I was only able to get a few hours of sleep during my 12 hours flight. I was more than happy to arrive and meet with the Thailand hot weather !

… After a short stay in France !

Let’s go back to France for a bit. The 3 weeks I spend there let me relax and clear off things of my to-do list.

But I also had to work on some work-related project which means only a part of my time was really mine. During this “recreation”, I studied iOS development in an attempt to create my first mobile app.

Unfortunately, I couldn’t. I don’t understand why but a mobile app is a kind of project I cannot complete. I always give up on the way due to a lack of motivation.

Maybe it’s not for me, I’ll stick to web application development for now.

My next project

I also spend time trying to find the right subject for an ebook. Yeah, I want to write an ebook, like everyone else !

The idea and motivation came from Nathan Barry and his self-published ebooks. The book he wrote, Authority, inspired me so much that now, I want to write my own ebook. Till now, I was not able to find the motivation to work on it, but things started to stabilize.

I have a new apartment in Bangkok, a nice job in a cool startup (AppyHotel) and I’m only 23. Still plenty of time to do big things. My dream/goal is actually to become independant, living on passive income, and work on whatever I want.

About this ebook thing, I have a few different ideas. I could create something focused on how Rails engines can let you organize a big web application in a clean way. Or I could create a simple how-to for people who want to start an online business without knowing anything about the ‘online’ part. I need to validate and find what people are ready to pay to access this kind of knowledge. Each idea is targeting a different group of people which is not optimal. Nathan Barry confirmed this here.

Being a Ruby on Rails developer, I think I will go for the first option since I belongs to this group myself.

It’s gonna be hard !

I have another problem. You may have guessed that I’m not a native english speaker. Writing content of quality is a real challenge for me.

By the way, if you notice any weird things in my articles or if you have any suggestions to help me improve my writing, just send a quick mail to thibault.denizet@gmail.com, thanks !

The plan

Since I’m not a native english speaker, I’m not sure about the quality of the content I can produce. Specially for a big format such as an ebook. I still have to think about it but I plan to start in the next weeks.

First, I will pinch some friends of mine to know what they think about the subject. Then I will setup a landing page and let people preorder with a nice discount. I will try to blog a lot to describe pitfalls I encountered and how I resolved them.

If you are interested, just sign up on my newsletter so you won’t miss anything !

Comments appreciated ;)

Please, leave a comment if you have anything to say. I’m always looking for feedbacks.

]]>
Sat, 23 Nov 2013 00:00:00 +0000http://devblast.com/b/whats-uphttp://devblast.com/b/rails-delegate-dont-break-the-law-of-demeter
I’m sure you know about the Law of Demeter. It’s also known as the principle of least knowledge. Let’s see how to apply it in Ruby on Rails !

If you don’t know about it, let me explain it quicly. The law of Demeter is a programming guideline implying that an entity should only talk to its close friends. If we put in another way, an object should not call methods through another object.

When using Rails and the cool associations feature, it can be tempting to chain method calls like this:

product.provider.name
provider.address.city
company.building.city

These lines violate the Law of Demeter. To fix it, we should change them to be :

Now, we don’t break the law of Demeter anymore since we can access the street directly from the company object. Plus, less BS inside our models ;) Note how we added allow_nil to the delegate. With this little addition, if the company does not have any building associated, we will just get nil when calling street and no exception!

If you never used the delegate method, it’s time to add it to your toolbox !

It’s been a while since I gave you some details about what I’m doing. You probably noticed that I published less articles recently, I have actually been quite busy with a few things.

First, I spent some time writing my thesis to validate my master.

The subject was :

How the creation of a modular and generic web application can allow a company’s diversification.

Sounds cool, right ? I’m sure you think so. Anyway, I submitted it on the first of October, just on time. After that, I finally had some time to complete and publish the tutorials about Single Table Inheritance. The following weeks have been busy at work and I was not able to produce more content for the blog.

I also try to relax after the pressure of my thesis even though I still had the presentation to do. I had to come back in France to do it and that’s what I did last Saturday. After 17 hours of travel, I arrived in Bordeaux in the evening. I actually did this presentation yesterday, on October 22th, and it went well. I was kinda stressed about doing it all wrong since we didn’t get real guidelines. The main point I tried to follow was to keep the things simple since not everyone in the audience could understand programming concepts. I try to focus on the business side and explain the advanced concepts in a very simple way. Looks like it paid off !

I’m confident about getting my degree but I will have to wait a few days to have the confirmation. Not being a student anymore makes me feel so free, anything is possible now !

I will fly back to Thailand in 3 weeks to keep working for AppyHotel. Till then, I will have a lot of times and I’m planning to use it to work on some of my ideas. I will also be writing a lot to add content to my blog and share what I learned recently !

If you read my first blup, you may be wondering about all the tutorials I plan to write and the screencasts I plan to do. It’s still a work in progress, everything has been delayed until now. I’m planning to work on some of them in the next days but I got a few ideas that went directly to the top of my todo list. I will give you more details about these secrets projects in a few weeks ;)

]]>
Tue, 22 Oct 2013 00:00:00 +0000http://devblast.com/b/blup-2http://devblast.com/b/single-table-inheritance-with-rails-4-part-3
In the last article, we created our controller and define the index view. In this one, we are going to add the missing views and see some tricks to handle paths for STI models.

Learn how to implement STI with Rails with this free ebook

Dynamic paths helper

Before we implement the other views, we need a way to create dynamic paths based on the race. To do that, we can use the following helpers method.

Last step before seeing our show action, we need to define @animal in the controller. To do that, we are going to add a callback before_action before every action where we will need @animal to be defined :

Okay, now you should be able to access the new page and fill the form. If you play a bit with the path, you will notice that the select box for the race is only enabled if you create a new Animal. If you try to create a new Lion (/lions/new), the select box will be selected by default and will be disabled.

Strong parameters for Animal

Before we actually create animals with our form, we need to define the parameters that can be passed to our animal. This is a Rails 4 new feature, if you want more information, check out the doc.

As you can see in the following code, we added a method called animal_params which define the three parameters that we want to allow for the model Animal. We also added the code for the create action :

Source code

Warm Up

Through this set of tutorials, I hope you understood what can be done with Single Table Inheritance and how it can prevent you from having similar controllers. You won’t use STI everyday, but when you need it you will be happy to find it ;)

Related articles

]]>
Wed, 09 Oct 2013 00:00:00 +0000http://devblast.com/b/single-table-inheritance-with-rails-4-part-3http://devblast.com/b/single-table-inheritance-with-rails-4-part-2
Time to continue learning about Single Table Inheritance with Ruby on Rails.

Learn how to implement STI with Rails with this free ebook

In this article, we are going to see how to create a common controller for our models (Animal, Lion, etc). We will also need to create the corresponding routes and add some helpers to generate the right paths. If you don’t have the code from the first part, you can get it here.

The common controller

Time to start working ! First, we have to generate the common controller for our models. The name is going to be AnimalsController which matches our parent model.

Setup the index action and the corresponding view

Fire up your server and access localhost:3000 and you will see, well nothing. We should add some content to our index view, maybe the list of all the animals in the database. To provide this list to the view, we need to add some simple code to our controller :

The view still looks pretty bad huh, but whatever, it’s not a design tutorial. You are free to add some css (and you can even pull request on [the repo][2], I will definitely merge it if it looks good).

Now that we have a basic way to show our data, we can start playing with Single Table Inheritance. In the first part, we created one table animals and one model Animal. We also created 3 other models (Lion, Meerkat, WildBoars) that inherit from Animal and all live happily in the same table. Thanks to that, we avoided repeating code at the model level. We can follow the DRY rule at the controller level by using a unique controller for all our STI models.

Routes and STI

After a bit of code, the index action of the Animals controller will be able to show either all the animals or only the animals of a specific race. To do this, the controller need to know which race is requested. Thanks to Rails, we can define a default parameter in our routes.

See the type key ? That’s the trick. Everytime we access /lions/*, Rails will add a parameter in params with the key type. So, for each model that inherit from Animal, we define resource routes and specify that they have to use the animals controller. We also add the corresponding type.

We can now extract the type value in the controller with the following methods :

Basically, before any action we assign the value of the race params, or Animal if no race is passed, to the variable @race so our views can access it. We can now change the Animal.all to race_class.all. The method race_class is going to send back the constantized parameter type like Lion for example.

def index
@animals = race_class.all
end

Warm Up

If you access http://localhost:3000, you will have the list of all animals. But if you access http://localhost:3000/lions or http://localhost:3000/meerkats, you only get the list of the specified animal. Wonderful, isn’t it ?!

That’s it for this article. In the next part, we are going to add dynamic paths and the missing views !

Today, we are going to do some model inheritance with Active Record ! This is not something that you should do everyday but in the right situation, it’s just awesome. Some parts can be tricky to implement, especially the routing and the creation of a shared controller.

This article will take you through the creation of the STI models. Another post will focus on the configuration of the routes and the creation of a controller shared by all the submodels.

Learn how to implement STI with Rails with this free ebook

Prerequisites

To follow this tutorial, you will need a working rails environment. I will use Ruby 2.0 with Rails 4 but you should be able to test the code using any version of ruby superior to 1.9.2 and at least Rails 3.

What is Single Table Inheritance ?

Single Table Inheritance is, as the name suggests it, a way to add inheritance to your models. STI lets you save different models inheriting from the same model inside a single table.

For example, let’s say you have an employee model. The employees can be of two types : manager or developer. They pretty much share the same attributes and columns. However, their behavior should be different. Creating two tables having the exact same fields would be bad.

But here comes STI ! With STI, you can just keep your employee model and simply subclass it with your two types of employee. The only thing to do at the database level is to add a type column to the employees table that ActiveRecord will automatically use to identify the submodel. If you want to know more about STI and see a real example, keep reading !

With great power comes great responsibility

STI should be used if your submodels will share the same attributes but need different behavior. If you plan to add 10 columns only used by one submodel, using different tables might be a better solution.

Creating the rails app

Time to create our rails app. If you already have a running app, jump to the next part. Else run the following commands.

Generate a rails app without tests and start the server

rails new sti --no-test-framework

Generating the models and migrations

Now, we are going to generate our models and the related migrations.

Generate the Tribe model

rails g model tribe name:string

Generate the Animal model

rails g model animal name:string age:integer race:string

The race column is going to be used by Active Record to save the submodel name. By default, AR will search for a column named type but you can use anything as long as you tell AR about it.

Then you can either add the column tribe_id to the Animal migration file or create a new migration :

Nothing complicated here. We setup the relation between the tribe and the animals and create three empty submodels. Note that self.inheritance_column = :race is used to specify the column for STI and is not necessary if you are using the default column type.

If you want to disable Single Table Inheritance or use the type column for something else, you can use self.inheritance_column = :fake_column.

Rails Auto-loading

Fire up a console and test that you can create each of the above models. You will see a NameError: uninitialized constant if you call a sub model (like Lion) before making a call to the parent model (Animal). This is due to Rails auto-loading system. To load a model, Rails is looking for a file called model_name.rb inside the app/models folder. There are a few solutions to fix this but we will use the simpliest one : just split each model declaration in its own file.

Add scopes to the parent models for each child model

Add delegates in the Tribe model

delegate :lions, :meerkats, :wild_boars, to: :animals

These are not mandatory but make the navigation between models easier.

Fill the database

Before proceding to the next part, we are going to create some objects in the database and play with our models. For now, we will use the console rails c. Thanks to STI, we can now use the models Lion, WildBoar and Meerkar to create the corresponding animal. The column race will be automatically filled by Active Record.

We also defined the talk method on animal as an “abstract method” (Since ruby doesn’t have abstract methods, we simply raise an exception if the model is called from Animal or from a submodel which doesn’t defines it). Indeed, we don’t know what a random animal have to sing !

Source Code

Warm up

Just play around with your new STI models and see everything you can do. As you can see, it can be pretty useful. In the second part, we will see how we can present our inherited models to the world through a single controller and how to configure the routes to do so.

Related articles

So it’s been a little less than 2 weeks that this blog is live. I wanted to give you an update about what is going on as the Blup (Blog Update \o/) #1.

Tips & Tutorials

I’ve been quite busy since I started, trying to find good tips and good topics for tutorials. Most of what I published was related to my day-to-day work. From now on, I’m going to create a few project with technologies I’ve wanted to test for a while. These projects will be used as examples to write tutorials about the chosen technologies.

The first one, which is already started, is a really simple web app build with angular.js and pouchDB. The first version will only work with local databases available in the browser. In a second version, I plan to add remote support with data synchronisation.

The second project is going to be something like a tweet aggregator. I want to build it with two sets of different technologies : Ember.js with Rails 4 and Angular.js with Golang. Yeah Golang, I really want to try it and start using * everywhere :D. I’ve also wanted to try Ember for a while and now that the version 1 is out, I have no excuses !

The next project is a Sencha Touch hybrid app. I’ve always wanted to have a published app but I never found the time to do it. Now that I told the world, I have to do it :)

Last year, I created a chat web application with Node.js for a school project. I thought it could be interesting to share with you how we build it.

After rechecking this Node.js web chat, full of realtime magic thanks to Socket.io, I wanted to try Rails 4 live streaming and see what can be done with it.

Well, that’s quite a lot and it won’t happen in 2 weeks. I’m still working full time and I have a mémoire to finish (and maybe start…) before the first of October.

Mémoire

So yeah, my mémoire. 50 pages. 1 month. 1 man.

Subject : How the modularisation of a web application can allow a company a fast diversification ? (It actually sounds better in french)

Every time I try to work on it, I get caught by Hacker news, a new post idea, or you know, anything that would be more interesting (quite a lot!).

So how do I plan to write it and find the motivation while still doing many other things ? Well, I’m not sure yet. I talked a bit with Philip Alexander, who is currently writing a book, to get advices about time management and writing.

He gave me a good advice, which I actually knew about but never thought about applying it to my mémoire. It’s actually quite like programming and the refactoring process.

You code something. Then you realize it sucks. So you rewrite/reorganize some parts while keeping the logic.

Not trying to get things perfect at first makes it much easier, at least for me. I just have to write 2 crappy pages that future Thibault will review.

That’s the process I will use to write my mémoire. Everyday, I’m going to write around 2 pages of content. But before writing, I will refactor what I wrote the day before. I want to finish the writing process before October 25, leaving me with 6 days to review and ask relatives to read it.

To get more motivated, I have been thinking about what I could do with this mémoire after getting my degree. The first and only idea that came up was to extract some parts, rewrite them, add new content and publish it as an e-book about writing modularised web apps with Rails.

Screencast

Screencasts are so cool. I love them. I want to do it myself but it’s going to take even more time than writing tutorials. Anyway, I will check what I can do, hoping to start screen casting soon !

Blog Statistics

So far, my blog has received 114 visits by 72 different people. The average visit duration is exactly 5 minutes. Most of the traffic comes from Thailand (where I live), followed by France (where I come from) and USA. I consider it a good start since it’s the first time I make content available online.

So that’s it for the next months. I will keep creating new content for this blog, finish my mémoire and start creating screencasts. I will write Blups every 2 or 3 weeks to let you know about the overall progress.

]]>
Mon, 02 Sep 2013 00:00:00 +0000http://devblast.com/b/blup-1http://devblast.com/b/how-to-debug-a-mobile-website-on-ios
Let’s say you are working on a mobile website or a mobile webapp. You develop it in your desktop browser because it’s much easier, right ? When finally comes the time to test it on a device/simulator, something goes wrong. How can you find out what ? There is no debugging tool integrated in mobile Safari… Desktop Safari to the rescue !

Everything following can be done with a real device plugged in usb or with the iPhone/iPad simulator.

The first step to debug a mobile website is to enable the Web Inspector on the device in Settings > Safari > Advanced > Web Inspector. Once it’s done, you will have to plug your Apple device to your computer and run Safari.

By default, the developer mode is not enabled in desktop Safari. You can enable it in Preferences > Advanced > Show Develop menu in menu bar.

Time to plug your device. Now, navigate to the Develop menu of Safari. You can see the list of plugged devices (T-phone is my iPhone) and you can see which pages/apps are available to debug.

Devices won’t appear if you enabled Private Browsing in the settings of mobile Safari.

Just click the website you want to debug and use with the web inspector to fix your mobile website !

]]>
Sat, 31 Aug 2013 00:00:00 +0000http://devblast.com/b/how-to-debug-a-mobile-website-on-ioshttp://devblast.com/b/how-to-make-a-website-mobile-ready
I used to have problems with the mobile thing when creating mobile websites. Indeed, if you want your mobile website to look good on devices, you need to define a few things : viewport, icons, splashscreens… So today, I’m going to tell you exactly what you need to do to make your website mobile-ready.

All the following has been tested on iOS. Most of it should also work on Android but I couldn’t test it, so no guarantee.

To make your website behave almost like a native app, you will need to add some lines to your html files. Let’s get started with the first thing, tell the world that your app is mobile capable !

Mobile Web App Capable

This meta-tag will tell mobile Safari or any other mobile browser that your website should be display in full-screen mode.

<meta name="apple-mobile-web-app-capable" content="yes" />

Viewport

You definitely want to set the viewport meta tag for your mobile website. With this, you can define how your website should look and if the user can zoom or not.

Topbar

Mobile websites can be saved to the home screen on iOS. If a user do so, you will have to do something about the top bar. You can control that with :

<meta name="apple-mobile-web-app-status-bar-style" content="black"/>

The options for content are default, black or black-translucent.

Home screen Icon

If your website is saved to the home screen, it will need an icon. If you don’t set one, the device will take a screenshot of your website. That usually doesn’t look so good ! You actually have to define multiple icons, the right one will be picked depending on the device resolution.

You could just use 2 image sizes (114x114, 144x144) and let the device resize it.

You could also just provide a png image at the root of your folder called apple-touch-icon.png or apple-touch-icon-precomposed.png and the device will pick it up.

You can either put apple-touch-icon or apple-touch-icon-precomposed in the rel attribute. With the latter, the device won’t apply any fancy effect on the icon.

Splashscreens

The last thing you can add to your mobile website is a splashscreen. That’s the screen the device will show before showing your website. Again, you need to define quite a lot of tags to fit a range of different screen sizes.

Today, I’m gonna talk about something that always caused me a lot of pain, everytime I had to deal with it : Same-origin policy. This thing is simply awful if you have to make HTTP requests from Javascript.

To counter that, you can use JSONP. But only to make GET requests. If you need more than that (POST, PUT, DELETE), you will have to use Cross-Origin Resource Sharing and that’s what I am going to explain in this post. To do this, I will use Angular.js and Sinatra. Let’s get started, shall we ?

Prerequisites

To follow this tutorial, you will need a version of Ruby and the Sinatra gem installed. You will also need a webserver, if you don’t have any check my post about SimpleHTTPServer.

Setup

So here is the basic code nothing fancy, a very very simple index.html, an angular module called MyApp completly empty and a Sinatra app with the basic route /hi coming from the documentation.

JS

Ruby

require 'sinatra'
get '/hi' do
"Hello World!"
end

Just create three files : index.html, app.js and server.rb and Copy/Paste the corresponding code in each file.

Run the code

You can run the Sinatra server with ruby server.rb and you can use any webserver to access index.html at http://localhost:9000. Indeed, CORS calls won’t work if you use the file url, you need a real domain.

Let’s get started by configuring the Sinatra app (don’t forget to restart Sinatra server) :

Ruby

require 'sinatra'
require 'json'
before do
content_type :json
end
set :protection, false
get '/movie' do
{ result: "Monster University" }.to_json
end
post '/movie' do
{ result: params[:movie] }.to_json
end

Okay, we are ready to go. If you access http://localhost:4567/movie from your browser, you should be able to see the last movie I saw. So let’s make our first javascript HTTP GET call.

Restart Sinatra server and tadaaaa ! Now it’s working \o/ So what did we do ?

Well, first we told the $http module that we were going to send requests to another domain. We also removed the header used by the browser/server to identify our call as XmlHTTPRequest. Then, we enabled CORS on the server by specifying the available HTTP methods and the allowed origins (in our case, any origin *).

You probably noticed that we added a new route on our server :

options '/movie' do

This is part of the Cross-Origin Resource Sharing specification. Before sending a request to another domain, a call with the HTTP method OPTIONS will be fired. The response to this call will determine if CORS is available or not. This response must contain the allowed origins and the available HTTP methods

Security notice

In a production environment, you should not accept any origin of course, you should specify the allowed domain names like this :

OPTIONS http://localhost:4567/movie Request header field Content-Type is not allowed by Access-Control-Allow-Headers. angular.min.js:106
XMLHttpRequest cannot load http://localhost:4567/movie. Request header field Content-Type is not allowed by Access-Control-Allow-Headers.

So what’s wrong ?

The answer is in the error, we need to add Content-Type to the allowed headers :

As I told you, it’s kinda weird. Well, you can easily clean it up by getting the first key of the hash, parse it and get the params hash, that’s up to you.

Well, now you should be able to setup CORS calls between your client and your backend ! If you have any problem, feel free to contact me or leave a comment. It took me a while to figure out everything and I hope it will save you a lot of time. If you are interested in seeing PUT and DELETE calls, leave a comment and I will add it.

Just a small one to let you know about an awesome tiny webserver : SimpleHTTPServer. You can simply run it like this from the directory you want to access :

python -m SimpleHTTPServer 8000

with the port number of your choice.

Hope it helps :)

Thibault

]]>
Tue, 20 Aug 2013 00:00:00 +0000http://devblast.com/b/lightweight-http-web-serverhttp://devblast.com/b/return-json-in-sinatra
Returning JSON from a Sinatra endpoint is really easy. You just have to to the following :

Let me introduce myself.. These days, I’m a Ruby on Rails developer, trying to like Javascript and starting my initiation into the marvelous world of writing. I’m currently using and abusing my skills at AppyHotel, working on the backend and the mobile webapp.

I’m actually not really ‘working’ there since I didn’t get my degree yet. But as soon as this internship is done and my thesis completed and accepted, I will be ready to embrace my career ! You may also want to know that I’m french, so now you know why I use some weird expressions sometimes ;)

No what about this blog. I’ve decided to start it for a few reasons such as, but not limited to :

Improve my writing skills

Attempt to build an audience, and keep it (more on that later)

Learn and become a better coder

Discover the online marketing

Share some funny or interesting experiences

Well, you get the picture ! I’m going to try to keep all that interesting, awesome and useful. I may talk about a lot of different things, but my main targets are technology and development (with Ruby, Javascript, and any new language I will learn).

By the way, I’m living in Bangkok. If by any chance you come around, let me know so we can go grab a beer !