cmcguigan333

Author Archives

Know Your Options: Alternatives for Live Data in Rails

Or: Alternatives to web sockets/action cable (in case, you know, you’re a masochist)

 

For the uninitiated, web sockets allow for a continuous connection with data- our gmail account’s fancy ability to fancily deliver emails in fancy real time is one example of this, as would be a stock ticker that updates in real time (real time meaning milliseconds). Action cable is rail’s fancy new way of integrating web sockets, and while everyone is terribly excited about action cable’s potential and web socket’s capabilities I figured I’d give a little bit of back ground as to why web sockets are considered to be so neat.

 

Back before web sockets, there were three popular ways to open a continuous data connection-
1 Polling- Polling involves the client asking the server, on a set interval (say, three seconds) if there is any new data.Returning to the “live comments” example, let’s say we have a page with a comments section. To create this application with polling, we can write some Javascript to ask the server every three seconds for the latest comment data in JSON format. If there is new data, we can update the comment section.
The advantage of polling is that it’s rock-solid and extremely simple to set up. For these reasons, it’s in wide use all over the Web. It’s also very resistant to network outage and latency – if you miss 1 or 2 polls because the network went out, for example, no problem! You just keep polling until eventually it works again. Also, thanks to the stateless nature of HTTP, IP address changes (say, a mobile client with data roaming) won’t break the application.

However, regarding scalability… You’re adding considerable load to your servers by causing everyclient to hit your server every 3 seconds. There are ways to alleviate this – HTTP caching is a very good one – but the fact remains, your server will have to return a response to every client every 3 seconds, no matter what.
Also, while polling is acceptable for “live” applications (most people won’t notice a 3-second delay in your chat app or comments thread), it isn’t appropriate for rapid back-and-forth (like games) or streaming data.
2 Long-Polling – Long-polling is a bit like polling, but without a set interval between requests (or “polls”). The client sends a request to the server for new data – if the server has new data, then it sends a response back like normal. If there isn’t any new data, though, it holds the request open, effectively creating a persistent connection, and then when it receives new data, completes the response.

 

Exactly how this is accomplished varies. There are several “sub-techniques” of long-polling you may have heard of, likeBOSH and Comet. Suffice it so say, long-polling techniques are considerably more complicated than polling, and can often involve weird hacks like hidden iframes.

 

Long-polling is great when data doesn’t change very often. Let’s say we connect to our live comments, and 45 seconds later a new comment is added. Instead of 15 polls to the server over 45 seconds from a single client, a server would open only 1 persistent connection.

 

However, it quickly falls apart if data changes often. Instead of a live comments section, consider a stock ticker. A stock’s price can changes at the millisecond interval (or faster!) during a trading day. That means any time the client asks for new data, the server will return a response immediately. This can get out of hand quickly, because as soon as the client gets back a response it will make a new request. This could result in 5-10 requests per second per client. You would be wise to implement some limits in your client! Then again, as soon as you’ve done that, your application isn’t really RealTime™ anymore!

 

3 Server-sent Events are essentially a one-way connection from the server to the client. Clients can’t use SSEs to send data back to the server. Server-sent Events got turned into a browser API back in 2006, and is currently supported by every major browserexcept any version of Internet Explorer.

 

Using server-side events is really quite simple from the (Javascript) client’s side. You set up an EventSourceobject, define an onmessage callback describing what you’ll do when you get a new message from the server, and you’re off to the races.

Server-sent event support was added to Rails in 4.0, throughActionController::Live.
Serving a client with SSEs requires a persistent connection. This means a few things: using Server-sent events won’t work pretty much at all on Heroku, since they’ll terminate any connections after 30 seconds. Unicorn will do the same thing, and WEBrick won’t work at all. So you’re stuck using Puma or Thin, and you can’t be on Heroku. Oh, and no one using your site can use Internet Explorer. You can see why ActionController::Live hasn’t caught on. It’s too bad – the API is really simple and for most implementations (“live” comments, for example) SSE’s would work great.

 

