Skip to main content

Mobomo webinars-now on demand! | learn more.

code@2x-2

PHP

The positives:
The potential downsides:

 

Ruby

The positives:
The potential downsides:

The ugly side of both:

Both either provide or use templating language/tools. This is a trap, don’t do it. Let server side handle server side, and front end frameworks handle the rest.

And the last word…

PHP may be a language that’s easier to use and pickup on the server side than Ruby, but historically it has a hard time competing with Ruby when it comes to its frameworks’ capabilities.

Categories
Author

JSON Web Token is a simple way to send information in the clear (usually in a URL) whose contents can be verified to be trusted. When might you use something like this?

  • In a Single Sign-On scenario where you want a separate authentication server that can then send user information in a trusted way. I wrote omniauth-jwt recently for just this purpose
  • When generating "one-click" email action links (as I talked about once before on this blog, but this is a better method!)
  • Any time you have the need to communicate a small payload of information between two sources via an unsecured transport

Before we get started, it's important to note that JWT does not encrypt the payload, it only signs it. You should not send any secret information using JWT, rather you should send information that is not secret but needs to be verified. For instance, sending a signed user id to indicate the user that should be logged in would work great! Sending a user's password would be very, very bad.

JWT works by simply encoding a string made up of a small JSON object and hashing it using a secret shared between the two parties. The algorithm is configurable, but is usually HMAC SHA-256. So how do we do this in practice? We'll take a look at a simple example of an email action link. Let's say we have a new social network and we're sending an email for someone to confirm a friend request. The information we want to send might look something like this:

{   "user_id":12345,   "friend_id":23456 } 

Of course, we can't just send a link that would, without any verification, friend one user ID to another. So we'll need to use JWT to sign it! Our example here will be in Ruby, and you'll need the jwt gem in your Gemfile.

require 'jwt'  EMAIL_SECRET = 'im-a-teapot'  payload = JWT.encode({   user_id: 12345,   friend_id: 23456 }, EMAIL_SECRET)  link = "http://myapp.com/emails/friend?jwt=#{payload}" 

You would then send the above link in the email and let the user know that if they click it they'll accept the friend request of the user represented by friend_id. The user then clicks the button. So how do we verify this when the link is clicked?

get '/emails/friend' do   payload = JWT.decode(params[:jwt], EMAIL_SECRET)   User.find(payload["user_id"]).add_friend!(payload["friend_id"])   "You accepted the friend request!" end 

That's all there is to it! Now the users are friends and there was no complicated login process needed! Of course, there are security concerns with this approach. As it stands, there's nothing stopping someone from "replaying" this token at a later date. If the users stop being friends but the same URL is visited a year later, the link will still work. JWT comes with a few different recommended ways to mitigate this:

  1. You can include an iat claim in your payload that is a UNIX timestamp of when the token was issued. The decoder should then check that this timestamp is within a certain valid window or otherwise reject it.
  2. You can include an exp claim in your payload that is a UNIX timestamp indicating when the token will expire. The decoding end should check that the current time is before the expiration and otherwise reject the token.
  3. You can assign a unique value to the jti claim. This way, the decoding end can check to make sure that the token has never been consumed before, making sure that it is one-use.

There are a few other registered claim names that might come in handy depending on your usage.

That's really all there is to it. There are JWT libraries available for most languages, and they're all very simple to use. JWT is a fantastic and simple way to communicate trusted information across untrusted channels. Hope you find a good use for it soon!

Categories
Author

As part of my work, I often create prototypes of Rails applications. My preferred tool for doing this is Serve. But as excellent as it is, it's a very thin application with no persistence layer. To be honest, I don't really want a persistence layer at this stage. But there are times when I want to be able to iterate over collections of objects the same way that I would in a Rails environment. Creating an index view of subscribers is a great example.

Now, I could just draft this all as html:

...but that's time consuming. Especially if you have more than a few. Sometimes you want to stress test a larger data set (to show pagination, for example, or to work out JavaScript performance on larger data sets) or just give a better match to real data.

To accomplish this, I use the Storable and Faker gems.

Enter Storable

