Your First Sinatra Apps

Sinatra is a DSL (domain-specific-language) for building websites, web services, and web apps in Ruby. A DSL is usually dedicated to solving a particular type of problem. SQL (structured query language) is another example of a DSL. SQL is used to facilitate interaction with relational database systems.

Sinatra is not a Framework like Rails. It doesn’t come with a pre-fabricated file structure or even a project folder. Sinatra is a lean language and is being used by companies like GitHub, Heroku, BBC, ThoughtBot, and Songbird.

The two main approaches to building Sinatra apps are classic and modular. In classic mode you just require Sinatra and start defining end-points. Classic applications are often single-file, standalone apps that are run directly from the command line or with a minimal rackup file. In modular mode you explicitly subclass Sinatra and build your app within that scope. You would take a modular approach if you wanted to build many small apps within a parent app. Think about mixins in Ruby, they’re just little modules(blocks of code) you can use throughout your app or you can have an entire app of just interacting mixins!

So why not use Sinatra for all of your apps and be done with it? Every technology has it’s place. Sinatra is usually reserved for smaller apps. If you want to build the next WordPress you could theoretically do it in Sinatra but using Rails would be more appropropriate. Why not just learn Rails from the outset? Same reason you probably shouldn’t try learning JavaScript as your first programming language. Learning Ruby is more practical and gives you a fundamental grasp of using a language to communicate with a machine. I’m so glad I learned Ruby before tackling other languages. Sinatra is less robust and is great warm-up for learning Rails.

So how do you install Sinatra? Easy! Type gem install sinatra anywhere in your command line. You should also install the Thin web server by typing gem install thin. Why Thin you ask? Thin is a Ruby web server that glues together 3 of the best Ruby libraries in web history:

  • the Mongrel parser, the root of Mongrel speed and security
  • Event Machine, a network I/O library with extremely high scalability, performance and stability
  • Rack, a minimal interface between webservers and Ruby frameworks

Which makes it, the most secure, stable, fast and extensible Ruby web server bundled in an easy to use gem for your own pleasure.

Let’s build our first “Hello World!” App! Jump back to your command line and make a directory for your sinatra app:

Open the folder in your text editor (sublime . ) and type the following:

Now make sure the file is saved and type ruby server.rb back in your command line. By default the application will listen on port 4567 so go ahead and open your web-browser and navigate to http://localhost:4567/ Your sinatra app should respond and you should see “Hello, world!” in the top left of your browser window. Congrats! Your first Sinatra App!

So what’s this sorcery? Sinatra separates the developer from middleware called Rack. No, nothing to do with Tyga’s hit single ‘Rack City.’ Rack provides a minimal interface between web-servers (e.g. Thin) that support DSL’s. Sinatra is going to use Rack to talk to Thin (our web-server). Essentially Sinatra speaks Italian, Rack speaks Italian and German, and Thin speaks German. We have to use Rack as our translator.

Sinatra DSL syntax is typically expressed in the form: verb ‘route’ do. We’re instructing our application to respond to HTTP GET requests to the path ‘/’; our apps response (behavior) is inside of the block. So when a server (Thin) hollers atcha app, your app responds: “Hello, world!” This block is appropriately named a method call. In Sinatra, a route is an HTTP method paired with a URL-matching pattern. Each route is associated with a block:

In Sinatra Routes are matched in the order they are defined. The first route that matches the request is invoked. This means, if you have another get ‘/’ do request beneath your Hello World request, the Hello World will be the only one triggered for this ‘/’ request.

rock-paper-scissors

Now let’s put some of what we learned to use and build a simple Rock Paper Scissors web-app! In your command line control-c out of your server connection and rename your server.rb file to game.rb (mv server.rb  game.rb). before we start processing routes we have to set up a before block with plain text responses and a hash with all viable moves:

This code will be stored in memory before our route is processed. Let’s set up our route and set a player_throw:

The most important thing to understand in this program is the params hash, the rest of the code in our block will be basic ruby. You’ll be using params in pretty much every Rails and Sinatra program you write. The params hash stores querystring data. What the heck is querystring? A very simplistic explanation is, it’s the last piece of data in any URL (Uniform Resource Locator). A more accurate definition is: A querystring is a set of characters input to a computer or Web browser and sent to a query program to recover specific information from a database. On the Internet, a querystring (also called an HTTP querystring) is part of the set of characters automatically input in the address bar of a dynamic Web site. For example, consider the following URL:

:www.bookfinder4u.com/search_author/Ernest_Hemingway.html?sort=date

