Posted 22 days back at GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS - Home
Episode 50: It's Monday today, let's change everything:
In this week’s podcast episode, recorded at RailsConf 2013, Ben Orenstein is joined by Jeff Casimir and Katrina Owen from Jumpstart Lab and gSchool to discuss performing, speaking, and imposter syndrome, preparing for your talk, and what makes a good talk and how to give one. The also discuss gSchool, the way the program works and they way it’s guaranteed, teaching, admitting ignorance, how good practice should be harder than the real thing, and why Jeff didn’t like studying Computer Science and why he didn’t enjoy programming and how Rails reignited his passion for creating things, and much more.
Posted 23 days back at Luca Guidi - Home
[ I wrote this post for frestyl, you can find the original article here. ]
Here at frestyl we're working hard, using cutting edge technologies to promote their wider-scale adoption and to help set the new standards with our direct experience. In the past months our geolocation service has been changed from a somewhat flaky IP lookup to the new HTML5 W3C draft. Our users noticed the difference and they are happier of the new level of precision.
Technically speaking, the migration was challenging because our home page (the natural entry point for a web app) is a huge map which shows the events around the user. Previously, we silently located the user through a server side process, put that location in session, and loaded the map. No big deal, just a classic request/response cycle. However, implementing the new standard means that browsers will notify the user when an application is trying to get their current location.
So what is the best way to handle this? Taking a UI page from the mobile development community, we chose to block our application with a modal dialog that aims to focus the user's attention on the browser's location prompt. Once the user responds to the browser, we change the state of the page accordingly. If they accept the geolocalization then we reload the page and display the map with content around the user's current location. Alternatively, if they decline, we prompt the user to explicitly enter a location, any location, around which they would like to base their experience.
For frestyl geo is beyond essential, the application works on the assumption that everyone has a location, and so we can't let users dive in until they have specified where they are (or more accurately, where they want to see content for). By using a modal dialog we are taking a risk, but we are also making a bold statement. Location is actually that important. If it is true for mobile platforms ‐ why should we consider a laptop to be any different?
Aspirations aside, as you can imagine all this workflow is hard to test. Before we were just mocking the IP lookup against the various scenarios (success/failure/timeout) with RSpec and everyone was happy about it, but now, it's all done via javascript and things are more complicated.
We want to share with other people facing similar challenges our experiences of how one might best write integration tests for the new HTML5 standards for Geolocation.
Step 1: Clarify the Goals
First of all: we separated acceptance tests from behaviors: the former are run via Cucumber (using Capybara) and the latter with BlueRidge (using Screw.Unit). The behaviors were easy to test, we wrapped the HTML5 Geolocation API with: $.location and re-mocked all the scenarios. The hard part was to run integration tests in real browsers (which is the goal of this post).
Let's say we want to run this Cucumber feature:
@javascript
Scenario: User is geolocalized
When I go to the home page page
And I share my location and it returns "41.8954656,12.4823243"
Then I should see a "Location found at: 41.8954656, 12.4823243" message
Step 2: Proxy the API
For obvious security reasons, developers can't access the Geolocation prompt that the browser gives to the user. This means that we can't even simulate a user click on accept (or reject) of the location lookup. So what to do? The main idea was to completely replace the Geolocation system while the tests were running, but if you try to assign something to navigator.geolocation the browser raises an exception (or ignores it entirely, like Chrome).
Our solution was to use a proxy to access to the wrapped API:
$.location = {
// window.geolocation_provider is useful for testing purposes, not used in
// development/staging/production envs.
geolocation_provider: window.geolocation_provider || navigator.geolocation
}
// usage:
$.location.geolocation_provider.getCurrentLocation(successCallback, errorCallback)
Step 3: Rack to the Rescue
Sounds great, yeah? Let's get to the interesting part: we need to set the window.geolocation_provider before the DOM is ready (the usual hook we use to initialize all the page scripts), otherwise the browser will still continue using navigator.geolocation.
To solve this we used a Rack middleware to inject some javascript just after the <head> tag is opened, so the browser immediately executes it, assigning the value we want to mock.
Step 4: Simulate Scenarios
We're not done yet, we still need to simulate user choice (accept/deny), Geolocation success, timeout and error scenarios. We easily can set from Ruby some Javascript top level vars for this purpose and let our implementation behave accordingly.
// simplified code
var state = null;
function getCurrentPosition( success, error, options ) {
if( state == 'timeout' )
simulateTimeoutError();
}
# Cucumber step
page.execute_script "state = 'timeout';"
Step 5: Celebrate
Okay, so we've managed to write reasonable integration tests and taken you through the biggest problems we encountered. You can find an example of a fully-working Rails 3 application using the HTML5 Geolocation standard with all the corresponding Cucumber scenarios implemented here.
Posted 23 days back at Luca Guidi - Home
I’m currently working as a consultant for an UN agency (IFAD) and we have a portfolio of ~15 Rails apps, developed in the last four years. The environment is heterogeneous and an half dozen of these projects are interfacing with legacy software and they are legacy themselves. As counterpart, the new apps we are developing are running on the latest bleeding edge technologies (Ruby 1.9.3, Rails 3.2, MongoDB, Redis, WebSockets etc..).
When I joined the team in last September, I had big problems to deal with all this amount of informations and to clone projects from GitHub then make them running on my dev machine. The most common issue is the missing and/or outdated documentation. Developers are lazy people and, in general, they just want to code. Documentation, UI/UX reviews are just an example of what they tend to avoid.
The post-git-clone syndrome became really frustrating for each project I needed to work on, so now I aim to document and create a single Rake task for setup.
Since we have several persistence options, to run all these databases as init.d services would be overkilling for my MacBook. So I went for the all-turned-off-by-default strategy and run only the processes that I actually need for a code session. I’m a big fan of Foreman, and it perfectly fits this need. Plus I don’t have to remind which is the database(s) needed for that specific project or if it needs a queue, everything is ready with just foreman start.
In our team we almost all use Mac (with Homebrew) as setup, but since a Foreman’s Procfile is too much coupled with the current machine is running on, I create a Procfile.example in each project and let my colleagues to customize their own configuration, according their machine, or completely skip it and use their own workflow. Remember, the goal isn’t about unify the development process, but to have the application running in less than 5 minutes, for people who never worked on that project before.
Here a complete and working example:
# lib/tasks/app.rake
namespace :app do
desc 'Setup the application'
task :setup do
require 'fileutils'
# ENVIRONMENT
puts "\n** Configuring servers.\n"
## Foreman
puts "*** Configuring Foreman."
FileUtils.cp Rails.root.join('Procfile.example'),
Rails.root.join('Procfile')
## Pow
puts "*** Configuring Pow."
FileUtils.ln_sf Rails.root, File.expand_path('~/.pow')
FileUtils.touch Rails.root.join('tmp/always_restart.txt')
# DATABASE
## Postgres
puts "\n** Configuring database.\n"
puts "*** Configuring Postgres: your current UNIX username is being used for connection."
FileUtils.cp Rails.root.join('config', 'database.yml.example'),
Rails.root.join('config', 'database.yml')
## Setup
puts "*** Setting up the database."
pids = %w( db ).map do |process|
Kernel.spawn("foreman start #{process}")
end
sleep 4
Thread.new do
begin
Rake::Task['db:setup'].invoke
rescue Exception => e
puts "*** [ ERROR ] failed to load the database: #{e.message}"
end
end.join
pids.each do |pid|
Process.kill('SIGTERM', pid)
end
end
end
Posted 23 days back at Luca Guidi - Home
[ I wrote this post for Redis ToGo, you can find the original article here and the related discussion on Hacker News. ]
Redis Store aims to be a toolkit for your Ruby applications, it natively supports sharding, master/slave replication, marshalling, timeouts and namespaces. Plus, it’s really easy to use with the most popular frameworks, such as Ruby on Rails.
If you love modularity, you will love Redis Store too: under the hood it just activates, at runtime, the best set of low level features requested by the above software layers. It’s delivered as a set of gems, one for each targeted framework, with a common background that’s the redis-store gem itself. This decision helped me a lot to deal with different versions of Ruby, several frameworks, and versions.
How to use it
Let’s say we want to use Redis Store in our Rails project. First of all we need to add an entry in our Gemfile:
gem 'redis-rails'
gem 'redis-rack-cache' # optional
Then we have many options:
## Cache Store
# config/environments/production.rb
config.cache_store = :redis_store
## Session Store
# config/initializers/session_store.rb
MyApplication::Application.config.session_store :redis_store,
servers: ['redis://:secret@192.168.6.23:6379/0', 'redis://:secret@192.168.6.99:6379/1']
## HTTP Cache
# config.ru
require 'rack'
require 'rack/cache'
require 'redis-rack-cache'
use Rack::Cache,
metastore: 'redis://localhost:6379/0/metastore',
entitystore: 'redis://localhost:6380/0/entitystore'
As you can see, it’s pretty easy to plug in, but let’s investigate how to manage our configuration. The first case is self-explanatory, we’re telling ActiveSupport to load our Redis backed store. Remember that, au contraire of Redis, which only supports strings, we can dump full objects here.
The second example is a little bit more complicated. First of all, we are employing a cluster of servers. As mentioned before, Redis Store supports sharding, that means the HTTP sessions will be transparently split across the two hosts. For each node we are specififying, respectively: protocol, password, ip, port and the Redis database.
The last one, instead describes the setup for the Rails recently added Rack::Cache. This is a Ruby implementation of an HTTP cache proxy (like Squid or Varnish), which helps to drastically improve response times, by storing the full contents for a given url. It has two components: the metastore, used mainly to check the existence of an entry, and the entitystore, that’s the repository itself. You’ve probably noticed another parameter in the configuration: it’s the namespace, all the keys will be prefixed with something like <namespace>:<key>. One last note: since we are storing just plain text, the mashalling module isn’t activated.
This is just a small portion of what Redis Store can do, it also supports Rack, Sinatra and I18n out of the box.
Conclusion
I strongly believe that Redis is must-have in your environment, it’s fast, flexible enough to be used as database, cache, pub/sub. That being said, Redis Store can be a great tool for scale your applications, but everything has a cost: fine tuning. Again, it-just-works, but as Rails itself, to step up, you’ll probably find out to experiment a little bit with the Redis configuration, in order to find the right threshold between performances, scalability and memory consumption.
If you want to give Redis store a try, please check it out on GitHub.
Posted 25 days back at Phusion Corporate Blog
Phusion Passenger is software that deploys Ruby and Python web apps, by integrating into Apache and Nginx and turning them into a fully-featured application server. It is very fast, stable and robust and thus used by the likes of New York Times, AirBnB, Symantec, Pixar, etc. It comes with many features that makes your life easier and your application perform better.
Phusion Passenger is under constant maintenance and development. Version 4.0.3 is a bugfix release.
Phusion Passenger also has an Enterprise version which comes with a wide array of additional features. By buying Phusion Passenger Enterprise you will directly sponsor the development of the open source version.
Recent changes
- Better protection is now provided against application processes that
are stuck and refuse to shut down cleanly. Since version 4.0.0,
Phusion Passenger already forcefully shuts down all processes during
web server shutdown. In addition to this, 4.0.3 now also forcefully
shuts down processes that take more than 1 minute to shut down, even
outside the context of web server shutdowns. This feature does not,
however, protect against requests that take too long. Use
PassengerMaxRequestTime (Apache) or passenger_max_request_time (Nginx)
for that.
- Fixed a crash in the HelperAgent which results in frequent process
restarts in some traffic patterns. Fixes issue #862.
- Fixed a problem that prevents processes from being spawned correctly
if the user’s bashrc changes working directory. Fixes issue #851.
- passenger-status now also displays CPU usage.
- The installer now checks for checksums when automatically downloading
PCRE and Nginx. Contributed by Joshua Lund.
- An error is now printed when trying to daemonize Phusion Passenger
Standalone on Ruby implementations that don’t support forking.
Contributed by Benjamin Fleischer.
- Although Phusion Passenger already supported JRuby, installing
Phusion Passenger with JRuby was not possible. This has been fixed.
- Various other minor bug fixes.
Installing 4.0.3
Quick install/upgrade
Phusion Passenger Enterprise users can download the Enterprise version of 4.0.3 from the Customer Area.
Open source users can install the open source version of 4.0.3 with the following commands:
gem install passenger
passenger-install-apache2-module
passenger-install-nginx-module
You can also download the tarball at Google Code. We strongly encourage you to cryptographically verify files after downloading them.
In-depth instructions
In-depth installation and upgrade instructions can be found in the Installation section of the documentation. The documentation covers:
- Detailed tarball installation instructions.
- Detailed upgrade instructions.
- Installation troubleshooting.
- Installation through APT and YUM.
You can view the documentation online here:
Final
If you would like to stay up to date with Phusion news, please fill in your name and email address below and sign up for our newsletter. We won’t spam you, we promise.
Posted 25 days back at Katz Got Your Tongue?
Alex Russell posted some thoughts today about how he wishes the W3C would architect the next version of the Content Security Policy.
I agree with Alex that designing CSP as a “library” that uses other browser primitives would increase its long-term utility and make it compose better with other platform features.
Alex is advocating the use of extensible web principles in the design of this API, and I wholeheartedly support his approach.
Background
You can skip this section if you already understand CSP.
For the uninitiated, Content Security Policy is a feature that allows web sites to opt into stricter security than what the web platform offers by default. For example, it can restrict which domains to execute scripts from, prevent inline scripts from running altogether, and control which domains the network stack is allowed to make HTTP requests to.
To opt into stricter security using the current version of CSP, a website includes a new header (Content-Security-Policy) which can contain a number of directives.
For example, in order to prevent the browser from making any network requests to cross-domain resources, a server can return this header:
Content-Security-Policy: default-src 'self' |
This instructs the browser to restrict all network requests to the current domain. This includes images, stylesheets, and fonts. Essentially, this means that scripts run on your page will be unable to send data to third-party domains, which is a common source of security vulnerabilities.
If you want to allow the browser to make requests to its own domain, plus the Google Ajax CDN, your server can do this:
Content-Security-Policy: default-src 'self' ajax.googleapis.com |
Factoring the Network Layer
If you look at what CSP is doing, it’s essentially a syntax for controlling what the network stack is allowed to do.
There are other parts of the web platform that likewise control the network stack, and more all the time. What you’d like is for all of these features to be defined in terms of some lower-level primitive—ideally, one that was also exposed to JavaScript itself for more fine-grained, programmatic tweaks.
Imagine that you had the ability to intercept network requests programmatically, and decide whether to allow the request to continue. You might have an API something like this:
var origin = window.location.origin;
page.addEventListener('fetch', function(e) {
var url = e.request.url;
if (origin !== url.origin) {
// block the network request
e.preventDefault();
}
// otherwise, allow the network request through
}); |
You would then be able to describe how the browser interprets CSP in terms of this primitive API.
You could even imagine writing a CSP library purely in JavaScript!
page.addEventListener('fetch', function(e) {
if (e.type === 'navigate') {
e.respondWith(networkFetch(url).then(function(response) {
// extract CSP headers and associate them with e.window.id
// this is a pseudo-API to keep the implementation simple
CSP.setup(e.window.id, response);
return response;
});
} else {
if (!CSP.isAllowed(e.window.id, e.request)) {
e.preventDefault();
}
}
}); |
The semantics of CSP itself can be expressed in pure JavaScript, so these primitives are enough to build the entire system ourselves!
I have to confess, I’ve been hiding something from you. There is already a proposal to provide exactly these network layer hooks. It even has exactly the API I showed above.
The Extensible Web
Extensible web principles give us a very simple path forward.
Continue iterating on the declarative form of the Content Security Policy, but describe it in terms of the same primitives that power the Navigation Controller proposal.
When web developers want to tweak or extend the built-in security features, they can write a library that intercepts requests and applies tweaks to the policy by extending the existing header syntax.
If all goes well, those extensions will feed into the next iteration of CSP, giving us a clean way to let platform users inform the next generation of the platform.
This approach also improves the likelihood that other features that involve the network stack will compose well with CSP, since they will also be written in terms of this lower level primitive.
Many of the benefits that Dave Herman outlined in the closing of my last post are brought into concrete terms in this example.
I hope to write more posts that explore how extensible web principles apply to platform APIs, both new and old.
Fellow web developers, let’s persuade Adam Barth, Dan Veditz, Mike West (the CSP specification editors) to factor the next version of CSP in terms of the new Navigation Controller specification.
Then, we will have the tools we need to extend the web’s security model forward.
<script type="text/javascript">
addthis_url = 'http%3A%2F%2Fyehudakatz.com%2F2013%2F05%2F24%2Fan-extensible-approach-to-browser-security-policy%2F';
addthis_title = 'An+Extensible+Approach+to+Browser+Security+Policy';
addthis_pub = '';
</script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12"></script>
Posted 25 days back at Katz Got Your Tongue?
Alex Russell posted some thoughts today about how he wishes the W3C would architect the next version of the Content Security Policy.
I agree with Alex that designing CSP as a “library” that uses other browser primitives would increase its long-term utility and make it compose better with other platform features.
Alex is advocating the use of extensible web principles in the design of this API, and I wholeheartedly support his approach.
Background
You can skip this section if you already understand CSP.
For the uninitiated, Content Security Policy is a feature that allows web sites to opt into stricter security than what the web platform offers by default. For example, it can restrict which domains to execute scripts from, prevent inline scripts from running altogether, and control which domains the network stack is allowed to make HTTP requests to.
To opt into stricter security using the current version of CSP, a website includes a new header (Content-Security-Policy) which can contain a number of directives.
For example, in order to prevent the browser from making any network requests to cross-domain resources, a server can return this header:
Content-Security-Policy: default-src 'self' |
This instructs the browser to restrict all network requests to the current domain. This includes images, stylesheets, and fonts. Essentially, this means that scripts run on your page will be unable to send data to third-party domains, which is a common source of security vulnerabilities.
If you want to allow the browser to make requests to its own domain, plus the Google Ajax CDN, your server can do this:
Content-Security-Policy: default-src 'self' ajax.googleapis.com |
Factoring the Network Layer
If you look at what CSP is doing, it’s essentially a syntax for controlling what the network stack is allowed to do.
There are other parts of the web platform that likewise control the network stack, and more all the time. What you’d like is for all of these features to be defined in terms of some lower-level primitive—ideally, one that was also exposed to JavaScript itself for more fine-grained, programmatic tweaks.
Imagine that you had the ability to intercept network requests programmatically, and decide whether to allow the request to continue. You might have an API something like this:
var origin = window.location.origin;
page.addEventListener('fetch', function(e) {
var url = e.request.url;
if (origin !== url.origin) {
// block the network request
e.preventDefault();
}
// otherwise, allow the network request through
}); |
You would then be able to describe how the browser interprets CSP in terms of this primitive API.
You could even imagine writing a CSP library purely in JavaScript!
page.addEventListener('fetch', function(e) {
if (e.type === 'navigate') {
e.respondWith(networkFetch(url).then(function(response) {
// extract CSP headers and associate them with e.window.id
// this is a pseudo-API to keep the implementation simple
CSP.setup(e.window.id, response);
return response;
});
} else {
if (!CSP.isAllowed(e.window.id, e.request)) {
e.preventDefault();
}
}
}); |
The semantics of CSP itself can be expressed in pure JavaScript, so these primitives are enough to build the entire system ourselves!
I have to confess, I’ve been hiding something from you. There is already a proposal to provide exactly these network layer hooks. It even has exactly the API I showed above.
The Extensible Web
Extensible web principles give us a very simple path forward.
Continue iterating on the declarative form of the Content Security Policy, but describe it in terms of the same primitives that power the Navigation Controller proposal.
When web developers want to tweak or extend the built-in security features, they can write a library that intercepts requests and applies tweaks to the policy by extending the existing header syntax.
If all goes well, those extensions will feed into the next iteration of CSP, giving us a clean way to let platform users inform the next generation of the platform.
This approach also improves the likelihood that other features that involve the network stack will compose well with CSP, since they will also be written in terms of this lower level primitive.
Many of the benefits that Dave Herman outlined in the closing of my last post are brought into concrete terms in this example.
I hope to write more posts that explore how extensible web principles apply to platform APIs, both new and old.
Fellow web developers, let’s persuade Adam Barth, Dan Veditz, Mike West (the CSP specification editors) to factor the next version of CSP in terms of the new Navigation Controller specification.
Then, we will have the tools we need to extend the web’s security model forward.
<script type="text/javascript">
addthis_url = 'http%3A%2F%2Fyehudakatz.com%2F2013%2F05%2F24%2Fan-extensible-approach-to-browser-security-policy%2F';
addthis_title = 'An+Extensible+Approach+to+Browser+Security+Policy';
addthis_pub = '';
</script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12"></script>
Posted 26 days back at Ruby5
An Intervention for ActiveRecord, Using Gems in RubyMtion, GemConfig, using Nested Attributes with BackBone, Lyricfy (sorry - Chris made me sing!), and a shoutout to Josh Kemp in this RubyLoco-Powered episode of Ruby5.
Listen to this episode on Ruby5
This episode is sponsored by New Relic
You should be using NewRelic by now, but you might not be checking out their blog regularly. They feature a constant stream of news relevant to the entire developer community, not just their customer base.
This week their blog features an article about the permutation testing they go on their Ruby Agent, testing it out against various Ruby versions, Rails versions, Sinatra versions, and other popular third-party gems. If you are looking into testing permutations, this is definitely worth a read!
And as always, NewRelic is still awesome and accounts are still free. go get one at newrelic.com
ActiveRecord Intervention
Ernie Miller's talk from RailsConf is up online. If you've been curious about the inner workings of ActiveRecord, here's your brain-food!
MotionBundler
If you're using RubyMotion, you've probably run into the situation where a gem you'd really like to use just isn't includable in your project. MotionBundler solves that with a single line of code. Don't try to use gems with C extensions though...
GemConfig
Gem authors - how do you add configuration options to your gem? Yaml? a little dsl? a Hash exposed into the Global namespace? Well check out GemConfig for a nice reusable solution to this problem.
Backbone Nested Attrs
Vicente Mundim recently blogged about a new gem named backbone-nested-attributes. It provides your backbone models with 1-1 and 1-N relations support, as well as Rails-like nested attributes
Lyricfy
I'm sorry. So very, very sorry.
Josh Kemp
Do horses prefer Nike, Adidas, or Rebok? Josh Kemp can tell you. He can also whip up a few domain models and a little bit of CSS into a custom rails app.
For months, Josh has been learning to become a developer and blogging about his journey, down the material he's working on and the hours he's spent doing it. (He's also the guy that inspired us to talk about RTanque a few months back). A lot of people have taken his journey, but few have done it with such visibility and passion.
He launched his resume site last week and gained a little retweet love from the likes of Corey Haines and Uncle Bob Martin - go watch him pound out a horseshoe - dude has a freakin forge in the back of his car?!?!
Posted 27 days back at GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS - Home
You may have noticed a recent addition to our blog posts. We concluded an experiment to add a “Written by [Author Name]” byline and link the author’s name to their Google+ profile.
Google calls this Authorship. It is a feature that lets you verify that you are the author of some content, such as a blog post. It is kind of like a microformat that Google uses in its search algorithms. It also causes an author’s face to show in Google search results:

We take the following one-time steps to set up Google Authorship for each author on our blog:
- Get a Google+ account.
- Verify our email address for the domain, which will automatically add you as a collaborator of that website on Google+.
Now, whenever we author a post for one of those websites, we take the following steps:
- Add a byline that has a link like
Written by <a rel='author' href='http://plus.google.com/GOOGLE_PLUS_ID'>AUTHOR NAME</a>..
- Link back to the article from our Google+ profile.
The links in both directions are help to confirm authorship of the article.
We can then see statistics on impressions, clicks, click-through rates, and average position in search results for pages for which we are the verified author:

Google Authorship is a nice way for us to better understand how our content appears in Google searches as well as expose our content to a wider audience.
Written by Caleb Thompson.
Posted 28 days back at Nuby on Rails
This article is heavily styled and is best viewed at PeepCode!
The only thing more difficult than learning something new is teaching it.
At PeepCode, we put a lot of time into creating great explanations of difficult concepts. We won’t publish a video until we’re confident that it explains the topic better than anything else out there. And feedback from people who have viewed our videos on Ember.js, Ruby on Rails, JavaScript and other topics show that we’re doing just that.
Summary
Here’s some of what we’ve learned about explaining technical topics to developers.
- Teach one thing at a time
- Tell a story
- Use appropriate terminology
- Know your audience
The Goal
The goal of any tutorial is to get back into the mind of someone who doesn’t understand the topic. If an explanation only makes sense to people who already know what you know, then it’s not a very good explanation.
But that insight alone doesn’t tell you how to explain well. Instead, it might help to think about how developers go wrong when trying to explain a concept.
- They try to teach too many things at once. This overwhelms the student.
- They are disorganized. Teaching things out of order makes the student do too much work to sort it out in their mind.
- They use the wrong words. Throwing an unknown term into an explanation can intimidate a student or even cause fear.
- They don’t know who they are speaking to. I don’t know of any single explanation that works for all people at all levels of learning. When developers are unclear about their audience, they risk delivering ideas that will confuse everyone listening.
Here are four solutions to these problems.
Teach one thing at a time
This is the biggest problem I see, and it’s the first strategy you should use to improve your explanations.
Decide what you’re trying to teach, and only talk about that. You’ll have to intentionally block out the 10 other things you want to communicate. If a concept is important enough, dedicate a separate chapter, slide, or day to it. Then focus on the one thing you’re trying to teach right now.
This is extremely difficult for developers. We love details. We love to debate some tiny nuance of a program before it even runs. We like discovering edge cases that no one else has thought about.
And we’re afraid. We’re afraid that when we conclude a presentation, one person in the audience will be able to say “Hah! You forgot to mention X!” Or “You were wrong on this one point!”
To teach well, you need to get over these fears. You need to allow yourself to say something that’s 99% true, even if you know someone will correct you for the 1%. Because mentioning that 1% in your explanation will probably hinder you from sticking to teaching just one thing at a time.
To teach well, you need to abandon your insurance policy of saying “We’ll cover this other thing later.” That disclaimer is only there to comfort you, not to help the student. Teach the one thing you’re trying to teach now, then teach one other thing later when you’ve finished teaching the one thing you’re teaching now.
In fact, leaving out an important concept or saying something that’s only 99% true can be used to your advantage. It can help you tell a story.
Tell a story with problems and solutions
Stories are great because they hold our attention. The story could go anywhere, but we also have a hunch about what will happen next. That anticipation keeps our interest: “Will it turn out like I think it will, or will something unexpected happen?”
Malcolm Gladwell is a great storyteller. Many of his stories use problems as a way to hold attention and lead to a solution (or continue the cycle with another problem and another solution).
A person figured this thing out. But then they discovered they were partly wrong. And it gave them a new insight into how it really worked. So they applied that knowledge to something else. And then…
When explaining a technical concept, start with a partial explanation that’s easy to understand. In order to make it understandable, you might have to leave out some details. But filling in those details now becomes the next part of your story.
For example:
Solution: Fixtures are Rails’ built-in way for feeding data to your tests. They are a concise way to describe all the data your application needs.
Problem: But fixtures become difficult to maintain when you have many different pieces of data.
Solution: It turns out they aren’t the only way. There are also factories. Here’s how factories work…
Problem: But there’s a problem with factories…
So teach one concept at a time. If you have to leave out a glaring edge case or alternate option, use it to organize your thoughts into problems and solutions that lead from one to the other.
When you’re telling a story, you need to use words. But be careful what words you use…
Beware of Terminology
In every hobby, field of study, or domain, a set of words emerges.
Mountain bikers want to grin while flowing through chunder. Skateboarders are stoked about gnar. Philosophers try not to equivocate about their ideology. Agile developers want to be clean while they keep their objects dry.
These words—big and small—are shortcuts. They make it easy for experts to discuss advanced topics after they already understand the basics.
If you are teaching experts about advanced topics, then you should use these shortcut words.But if you are teaching people who are not experts, then using domain-specific language will confuse them.
For any term, one’s relationship to the word falls under one of these categories:
- I have never heard it before, and have no idea what it means.
- I have heard it a few times but don’t understand it.
- I have a basic understanding of the word.
- I have thorough understanding. It’s part of my vocabulary. I can use it to explain other concepts.
Part of your job as a teacher is to help students add new words to their vocabulary. Finding their place in the list above will help you know which words to teach, and which ones to use.
Know your audience
Finally, understand your audience. I’m mentioning it last, but it should happen first in your preparations.
Are you teaching beginners or experts? Backend programmers or front-end? People with a computer science degree or the self-taught?
This determines what terms you can use. Your professional audience will be frustrated if you spend large amounts of time explaining things they already know. Your beginner audience will be confused if you assume they are fluent in concepts they have never heard about.
This is the first part of your preparations for teaching, but is also the most uncertain. The people who show up for your presentation or consume your material online might not be the audience you prepared it for.
Conclusion
There is a massive need for great explanations on all kinds of topics. Without good explanations, many open source projects will fail. It’s pretty simple: if people don’t know to use your software, they won’t.
So teach one thing at a time that flows from one idea to another with the appropriate words for the intended audience.
And if you think you want to take a crack at explaining a technical topic, contact us. We’re always looking to pay skilled teachers to make videos for us!
Posted 28 days back at Katz Got Your Tongue?
If we want to move the web forward, we must increase our ability as web developers to extend it with new features.
For years, we’ve grabbed the browsers extension points with two hands, not waiting for the browser vendors to gift us with new features. We built selector engines, a better DOM API, cross-domain requests, cross-frame APIs.
When the browser has good extension points (or any extension points, really), we live in a virtuous cycle:
- Web developers build new APIs ourselves, based on use-cases we have
- We compete with each other, refining our libraries to meet use cases we didn’t think of
- The process of competition makes the libraries converge towards each other, focusing the competition on sharp use-case distinctions
- Common primitives emerge, which browser vendors can implement. This improves performance and shrinks the amount of library code necessary.
- Rinse, repeat.
We’ve seen this time and time again. When it works, it brings us querySelectorAll, the template element, and Object.observe.
The Sad Truth
The sad truth is that while some areas of the browser are extremely extensible, other areas are nearly impossible to extend.
Some examples include the behavior and lifecycle of custom element in HTML, the CSS syntax, and the way that the browser loads an HTML document in the first place. This makes it hard to extend HTML, CSS, or build libraries that support interesting offline capabilities.
And even in some places that support extensibility, library developers have to completely rewrite systems that already exist. For example, John Resig had to rewrite the selector engine from scratch just to add a few additional pseudo-properties, and there is still no way add custom pseudo-properties to querySelectorAll.
Declarative vs. Imperative
A lot of people see this as a desire to write everything using low-level JavaScript APIs, forever.
No.
If things are working well, JavaScript library authors write new declarative APIs that the browser can roll in. Nobody wants to write everything using low-level calls to canvas, but we’re happy that canvas lets us express low-level things that we can evolve and refine.
The alternative, that web authors are stuck with only the declarative APIs that standards bodies have invented, is too limiting, and breaks the virtuous cycle that allows web developers to invent and iterate on new high-level features for the browser.
In short, we want to extend the web forward with new high-level APIs, but that means we need extension points we can use.
Explaining the Magic
If we want to let web authors extend the web forward, the best way to do that is to explain existing and new high-level forms in terms of low-level APIs.
A good example of in-progress work along these lines in Web Components, which explains how elements work in terms of APIs that are exposed to JavaScript. This means that if a new custom element becomes popular, it’s a short hop to implementing it natively, because the JavaScript implementation is not a parallel universe; it’s implemented in terms of the same concepts as native elements.
That doesn’t necessarily mean that browsers will simply rubber-stamp popular components, but by giving library authors the the tools to make components with native-like interfaces, it will be easy for vendors to synthesize web developer zeitgeist into something standard.
Another example is offline support. Right now, we have the much-derided AppCache, which is a declarative-only API that makes it possible to display an HTML page, along with its assets, even if the browser is offline.
AppCache is not implemented in terms of a low-level JavaScript API, so when web developers discovered problems with it, we had no way to extend or modify it to meet our needs. This also meant that we had no way to show the browser vendors what kinds of solutions would work for us.
Instead, we ended up with years of stagnation, philosophical disagreements and deadlock between web developers and specification editors, and no way to move forward.
What we need instead is something like Alex Russell’s proposal that allows applications to install JavaScript code in the cache that intercepts HTTP requests from the page and can fulfill them, even when the app is offline. With an API like this, the current AppCache could be written as a library!
Something like Jonas Sicking’s app cache manifest is a great companion proposal, giving us a nice starting point for a high-level API. But this time if the high-level API doesn’t work, we can fix it by using the low-level API to tweak and improve the manifest.
We can extend the web forward.
Extensions != Rewriting
It’s important to note that web developers don’t want a high level API and then a cliff into the low-level API.
Today, while you can implement custom elements or extend the selector engine, you can only do this by rewriting large chunks of the stack alongside the feature you want.
Real extensibility means an architecture that lets you tweak, not rewrite. For example, it would be possible to add custom rules to CSS by writing a full selector engine and application engine, and apply rules via .style as the DOM changes. With mutation observers, this might even be feasible. In fact, this is how some of the most devious hacks in the platform today (like the Polymer Shadow DOM polyfill) actually work.
That kind of “extensibility” doesn’t fit the bill. It doesn’t compose well with other extensions, defeats the browser’s ability to do performance work on unrelated parts of the stack (because the entire stack had to be rewritten), and is too hard to provide meaningful iteration.
Browser implementers are often wary of providing extension points that can be performance footguns. The biggest footgun is using libraries that rewrite the entire stack in JavaScript, and whole-stack-rewriting strategies are the tactic du jour today. For performance, we have little to lose and much to gain by making extensions more granular.
Extend the Web Forward
So what do we gain from a more extensible web? I’ll let Dave Herman, a member of TC39, answer that for me.
- When you design new APIs, you are forced to think about how the existing system can express most of the semantics. This cleanly separates what new power is genuinely needed and what isn’t. This prevents cluttering the semantics with unnecessary new magic
- Avoiding new magic avoids new security surface area
- Avoiding new magic avoids new complexity (and therefore bugs) in implementation
- Avoiding new magic makes more of the new APIs polyfillable
- Being more polyfillable means people can ramp up faster, leading to faster adoption and evolution of the platform
- Avoiding new magic means that optimizations in the engines can focus on the stable core, which affects more of new APIs as they are added. This leads to better performance with less implementation effort
- Avoiding new magic means less developer education required; people can understand new APIs more easily when they come out, because they build off of known concepts
- This means that the underlying platform gets fleshed out to be expressive enough to prototype new ideas. Library authors can experiment with new features and create more cowpaths to fill the Web API pipeline
All this, and more! There’s something for everybody!
Implementors and web developers: let’s work together to extend the web forward!
<script type="text/javascript">
addthis_url = 'http%3A%2F%2Fyehudakatz.com%2F2013%2F05%2F21%2Fextend-the-web-forward%2F';
addthis_title = 'Extend+the+Web+Forward';
addthis_pub = '';
</script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12"></script>
Posted 28 days back at Katz Got Your Tongue?
If we want to move the web forward, we must increase our ability as web developers to extend it with new features.
For years, we’ve grabbed the browsers extension points with two hands, not waiting for the browser vendors to gift us with new features. We built selector engines, a better DOM API, cross-domain requests, cross-frame APIs.
When the browser has good extension points (or any extension points, really), we live in a virtuous cycle:
- Web developers build new APIs ourselves, based on use-cases we have
- We compete with each other, refining our libraries to meet use cases we didn’t think of
- The process of competition makes the libraries converge towards each other, focusing the competition on sharp use-case distinctions
- Common primitives emerge, which browser vendors can implement. This improves performance and shrinks the amount of library code necessary.
- Rinse, repeat.
We’ve seen this time and time again. When it works, it brings us querySelectorAll, the template element, and Object.observe.
The Sad Truth
The sad truth is that while some areas of the browser are extremely extensible, other areas are nearly impossible to extend.
Some examples include the behavior and lifecycle of custom element in HTML, the CSS syntax, and the way that the browser loads an HTML document in the first place. This makes it hard to extend HTML, CSS, or build libraries that support interesting offline capabilities.
And even in some places that support extensibility, library developers have to completely rewrite systems that already exist. For example, John Resig had to rewrite the selector engine from scratch just to add a few additional pseudo-properties, and there is still no way add custom pseudo-properties to querySelectorAll.
Declarative vs. Imperative
A lot of people see this as a desire to write everything using low-level JavaScript APIs, forever.
No.
If things are working well, JavaScript library authors write new declarative APIs that the browser can roll in. Nobody wants to write everything using low-level calls to canvas, but we’re happy that canvas lets us express low-level things that we can evolve and refine.
The alternative, that web authors are stuck with only the declarative APIs that standards bodies have invented, is too limiting, and breaks the virtuous cycle that allows web developers to invent and iterate on new high-level features for the browser.
In short, we want to extend the web forward with new high-level APIs, but that means we need extension points we can use.
Explaining the Magic
If we want to let web authors extend the web forward, the best way to do that is to explain existing and new high-level forms in terms of low-level APIs.
A good example of in-progress work along these lines in Web Components, which explains how elements work in terms of APIs that are exposed to JavaScript. This means that if a new custom element becomes popular, it’s a short hop to implementing it natively, because the JavaScript implementation is not a parallel universe; it’s implemented in terms of the same concepts as native elements.
That doesn’t necessarily mean that browsers will simply rubber-stamp popular components, but by giving library authors the the tools to make components with native-like interfaces, it will be easy for vendors to synthesize web developer zeitgeist into something standard.
Another example is offline support. Right now, we have the much-derided AppCache, which is a declarative-only API that makes it possible to display an HTML page, along with its assets, even if the browser is offline.
AppCache is not implemented in terms of a low-level JavaScript API, so when web developers discovered problems with it, we had no way to extend or modify it to meet our needs. This also meant that we had no way to show the browser vendors what kinds of solutions would work for us.
Instead, we ended up with years of stagnation, philosophical disagreements and deadlock between web developers and specification editors, and no way to move forward.
What we need instead is something like Alex Russell’s proposal that allows applications to install JavaScript code in the cache that intercepts HTTP requests from the page and can fulfill them, even when the app is offline. With an API like this, the current AppCache could be written as a library!
Something like Jonas Sicking’s app cache manifest is a great companion proposal, giving us a nice starting point for a high-level API. But this time if the high-level API doesn’t work, we can fix it by using the low-level API to tweak and improve the manifest.
We can extend the web forward.
Extensions != Rewriting
It’s important to note that web developers don’t want a high level API and then a cliff into the low-level API.
Today, while you can implement custom elements or extend the selector engine, you can only do this by rewriting large chunks of the stack alongside the feature you want.
Real extensibility means an architecture that lets you tweak, not rewrite. For example, it would be possible to add custom rules to CSS by writing a full selector engine and application engine, and apply rules via .style as the DOM changes. With mutation observers, this might even be feasible. In fact, this is how some of the most devious hacks in the platform today (like the Polymer Shadow DOM polyfill) actually work.
That kind of “extensibility” doesn’t fit the bill. It doesn’t compose well with other extensions, defeats the browser’s ability to do performance work on unrelated parts of the stack (because the entire stack had to be rewritten), and is too hard to provide meaningful iteration.
Browser implementers are often wary of providing extension points that can be performance footguns. The biggest footgun is using libraries that rewrite the entire stack in JavaScript, and whole-stack-rewriting strategies are the tactic du jour today. For performance, we have little to lose and much to gain by making extensions more granular.
Extend the Web Forward
So what do we gain from a more extensible web? I’ll let Dave Herman, a member of TC39, answer that for me.
- When you design new APIs, you are forced to think about how the existing system can express most of the semantics. This cleanly separates what new power is genuinely needed and what isn’t. This prevents cluttering the semantics with unnecessary new magic
- Avoiding new magic avoids new security surface area
- Avoiding new magic avoids new complexity (and therefore bugs) in implementation
- Avoiding new magic makes more of the new APIs polyfillable
- Being more polyfillable means people can ramp up faster, leading to faster adoption and evolution of the platform
- Avoiding new magic means that optimizations in the engines can focus on the stable core, which affects more of new APIs as they are added. This leads to better performance with less implementation effort
- Avoiding new magic means less developer education required; people can understand new APIs more easily when they come out, because they build off of known concepts
- This means that the underlying platform gets fleshed out to be expressive enough to prototype new ideas. Library authors can experiment with new features and create more cowpaths to fill the Web API pipeline
All this, and more! There’s something for everybody!
Implementors and web developers: let’s work together to extend the web forward!
<script type="text/javascript">
addthis_url = 'http%3A%2F%2Fyehudakatz.com%2F2013%2F05%2F21%2Fextend-the-web-forward%2F';
addthis_title = 'Extend+the+Web+Forward';
addthis_pub = '';
</script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12"></script>
Posted 28 days back at GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS - Home
If you’re a Ruby developer working with Rails, at some point you’re going to
need to work with JavaScript. While the two languages have many similarities,
the fundamental differences in their object models can be quite jarring.
CoffeeScript helps to provide a more Ruby-like syntax, but if you’re not careful
you can introduce bugs to your code in surprising ways.
Let’s look at an example. Let’s say we have an expensive operation, and need to
cache the result. In CoffeeScript, we might write the this code as:
class GiantRobot
smashCache: {}
smashInto: (other) =>
@smashCache[other] ||= @expensiveCalculations(other)
However, this code leads to a surprising problem when we start smashing things
together.
ralph = new GiantRobot()
voltron = new GiantRobot()
ralph.smashInto(optimusPrime) # => not cached
ralph.smashInto(optimusPrime) # => cached
voltron.smashInto(optimusPrime) # => cached?!
To see why this occurs, we need to take a look at how objects work in
JavaScript. Unlike Ruby, JavaScript has no concept of classes. Instead it
constructs its objects using prototypes. If you’re writing your code in
CoffeeScript, you can almost always ignore this fact, and write your code as if
you were in Ruby or Python. In this case, however, CoffeeScript is making our
problem less apparent, so let’s take a look at what this code looks like using
plain JavaScript.
function GiantRobot() {}
GiantRobot.prototype.smashCache = {};
GiantRobot.prototype.smashInto = function(other) {
if (!this.smashCache[other]) {
this.smashCache[other] = this.expensiveCalculations(other);
}
return this.smashCache[other];
};
Specifically, our problem stems from the fact that setting smashCache on the
prototype may not work the way you’d think.
How prototypes work
When we create ralph with, ralph technically has no smashCache property.
When we do this.smashCache, JavaScript looks for that property on ralph,
followed by ralph’s prototype, then ralph’s prototype’s prototype, and so forth
until it finds something that has the smashCache property.
JavaScript provides us a way to see this in action, using the hasOwnProperty
method.
ralph.hasOwnProperty('smashCache') # => false
GiantRobot.prototype.hasOwnProperty('smashCache') # => true
So when we call this.smashCache, we are always getting back
GiantRobot.prototype.smashCache, which means when we mutate it, we are
mutating the same instance of smashCache that is used by every instance of
GiantRobot. This is only an issue when we’re talking about arrays and objects.
ralph.smashCache = 'some value'
# Variable assignment sets the property directly on the instance
ralph.hasOwnProperty('smashCache') == true
Avoiding mutating the prototype
So how do we get around this? Ironically, the answer is simply to make our
original example look more like our Ruby code.
class GiantRobot
constructor: ->
@smashCache = {}
Now each instance will have it’s own separate smashCache, and all is well with the
world.
Backbone.js gotcha: Mutating the defaults object
A similar problem exists in Backbone.js when using the defaults object on your
models.
class RobotProfile extends Backbone.Model
defaults:
images: []
addImage: (newImage) ->
@get('images').push(newImage) # => Mutates a shared instance
The solution for this problem is even simpler. If we change the defaults
property to be a function that returns the same hash, Backbone will call it
every time a new instance is created.
class RobotProfile extends Backbone.Model
defaults: ->
images: []
Now our images array will no longer be shared across multiple instances, and we
can mutate to our heart’s content.
Written by Sean Griffin
Posted 29 days back at Ruby5
Easier rules for class structure, ProMotion for RubyMotion, JSON APIs in Rails 4, concurrency with Futuroscope, ActiveRecord help via Searchlight, and internationalization with haml-i18n-extractor.
Listen to this episode on Ruby5
This episode is sponsored by Heroku
Build better apps, faster. Spend your time building applications, not managing the servers that run them. Heroku is a Platform as a Service that adds simplicity to deploying, scaling and managing the infrastructure that runs applications. It removes barriers that slow the software development process, freeing you to put 100 percent of your energy into creating quality software.
Sandi Metz's Rules for Developers
Sandi Metz, author of Practical Object-Oriented Design in Ruby, has put together some simple rules of thumb regarding class and method composition. Caleb Thompson wrote up a blog article about them over at the Thoughtbot blog.
ProMotion
To make it even easier to build iOS apps in Ruby, Jamon Holmgren created ProMotion, a RubyMotion framework for abstracting the screen and navigation handling in a Ruby-like way. It makes it easy to work with things like UINavigationControllers, UITabBarControllers, and UIViewControllers.
JSON APIs with Rails 4
Emil Soman wrote up a blog article on how to write a tested, documented and versioned JSON API Using Rails 4.
Futuroscope
Josep Jaume Rey of Codegram wrote in to let us know about Futuroscope. It's their implementation of "futures", which let you easily handle processes in the background. You just wrap your long-running code in a block, and retrieve the result when you need it.
Searchlight
The Searchlight gem, which simplifies complex method chains. It works with ActiveRecord and ActionView out of the box. It also lets you set defaults and offers other shortcuts for interacting with Rails forms.
haml-i18n-extractor
This week Shai Rosenfeld released the haml-i18n-extractor gem, which is a command line tool that looks for certain strings in your haml templates that are likely to be internationalized. It replaces those strings with calls to the translate ("t") method, then it creates the proper yaml locale files for you.
Posted 29 days back at GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS - Home
Episode 49: The psychology of work:
In this week’s episode, recorded at RailsConf 2013, Ben Orenstein is joined by Gregg Pollack and Nathaniel Bibler from EnvyLabs and codeschool.com. Gregg shares what he’s learned running his business, when not to be transparent, how to deal with compensation, and how the EnvyLabs compensation structure has changed over the years. Nathan, Gregg, and Ben also discuss Code School, yearly payments to a subscription, making courses effective, effective marketing, the effectiveness of mailing lists, community events, shared ownership, and much more.