Serve provides a views/view_helpers.rb file, which is where I will store my ruby code. Since Storable can read YAML files (and because I do often use fixture data in real Rails apps), I use YAML as my data store.

Let's set up the data store first, using a Subscriber model. You can go about this one of two ways:

  1. build your models by hand (the same way you would create fixtures for RSpec), or
  2. randomly generate a set number of models.

You should choose your approach based on what your end goal is; since I'm just trying to quickly populate a lot of data, I'll go with some random generation.

Enter Faker

The ERB loop uses the Faker gem to create a first and last name, which it then uses to create the object's key and describe the object's attributes. This setup will create 10 of these objects. I could even use this later to seed fixture data for tests; in that case, I'd define those objects manually.

Now that we have the data store in place, let's do something with it: create some ruby objects:

This creates a class that we can marshal our data in to, enabling us to create our collection. The field definitions default to being Strings, but (as you can see with :id) you can specify a type using Ruby's hash syntax.

Massage that fake data!

I've also added a full_name method to the class, since I know that I'll want to display a Subscriber's full name in the "first_name last_name" pattern. You can define any number of methods that you want here.

Next is a self.bootstrap method, which accepts a file path as a parameter. This reads in the specified YAML file, processing it through ERB (the load command with the ERB wrapper can be replaced by load_file if you're just using straight YAML), and then creates a new Subscriber instance for each object defined in the YAML file.

Finally, there's the self.all method, which similarly to the Active Record finder method of the same name, without the database call. It will search the active Ruby object space and return all of the objects of the Subscriber class.

This implementation of #all is a bit crude, but it works.

Voila

With all of that taken care of now, we can finally get back to our view and do this:

...which is much easier to maintain, especially if that bit of HTML code is rapidly changing. Storing the data in the YAML file (especially inside of a loop), means that adding/removing/modifying the object's attributes is much easier to do as well, and with a lot less typing.

Categories
Author

As the focus on multithreaded Ruby grows and grows, code autoloaders seem to be a less and less manageable solution. By the same token, it can be pretty ugly to manually require dozens of files or come up with complex schemes for requiring files.

Node.js has a pattern that I personally enjoy: if you require a directory, it will automatically look for a file called index.js in that directory and require that if present. This, to me, presents a simple, usable way to manage complex require schemes. On a whim, I decided to see how easy it would be to implement such a pattern in Ruby. Turns out it's not hard:

def require(path)     super rescue LoadError => e     searches = $:.map{|dir| File.join(dir, path)}     searches.each do |search|         if File.exist?(path + "/index.rb")             return require path + "/index"         end     end     raise e end

This implementation is simple, naive, and likely extremely dangerous in ways I don't understand. What it does is simply take the path specified in the require call and walk through the load path, looking for an index.rb file in a directory denoted by the path. If it finds one, it requires that and returns. If it doesn't, it raises the standard LoadError.

I'm not an expert on Ruby's file loading internals, which is why I spent five minutes making this hack method instead of trying to come up with an actual elegant solution. What I want to do, however, is start a conversation about whether this pattern makes sense or has a place in Rubyland. I think it would be nice to have a structure like this:

# In e.g. "application.rb"  require 'app/models'   # In app/models/index.rb  require 'app/models/user' require 'app/models/post' # ...

It keeps everything explicit (I've become a big fan of explicit requires as opposed to directory or name-based autoloading) while still keeping a syntactically nice require call that describes what is happening quite well.

So what do you think? Is this a pattern worth exploring? Is this maybe a gem waiting to be written? Should it be made part of the core language? Let me know in the comments below or tweet @intridea with your thoughts!

Categories
Author

This past weekend I participated in Random Hacks of Kindness (RHoK) hosted by the OpenGov Hub in DC. I attended my first RHoK event in June of 2010 after reading about it on slashdot, and I ended up working on a winning project. I've been a regular at the event ever since. I was extra excited this time around because RHoK was being held alongside the first ever Sanitation Hackathon, an event that tries to find technological solutions to some of the very serious sanitation problems around the world.

The event kicked off with presentations from subject matter experts on situations that called out for aid. Problems ranged from the illegal dumping of septic waste, to finding a way to better connect domestic violence victims who are working to re-build their lives with socially conscious employers, in order to ease their re-entry into the work force. 

More people have access to cell phones than to clean and safe toilets

The problem that piqued my interest was submitted by the Peace Corps where tro-tro passengers had to wait in the vehicle until it was at capacity because there was no line of communication between the driver and passenger notifying them when it was departing. Not only was the problem well defined and solvable in one weekend, but the solution could also be general enough to be applicable to any situation where someone has to send notifications to a group without the painful process of gathering emails or phone numbers from everyone and sending a group message. 

I worked with Chelsea Towns, a RHoK veteran who works for the Peace Corps and Thad Kerosky, a developer who used to be a Peace Corps volunteer in Tanzania and Liberia. The solution we provided was an SMS based notification system that allows anyone to create an event, a trip in case of the tro-tro driver or conductor, which anyone can subscribe to receive notifications for. The technology we used was Ruby on Rails deployed to Heroku, using Twilio API for the SMS part. We named the project Tro-Tron.

Usually at other hackathons, things are a little more competitive and folks are focused on getting their projects done by the deadline. At RHoK the amount and quality of collaboration is awesome; you will always find people moving from team to team trying to help out as much as they can, and it is not unusual to have a lot of people contributing to more than one project. My favorite part of the weekend was meeting so many new people, I met three different Peace Corps volunteers who were in The Gambia, one of them back when I was still a baby. I also got to meet Javier for the first time, another Intridean who brought a lot of energy and helped test the application.

RHoK wrapped up on Sunday with some impressive presentations and demos. You can fork the project on github and view photos we took at the event on flickr.


History of RHok: in 2009, some good folks from Microsoft, Google, Yahoo NASA, and the World Bank started the Random Hacks of Kindness (RHoK) hackathon, an event that aims to connect subject matter experts in disaster management and crisis response with volunteer software developers and designers in order to create solutions that have an impact in the field. Since then, RHoK has grown into a community of over 5000 in over 30 countries around the world.

Categories
Author

Last weekend I had the opportunity to speak at RubyConf 2012 about a topic that is very exciting to me: Cross-Origin Resource Sharing (CORS). CORS allows for true cross-domain AJAX in the browser which, while simple in concept, is powerful in potential. The fine people at Confreaks recorded the session and you can watch it here:

There are two extremely interesting new things you can do with CORS (and probably many more yet to be discovered):

  1. SOA in the Browser. With CORS you can implement lightweight HTTP services that are called and coordinated through the browser instead of on the server. This gives you the modularity to scale pieces independently without the complexity of weaving together a server-side service fabric.
  2. Serverless Mashups. When more APIs implement CORS (like GitHub and Amazon S3 currently do) it will be possible to construct mashups with zero server-side code that can be hosted statically and distributed via CDN.

To find out more about how to implement CORS in your Ruby web apps and my thoughts about where this all is going, check out the video.

Categories
Author

The Rails community has had its share of misogynistic debacles over the last several years. Dominated by male programmers (recent statistics suggest 94% of employed Rails programmers are male), the inroads to professional Rails development for females are not exactly accessible or welcoming.

Of course, it's not just the Rails community that lacks representation from women. When only 18% of the Computer Science undergraduate degree recipients in 2010 were female (Source - NCWIT.org) it's obvious there is a lack of female participation in the entire field of programming.

Though the speculation of why this has become a problem is varied, Rails Girls is a movement that's focusing on the more important part of the equation - solving it.

No community can be considered healthy without a balanced representation in gender and race. That's why at Intridea we're excited to sponsor Rails Girls DC, taking place September 14-15th at the Living Social offices in Washington, DC. We're supporting Rails Girls because we want to foster a healthier community - one where women are building their great ideas alongside men, in equal numbers and with equal opportunity.

Women can apply now to attend the free development workshops that are taking place around the world including Germany, Estonia, Spain, Belgium, and more. Additionally, Rails Girls has open sourced their guides to organizing these events, making it easy for Rails developers to change the shocking statistics that plague our community.

We're looking forward to being a part of this great event. Additionally, we're hiring Rails developers and women are encouraged to apply!

Categories
Author

Don't cry. We've all been there too. Regression issues in the presentation layer make the entire team go crazy. Why can't we have a methodical way of testing the UI to ensure once designs are styled as views, they stay the way they were created?

The first release of GreenOnion is an attempt at just that. It moves from testing code to testing the visual interfaces that designers have envisioned and end-users will interact with. Developed after reading Jeff Kreeftmeijer's post on creating image diffs, GreenOnion brings together both OilyPNG and Capybara to test the UI.

RSpec, MiniTest, Test::Unit all allow devs to create solid code using BDD/TDD, but there has yet to be a good way to make sure bugs are not introduced in HTML and CSS. Sure, we have Watir and Capybara (a dependency of GreenOnion), but these tools are more focused on the functionality of views rather than how they actually look. GreenOnion captures and compares what the user would actually see. There will never be a sure-fire way to fully automate testing something so subjective as visual aesthetic, but GreenOnion should help the designer or developer by highlighting where things might be going wrong.

The GreenOnion workflow

  • Run skin method for the 1st time on a URL (best case would be if the styling of the page was correct)
  • Save skin
  • Run skin method for the 2nd time on a URL
  • Compare 1st skin to the 2nd (fresh) skin

Percent of change

GreenOnion.skin_percentage(url, threshold [optional])

The primary feature of GreenOnion is seeing how much (if at all) a view has changed from one instance to the next, and being alerted when a view has surpassed into an unacceptable threshold.

What do we mean by threshold?

The threshold is the percentage of pixels that are allowed to change from one iteration of a view to the next. This will give the view tolerance of change, and if that tolerance has been surpassed, then the test will alert the developer.

Visual change

GreenOnion.skin_visual(url)

Once you are aware of a issue in the UI, you can also check out where the offending issue may have taken place. You should open your "skins" directory, and check out the files with "_diff.png" at the end of the filename. The pixels will be highlighted and will have the same effect as the Photoshop "difference" filter.

Roadmap

We hope that this is just the beginning of more robust testing in the UI. Here are some areas that we will focus on in the future:

  • Screenshots can either be viewed as a visual diff, or overlayed newest over oldest and viewed as an onion-skin with sliding transparency.
  • Allow for flexibility in picking browsers
  • More robust skinner generator
  • Should allow for testing using fixtures/factories
  • Flexibility in skin filenaming
  • Test with UI events
Categories
Author

I'll be spending the last weekend of July with passionate Ruby developers and pioneers in Burlington, Vermont - a small but charming city situated on the eastern shore of sparking Lake Champlain, and the perfect spot for Vermont's first Ruby conference, BURUCO.

Though this is a much anticipated retreat from the commotion of New York City (which is where I've been spending the majority of my time for the last several months), it's also an exciting opportunity for me to share some of the recent work I've been doing on spatial programming and location based apps.

I'm looking forward to sharing my knowledge, connecting with other developers, and learning from other giants in the community who are doing meaningful work. There will be interesting presentations from:

  • Marc-Andre Cournoyer, author of "The 4 Hour Work Week For Ruby Hackers"
  • Joshua Hull and Alex Maccaw of Twitter. I'm looking forward to learning more about Renee in Joshua's talk and getting an inside look at Spine, a JavaScript framework Alex wrote.
  • Dan Croak from Thoughtbot who will be diving into Rails conventions.
  • Scott Tadman, creator of PostageApp.com - a SaaS-based Email Delivery service for web apps - will be presenting on building asynchronous server applications with Ruby and Rails.
  • Jen Myers of Relevance will be talking about the area where design and development intersect and how developers can leverage design principles to build better applications.
  • Harold Gimenez who builds tools on top of Postgres all day long at Heroku and will be demonstrating its power and usefulness.
  • Mark Bates, founder of Meta42 Labs, a Boston-based consultancy who will be presenting on testing JavaScript and CoffeeScript in Rails.

 

Categories
Author
Subscribe to Ruby