The querystring in this example consists of one field or variable, technically called a key in this context (the word “sort”), followed by an equals sign (=), followed by the value for that key (the word “date”). A querystring may contain several key-value pairs. When there is more than one key-value pair, they are typically separated by ampersands (&). So params is just a Hash with key value pairs. And we use this hash to pass along information from one request(page) to another. This will make more sense as we finish building our first web game.

The only thing left to tackle that might seem unfamiliar is the ‘halt’ command. It’s pretty simple, processing will stop immediately once the halt command is called. The player_throw will essentially be fixed and placed at the end of your URL. The computer_throw is random (.sample). Yall should be able to work your way through the rest of the logic.

So that’s our basic game! Let’s test it. Jump back into your command line and type ruby game.rb to establish connection with your server. Once you’re connected open your browser and navigate to http://localhost:4567/throw/rock or http://localhost:4567/throw/scissors or http://localhost:4567/throw/paper . Notice how we (the player) is inputing the throw in our URL, and the computer (the program) is generating it’s own throw and comparing it with ours. Keep refreshing your browser and you’ll see different results. What do you think you can do to set off halt 403? Just type anything besides our three set inputs at the end of our URL.

Sketch A Logo

My full-stack ambition has led me to Sketch. I always wanted to learn how to use photoshop or illustrator but never quiet had the time. I started using Sketch a few weeks ago after stumbling on this article. Sketch is a fairly new designer-centric application that’s really gaining popularity. Sketch is primarily focused on user interface design. Everything is already in vector, so you don’t have to worry about designing for multiple devices, and delivering assets is a breeze. It’s super lean and intuitive, the interface is bare bones and not nearly as cluttered as photoshop and illustrator. Programmers are notorious for opposing anything that has to do with design and with bloated adobe products you can’t really blame them. I argue that the wider your range of expertise the more valuable you are. And honestly making something like a neat logo, as I’ll demonstrate in this post, isn’t terribly difficult in Sketch!

Let me briefly discuss some of the awesome features in sketch that any full-stack developer would appreciate. If you’re wireframing in Sketch you don’t have to worry about your design translating to CSS. So all of the textures, gradients, shadows etc… are easily coded for. This is because all of the tools in sketch can only produce attributes that can be converted to CSS. With photoshop you can go crazy with all the options available and have a very hard time translating your outlandish design to CSS. If you’re familiar with Rails you know how many decisions are made for you so you don’t have to waste time, Rails confines you but in a very good way. Any design in Sketch can easily be exported to the web. Many designers use ~3 different apps for 3 different tasks: wireframing, UI design, and vector logo graphics. Sketch is a one stop shop for all 3 of these tasks. Lastly, familiarity with grid systems is essential to building responsive sites. Sketch has a customizable grid system. Most of the time you’ll probably be using the default 12-columns but sometimes you’ll want to fit more content on the page and go with 16-columns.

Screenshot 2015-08-07 15.39.40

These are the 2-logos I was able to sketch, with Sketch…. hi-hat! I’m currently a student at Turing so I figured why not redesign the school logo. Turing is mainly a back-end developer program so design excursions like this are usually side projects. So how does someone with zero experience with this software quickly build a neat vector logo? Designing like anything else is essentially problem solving, and the best approach is to break everything down into tiny manageable chunks, just like programming. I sketched some stuff in my notebook to kinda have an idea of what I wanted and took it from there.

I split the logo up into a bunch of pieces: circles, lines, and text. Creating and styling each element taught me a little bit more about the software and anything I got stuck on I would google or find the 1-person I know who uses it. The biggest challenge was getting text to neatly wrap around an oval or any shape for that matter, thankfully Sketch has something called “Text on Path.” Believe it or not the big-logo on the right consists of 22-peices, 19-peices for the one on the right! After building all of the components separately I chunked some of them together for the assembly process, and wa-lah!

Why learning to code can be so difficult, oh because it’s so easy!

I actually wrote this around 3-months ago, forgot to post it, and just now read through it and decided it might be a worthwhile read for the struggling developer. As I move ever deeper into my programming career I still believe that programming is simple and should be approached with a simple open mind.

If you’re like me, you started learning to program later in life than the average bear. You were searching for something that would be both intellectually stimulating and creative… very difficult parameters for any standard career to meet. But the field of programming is such an outlier relative to anything else out there in the ‘real world’ abyss.