(All descriptions from THIS fantastic article written by Nate Berkopec:https://www.nateberkopec.com/2015/09/30/action-cable.html)

 

So, how does this effect us? Well, I think it’s only a matter of time before all of us, in our new development jobs or in our awesome, shinny side projects, will want to at least take a shot at creating a real-time updating, persistent data connection enacting, super fantastic application, and when the time comes to create it, it’ll be nice to have a head start in knowing what your options are.

How to plan your next rails app

For me, there’s no such thing as too much planning. When I travel, I pack 3 or 4 days early, to make sure I don’t forget anything. It’s a little extreme, I know, but hey, I haven’t forgotten anything super important in 15 years of traveling on my own!

I’m writing this blog post because while I’ve seen some good answers to this question around the internet, they’re all scattered around in random places, hidden in stack overflows and under various neglected corners. This is an attempt to consolidate all the information I’ve found and stick it in one place.

When I’m building something as potentially intricate as a rails app, I sure as heck want to know beforehand EVERYTHING I’m about to do.

So it comes as no surprise that I have a keen interest in what the ‘best’ way is to plan out your app. And yes, I’m aware of the ‘draw out the path of your app’ way and the different visualizing applications out there designed to help you solidify your plans, but I wanted to know if I could go further with it. Is there a truly foolproof process? One that is repeatable as well as documentable?

Here’s what I found:

Primary Questions

There seem to be three big questions (hereafter referred to as ‘the big three’) people ask when discussing app design, and these are: Do I plan out the Front-end/User Interface or the backend/models first? When should I start testing? And how do I make my app as efficient as possible?

UI or Backend first?

Of course, this falls to preference, however there seems to be a common thread: Anecdotally, those who started with the backend and left the front end for later found that they had to do significant refactoring later on, mainly because it turned out that the way users were going to interact with their app didn’t fit into the rigid constraints of their models and associations. User interaction, like human beings themselves, are not so easily encapsulated. This is one reason why they’re fun to design for (as opposed to cats. Have you ever designed an app for cats? Oh my GAWD) but its also why this aspect of app building is so difficult. Users will find ways to interact with your app that you never even dreamt of- this is good and right, in my opinion, as long as it’s safe and respectful (and legal), but it does make design tricky.

Here are two great threads, one from reddit and one from stack overflow, for further reading:

REDDIT

STACK OVERFLOW

When should I start testing?

In short, as soon as possible. Developers who said that their teams used a ‘build tests later’ approach sincerely regretted it because going back to write tests for code you may have written days or weeks ago is difficult. It’s easiest to write tests as you write the code the tests are for, according to several of the articles I read.

Like this ARTICLE

How do I make this thing as efficient as possible?

In order to answer this question, you should ask yourself two others: What will my app do? And perhaps more importantly: what will it NOT do? It is incredibly important to not overreach in the design phase of your app. Yes, go ahead and dream big, make your app the best thing ever, but then plan it and pare it down, then pare it down again. Kill your darlings, break it down to its absolute essentials. Make it so that your app does one thing great, not two or three things in a confusing, poorly designed way.

I have to come clean, I saved the best for last. Here’s a great guide to help you design your next app: THOUGHBOT’s GUIDE

This is thoughtbot’s playbook on how they make stuff, from the first post-it sketch to when the first user interacts with the finished product. There doesn’t seem to be anything else quite like it out there on the internet. It is incredibly thorough, informative and inspirational, and I suggest you take the time to read through every part of it.

Thanks for taking the time to read through this article, hopefully it gave you a decent idea of where to start when designing your next big project. As always, I’ll update this article if I come across any new and exciting info.

Let’s talk about self real quick

To understand self, or the concept of self, it will help to understand methods and instances.

A method call in Ruby is the sending of a message to a receiver- the message is the method and the receiver is the object. What is an object? I’m so very glad you asked!

An object in code is a thing with all the data and all the logic required to complete a task. Objects are models and metaphors for the problems we solve in code.

Basically, an object as defined in Ruby is very similar to an object as defined in real life- it’s a thing that has an identity, it can also ‘hold state and manifest behavior by responding to messages’, as this wonderful article on objects from Ruby Monk puts it.

https://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/39-ruby-s-object-model/lessons/127-object-identity-what-is-an-object

An ‘instance’ is an iteration of a Class, so for instance (get it!?!?) – If we have…

class Fresh
def broccoli
puts “Broccoli! Fresh!”
end
end
Fresh.new.broccoli

The instance here would be Fresh.new, with the method broccoli being called on it, returning “Broccoli! Fresh!”

So, now that we know these things, let’s get into self-

“The keyword self in Ruby gives you access to the current object – the object that is receiving the current message.”

So let’s say that self is like the T.A.R.D.I.S. with a fixed chameleon circuit- there is always one and only one T.A.R.D.I.S. but this T.A.R.D.I.S. can be many different things in the context of when it is accessed.

Ok, for those of you who aren’t Dr. Who fans (what are you doing on this blog?) this means that self is a fixed concept, but the identity of self is subject to change. The origin of this changiness (my word, not real) is when and where it is accessed, i.e. within any method you’re using self in. Yea it’s not easy to grasp, just read this blog post a few more times, see if it helps. If it doesn’t, grab yourself a space and time machine and boom, you’ll have all the time in the multiverse to grasp it.

Pry it

Everything you wanted to know about pry, but were too afraid to drop a binding.pry into

Pry was created by John Mair (NOT Mayer)

Here’s his twitter: https://twitter.com/banisterfiend

I wasn’t able to find anything on why he decided to make this, what his motivations are or his history, but he does state in the documentation of pry that he wants it to eventually have the amount of functionality of lisp, so I think its safe to conclude he wasn’t happy with the options out there and wanted to improve on the standard REPL, for instance IRB.

Reminder: IRB is the interactive Ruby shell, and allows us to write, test and modify code as we go.

Pry is a REPL, or read-eval-print-loop, also known as an interactive top-level or language shell. A REPL takes single user inputs (or single expressions), evaluates them and returns the result to the user.

Pry is like IRB but with a lot more functionality, like saving history between sessions, auto-complete, syntax highlighting and auto indentation.

Ok, enough with the histrionics, here are 5 cool and (probably) lesser known tricks for Pry:

Since many of our use cases will involve using pry’s ability to ‘pause’ our programs by dropping a binding.pry into them and not necessarily utilizing pry on its own, I’ll gear these tips towards that way of using it. Suffice it to say however that pry can indeed be used independently, on its own, to write, experiment and even bring code out of pry into a file, instead of the other way around.

1 Search your history- hist –grep makes it easy to search through your pry history-

6] pry(main)> def foo