Being a decent programmer has very little to do with learning the syntax of a language and very lot to do with solving problems. You hear this mantra from almost every potential employer, “we’re looking for problem solvers.” The only problem is very few people posses this very fundamental skill. Why? We all have to solve small problems growing up. You have a flat tire and no cell phone reception… problem! You lose your house keys and phone while out getting hammered… problem! You’re kind-of ex-girlfriend sees you hooking up with another girl at a soccer game… you get my point. Maybe we’re just better suited for solving immediate pressing problems than having to sit down for hours and break an encryption app into it’s components.

I’m 10-weeks into my programming career and every day is still very challenging and requires laser like focus for extended periods of time if you want to keep up with the pace. My fellow classmates, some of the most intelligent people I’ve ever encountered seem to struggle in one way or another. The first 5-weeks of training seemed un-bearable at times. Objects as classes, methods defining behavior, instance variables defining state, dependencies, readable and writable attributes, testing methods, throwing pry bindings all over the place…. and on and on it goes with seemingly no end until you slap into the git wall and start encountering merge conflicts and failed pull requests. If you told me I would have a fundamental grasp of what I just listed 10-weeks ago, I would probably optimistically nod and doubt the possibility. But as with most things, when you apply yourself, and I mean really apply yourself good things happen.

What I’ve learned from myself and the brilliant people I’m surrounded with on a daily basis is, you have to slow down to go fast. Solving programming related issues doesn’t always come down to high IQ. Most often newbs like me spend hours upon hours on a small component of our applications only to see a more experienced programer implement something so simple you feel insulted by it. Deep down you know for a fact you could have come up with the same solution and frankly there was nothing complicated about it. It was just a different way to approach the problem. I’ve noticed that 9 out of 10 times when I can’t seem to solve a problem it’s not because I don’t have or posses the tools it’s because I don’t take those extra 5min to draw out the problem and each step on a piece of paper or just pseudo code it. This is where slowing down to go fast comes into the picture. A newbs instinct when confronted with a problem is to start typing things up without really understanding where they’re heading. Sometimes it works, which may only lead to developing a terrible habits. A more patient focused individual will sit down draw/sketch out the problem or at least one of the components and then start actually writing code.

Amazingly the fine folks at Turing warn the newbs countless times about the hurdles they are inevitably going to encounter and yet very few actually listen. Granted some people have a better ability to hold on to process and evaluate information. They’re just better thinkers, less cloudy in the head but even they’re not immune to tricky problems. Inevitably every seemingly complex problem I’ve solved turned out to be relatively simple, I just didn’t bother to incrementally take a linear step-by-step approach to solving it. I’ve since improved greatly. It’s a peculiar skill to acquire. Programming is easy it’s just not what most people are used to doing.

Humans are used to communicating with other conscious humans, not with algorithmic machines. We could easily tell a human to go to the supermarket and pick up a list of groceries but imagine telling that to a machine with it’s own language and operating system? What takes a few sentences for humans takes maybe a hundred lines for a machine. And being able to break down the steps of going to the grocery store choosing certain items in specific locations, putting those items in the cart, taking them out, putting them on the register table, waiting for them to be scanned, bagging them, paying for them, walking out of the store to the car, opening the car… you get where this is going. And that’s not even a fraction of all of the commands you have to tell your machine in order for it to properly execute. But when you think through it you realize how easy these commands are. Does it take time? Yes! But it’ll take far more time if you don’t think through the whole process in very tiny detailed increments. The newb out of the gate will skip and not think through the detailed algorithm, the master will. That’s why hard coding something that works, even if it’s 100 lines, is far better than 15 pretty lines of janky-ness. The 100 lines will easily be refactored into less than 15.

Community

I’ve been pondering about community lately. According to Abraham Maslow, satisfying the need to belong is a prerequisite to developing self-esteem and confidence, which in turn is a prerequisite for self-actualization – the motive to realize one’s fullest potential. These higher order needs require a social context, which is why belonging supports self-esteem in Maslow’s Pyramid.

HeirarchyOfNeeds

The need to belong is driven by evolutionary factors. It is a powerful, fundamental, and extremely pervasive motivation. Belonging helps people in times of trouble. It provides a place to share good and bad news and to avoid loneliness and feeling unloved. It’s the place to get the information and the real interpersonal rewards that build confidence and self-esteem. Belonging’s powerful effect on productivity is well-studied and understood in business and industry forums all over the world.

Turing has a strong blossoming community of students, instructors, teachers assistance, alumni, and mentors. Even though I’m taking this module off, I still visit Turing a couple days a week to get work done and spend some time with the hommiez. I never go with the intention of pairing with anyone but somehow end up pairing anyway, learning a shit ton, and feeling super fortunate to have access to such a cool place. Big shout out to Jeff Casimir for not casting me out into the desert. Since so many people from the Turing community have helped me solve so many different problems, I figured instead of just thanking them I would praise through presentation. So let’s reminisce.