[6] pry(main)* puts “whahwa”

[6] pry(main)* end

=> :foo

[7] pry(main)> show-method foo

From: (pry) @ line 1:

Owner: Object

Visibility: public

Number of lines: 3

def foo

puts “whahwa”

end

[8] pry(main)> hist –grep foo

6: def foo

9: show-method foo

2 ‘Show-method’ which will show you the source of a method (usually used for something you wrote)

3 Mess up a line of code and can’t figure out how to go back? Here’s how –

amend-line N replacement code where N is the number of the line (or range of lines using A..B syntax) you wish to replace. The amend-linecommand is usually used in concert with show-input command.

4 The play command -If you’re confident that your binding.pry is in the right place but don’t know exactly where your code is going wrong, the play command might be super helpful. This command enable you to replay code from files and methods as if they were input directly into the REPL. Supported options:

Use the -l option to restrict a subset of lines to be played
Use the -o option to play Pry’s output history
Use the -i option to play Pry’s input history. This can only replay pure Ruby code, not Pry commands.
Use the -s option to select the super method. Can be repeated to traverse the ancestors
Use the -d option to play documentation for methods
Use the –open option to play the selected content except the last line (which is usuallyend). amend-line can then be used to modify the method
For instance, if you’re in pry after hitting a binding.pry (on line 5), you can type in ‘play -l 6’ and pry will then run the code on line 6. Pretty cool.