Before Trey Tomlinson, a tall Scandinavian looking dude who just landed a sweet job at CaptainU, came into the picture I wasn’t sure how to use RSpec to test a change to my test database. Here’s an example of how I tested a user successfully registering.

Screenshot 2015-07-31 12.36.00

I was just using the within block and setting an expectation of what should appear on the page, not really checking whether a new user was actually saved to the database. Here’s the Trey effect.

Screenshot 2015-07-31 12.34.39

Orion Osborn recently graduated from Turing and is now working for Invoca, pointed me to a great tutorial on Heroku on how to set-up paperclip with Amazon S3. He also patiently watched in horror/confusion when I showed him the dark side of sending AJAX requests. Turns out when your AJAX is set-up improperly and you’re trying to make any changes to your database from within a pry-session, your pry-session hangs and you can press Control-C all you want but unless you kill all of your Ruby processes (kill -9 ruby) that facker won’t let you out! Alan Smith, Turing grad works at LivingSocial, was fortunate enough to have witnessed this sorcery first hand and suggest killing all Ruby processes.

DJ Greenfield, recent grad with Zeus like hair, actually got the ball rolling on setting up that AJAX request so I’m not sure whether I should hug or kick him. He also helped me pimp out my images with JQuery for this dinner-dashy rails-app I’ve been working on. The basic idea of what I was trying to accomplish: When a user hovers over a category-image, I would like the opacity of the image to cut in half and the category name to appear as a link to that category’s-show-page. Seems simple enough right? F**k No! Along with DJ I had to recruit Justin Holmes (Former Dolphin trainer for the NASA Dolphin In Space Expedition and contestant on The Bachelor) for this delicate affair. I think we all learned more about JQuery and CSS inheritance in those couple hours than in the past few months! Everything works except the text(category-name-link) is inheriting its opacity from the image making the image and text fade upon hovering….. Brutal if you ask me, but I’ll move some divs around later on tonight and get it working. Once what’s in the computer behaves the way I want it to, I’ll write an educational blog post.

Even though Sally MacNicholas has to manage 2 kids, she still has the tenacity to produce the best API curious I’ve seen this module. She basically consumed Instagram’s API and reproduced the user dashboard page, it looks better than it looks on the real Instagram! She also took some headshots and cool pictures of Rob, Vanee, and I. I still haven’t received them, a-hem a-hem, but I have faith in Sally.

Robert Cornell, student at Turing, father of 2 teens, recently re-married, and co-founder of a tech-start-up is my friend and Turing lunch buddy. Tough to believe how he even has the time to do anything! Rob laid the guilt trip on real thick when he found out I was taking this module off! He’s since calmed down, maybe because I show up and have lunch with him from time to time. Maybe because he spent all of last week hyping up going out on Saturday and backed out 5-hours before game-time.

Regis is the new kid on the block who’s quickly made it to my list of top-five people at Turing I would do acid with. I feel like I become a smarter bohemian every time I speak to him. Our most recent conversation started with Node.js being single threaded, led to people resembling virtual machines, and ended with everything just being a box within yet another box.

Drew Reynolds is the go to for creative sass on the web, start-up knowledge, and a sick new techno/trance mix to pump out code to. When he posted a link to p5.js last week my mind was blown yet again. I’m totally into front-endy stuff and that library is just a treasure.

That rails app I was working on, I set it up in a way that forces an Admin to either add a new item to an existing category or create a new category for that item all from one form. In this form I had a dropdown menu that contained all of the existing categories and a “New Category” place holder. So I said to myself, wouldn’t it be sweet if you could click on “New Category” and have an input field magically appear? heck yeah it would. So Patrick Medaugh, myself and JavaScript’s bastard child JQuery went to work. An hour later, we made magic happen.

Screenshot 2015-07-31 21.40.42  Screenshot 2015-07-31 21.35.53

I started using Sketch a few weeks ago and I must say it’s pretty awesome. If you’re into graphical design UX/UI stuff I would highly recommend you check it out. I was struggling to figure out how to wrap text around curved lines or shapes. There’s not too many designers a part of the Turing community. Thankfully Cara Jo, a denver based web-designer happened to join the Turing community. I messaged her asking if she used Sketch and how I could get this darn text to hug stuff! Short story shorter, she helped me get it to work and I produced this masterpiece.

marz

Incredible isn’t is? So that’s a very brief case study of my past few weeks within the Turing community! If you’re not currently a part of a community Maslow thinks you should probably find one.