5 the -wtf?(??????!!) command

The creator of Pry seems to have a pretty good sense of humor, as finding the backtrace for an error requires you to type it wtf? Further, you can even add ? or ! to your command to see more lines.

Of course, the best documentation comes from the source, so if you’d like to find more tricks or get more specific with the ones I described above, head over to the pry wiki at https://github.com/pry/pry/wiki/User-Input on github. Happy prying!

Further resources on pry:

Great talk by Conrad Irwin about REPL driven development with Pry: https://www.youtube.com/watch?v=D9j_Mf91M0I

https://www.bignerdranch.com/blog/my-top-5-pry-features/

Armoire

Screen Shot 2016-07-09 at 2.47.12 PM

ARMOIRE: look great so you can focus on what matters.

Armoire is an intuitive real time apparel planner and scheduling platform. It optimizes your daily outfit selection based on:

  • Apparel/Accessories/Shoes you already own, your current geocoordinates, amongst other factors (time since last worn, color coordination, amount of likes by friends etc.).
  • Incorporates: Ruby on Rails Relational mapping: PostgreSQL User authentication and session: Devise Bootstrap customized with SASS Early Beta currently located on Heroku: intense-harbor-75235.herokuapp.com/

Features:

 

 

  • Users can uploaded pictures, set attributes of their favorite garments, shoes and accessories.
  • Users can create their own unique outfits, and preview before adding to their Armoire.
  • Alternatively users can generate random outfits, or view customized recommendations based on a proprietary algorithm.
  • Users can friend, favorite outfits and communicate with other users.
  • Weather API integration (Forecast.io) for real time updates based on season/weather reports.
  • Clean, user friendly interface

Authors: Jen Abella, Chris McGuigan, Chris Bradshaw, Maisie Athens

Smooth To-Do List

poster
00:00
--
/
--

 

Click HERE to see this on my Github!

 

  • Utilizes React JS and the Flux architecture. It’s meant as a tutorial or guide for how to build a React JS application.
  • Npm and bower for package management, the default Bootstrap theme, LESS CSS for minor style and positioning adjustments, and finally brunch to build it all up and provide a simple web server.
  • EventEmitter for event notifications as per the Flux architecture.

 

Goodli

[WPGP gif_id=”161″ width=”600″]

Screen Shot 2016-07-08 at 2.47.05 PM

Click HERE to check out Goodli live on Heroku!

Description

LinkedIn for the social conscience.

 

 

[WPGP gif_id=”172″ width=”600″]

Background

The core features of the app were built in two weeks as part of Flatiron School’s project mode. We began Goodli as a way users to create socially impactful events and highlight their involvement in socially impactful events. The app promotes engagement through the exchange of karma points for event participation.

[WPGP gif_id=”181″ width=”600″]

Features

Event and Karma CRUD Actions – Change.org API Integration – Integrated Bootstrap Theme with Ajax functionality – User Registration and Session functionality with Devise

[WPGP gif_id=”183″ width=”600″]

Contributing

Fork it (unless you’re core team)
Create your feature branch (git checkout -b my-new-feature)
Commit your changes (git commit -am ‘Add some feature’)
Push to the branch (git push origin my-new-feature)
Create new Pull Request

Authors

Evan Hawk (@evanahawk), Chris McGuigan (@chris_mcguigan) , George Toothman (@georgetoothman)

License

Goodli is MIT Licensed. See LICENSE for details.