Clearer Conditionals using De Morgan's Laws

Posted 4 months back at GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS - Home

Ever seen a hard-to-parse conditional like this?

def allow_access_to_site?
  ! (signed_out? && untrusted_ip?)
end

Let's use De Morgan's Laws to clean it up and see who actually has access to our site.

De Morgan's Laws

Whoa, who's this De Morgan guy? Augustus De Morgan, in addition to looking like a 19th-century John C. Reilly, formulated two important rules of logical inference. You can check out the formal definition on the Wikipedia page, but here they are in Ruby code:

# One
!(a && b) == !a || !b
# Two
!(a || b) == !a && !b

Well hey, it looks like we can use these on our gnarly conditional above. Let's try it.

Law-abiding Ruby code

Recall that the original conditional was ! (signed_out? && untrusted_ip?). Let's use the second law and puzzle it out.

# Original
! (signed_out? && untrusted_ip?)
# Conversion using second law. I've added parentheses for clarity.
# a = signed_out?
# b = untrusted_ip?
(! signed_out?) || (! untrusted_ip?)

Here I notice that ! signed_out? and ! untrusted_ip? are double negatives: not signed out, not untrusted IP. Now what they're really trying to say is: signed in, trusted IP. Let's simplify further, using better method names.

# Simplify a: (! signed_out?) == signed_in?
(signed_in?) || (! untrusted_ip?)
# Simplify b: !(! untrusted_ip?) == trusted_ip?
(signed_in?) || (trusted_ip?)
# Remove parentheses
signed_in? || trusted_ip?

These methods, signed_in? and trusted_ip?, might exist and they might not. Creating them is part of this refactoring. You might even end up removing the signed_out? and untrusted_ip? methods in favor of these new, positively-named methods.

And that's it. We took a hard-to-parse conditional and made it clearer and easier-to-read using De Morgan's second Law.

Before:

def allow_access_to_site?
  ! (signed_out? && untrusted_ip?)
end

After:

def allow_access_to_site?
  signed_in? || trusted_ip?
end

What's next?

If you found this useful, you might also enjoy:

Clearer Conditionals using De Morgan's Laws

Posted 4 months back at GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS - Home

Ever seen a hard-to-parse conditional like this?

def allow_access_to_site?
  ! (signed_out? && untrusted_ip?)
end

Let's use De Morgan's Laws to clean it up and see who actually has access to our site.

De Morgan's Laws

Whoa, who's this De Morgan guy? Augustus De Morgan, in addition to looking like a 19th-century John C. Reilly, formulated two important rules of logical inference. You can check out the formal definition on the Wikipedia page, but here they are in Ruby code:

# One
!(a && b) == !a || !b
# Two
!(a || b) == !a && !b

Well hey, it looks like we can use these on our gnarly conditional above. Let's try it.

Law-abiding Ruby code

Recall that the original conditional was ! (signed_out? && untrusted_ip?). Let's use the second law and puzzle it out.

# Original
! (signed_out? && untrusted_ip?)
# Conversion using second law. I've added parentheses for clarity.
# a = signed_out?
# b = untrusted_ip?
(! signed_out?) || (! untrusted_ip?)

Here I notice that ! signed_out? and ! untrusted_ip? are double negatives: not signed out, not untrusted IP. Now what they're really trying to say is: signed in, trusted IP. Let's simplify further, using better method names.

# Simplify a: (! signed_out?) == signed_in?
(signed_in?) || (! untrusted_ip?)
# Simplify b: (! untrusted_ip?) == trusted_ip?
(signed_in?) || (trusted_ip?)
# Remove parentheses
signed_in? || trusted_ip?

These methods, signed_in? and trusted_ip?, might exist and they might not. Creating them is part of this refactoring. You might even end up removing the signed_out? and untrusted_ip? methods in favor of these new, positively-named methods.

And that's it. We took a hard-to-parse conditional and made it clearer and easier-to-read using De Morgan's second Law.

Before:

def allow_access_to_site?
  ! (signed_out? && untrusted_ip?)
end

After:

def allow_access_to_site?
  signed_in? || trusted_ip?
end

What's next?

If you found this useful, you might also enjoy:

Episode #427 - December 17th, 2013

Posted 4 months back at Ruby5

rails-assets.org, Rails Database Info, Callbacks Extraction, Shutterbug, A Deeper Look at Ruby’s Enumerable, Prawn 0.13.0

Listen to this episode on Ruby5

This episode is sponsored by Top Ruby Jobs
If you're looking for a top Ruby job or for top Ruby talent, then you should check out Top Ruby Jobs. Top Ruby Jobs is a website dedicated to the best jobs available in the Ruby community.

rails-assets.org
The team at monterail created a gem host that automatically converts packaged bower components into ruby gems.

Rails Database Info
Vlado Cingel sent us a gem over the weekend called Rails database info. This gem adds an html endpoint to your Rails application which will give you a quick display of your database schema and contents for reference.

Callbacks Extraction
Alex Topalov wrote about how to refactor your app away from callbacks to small easy to understand ruby objects. He does this by moving the callbacks out of their domain classes and into a unitary class.

Shutterbug
Shutterbug is a rack service that sends a JavaScript library to the browser, then makes it simple to send HTML fragments back to the server, which can generate images using PhantomJS.

A Deeper Look at Ruby’s Enumerable
This week the ruby love blog gave some love to some helpful enumerable methods that we might tend to forget about. Methods like any?, all?, none? and each_cons.

Prawn 0.13.0
This week the prawn gem got it’s first official release in 2 years. It’s now at version 0.13.0. There’s lots of new features, bug fixes, and breaking changes so be sure to read the change log before attempting to upgrade.

On Happiness

Posted 4 months back at Luca Guidi - Home

The end of the year is the perfect circumstance to look back and spend some time thinking about life, achievements and all the preeminent aspects of life.

As a naive younger man, I have always been disappointed by how many year resolutions have missed in the past. Mostly because they are a failure by design: the wishful self is delighted to dictate the new agenda of change, where all the lazyness, tiredness, and unforeseen accidents will magically disappear to leave room to a bright, joyful and productive future. This will never happen.

What really works is to plan nothing

If you aim to write more, just find the time and do it. Don’t plan, do it. Todo lists were invented to sit and watch us with disapproval, they always generate a sensation of unfulfillment, we are always inadequate and behind the goal. And if we’re still struggling, we probably have chosen the wrong desire. Better admit the failure, turn it down, than blindly follow somebody else’s dream.

Don’t expect anything, be grateful, instead

Be grateful when an achievement is met, be grateful for your life, for your family. Focus on what you already have, not on what you don’t. What is part of your existence right now, is the ground for happiness, the solid foundation to build a blissful future. When something get lost, like an habit, don’t despair, be thankful to have had that thing in your life, if it’s the case, it will came back.

Strive for long term happiness

I admit that daily routine can be overwhelming, sometimes depressing. Shit happens, and it will forever. Life is like that, and for sure, we easily forget moments, but what we keep are memories. Be sure to create them. That’s why I love photography, it’s the perfect incentive to create memories. Be also sure that your memories will be sunny, it’s what really matters when look back in the past and answer to the ultimate question: was my life happy?

Animating Modals in Angular.js

Posted 4 months back at GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS - Home

Modal dialogs are popular in rich client-side applications. When you have them, it's nice to have transitions between them. We could even take it a step further, and have separate transitions for opening/closing the modal, and another transition when we switch between them.

Fancy Directives

This is surprisingly simple to accomplish with Angular, using a handful of directives, and a service to encapsulate what we're currently displaying. We'll start by creating a "modal view" directive, with two options. One will control whether or not we're displaying the modal, and another will control what templateUrl to display.

modalView = ->
  restrict: 'E'

  scope:
    _modalShow: '&modalShow'
    _modalContent: '&modalSrc'

  templateUrl: '/templates/modal_view.html'

app.directive('modalView', modalView)

Our template would look like this:

.modal-backdrop(ng-if="_modalShow()")
.modal-container(ng-if="_modalShow()")
  .modal-window
    .modal-dialog
      .modal-content(ng-include="_modalContent()")

We make use of two directives that Angular provides. ngIf will remove the element from the DOM if its expression evaluates to false. ngInclude replaces its contents with the template at whatever URL its expression evaluates to.

Angular directives are small reusable snippets of HTML with some logic attached to them. Often times they simply exist to compose the built-in directives provided by Angular, which are incredibly powerful. Combined with Angular's bindings, they allow us to manipulate the DOM in large ways simply by changing a variables.

Next, we need a service to encapsulate what we're displaying, and a controller to expose that service to our application.

class Modal
  isOpen: => !!@src

  open: (src) => @src = src

  close: => @src = ''

app.service('Modal', Modal)

class ModalCtrl
  constructor: ($scope, Modal) ->
    $scope.modal = Modal

app.controller('ModalCtrl', ['$scope', 'Modal', ModalCtrl])

Both of these classes are incredibly simple. Our modal service exists to allow us to share one src variable across the application. Now in our layout, we would add the following.

%div(ng-controller="ModalCtrl")
  %modal-view(modal-show="modal.isOpen()" modal-src="modal.src")

Now we can change the modal's content by calling Modal.open('/whatever.html'). If the modal isn't already open, it'll place it on the DOM. If it is open, it'll change the content. Because these happen on different elements, we can apply separate animations depending on which element enters the page.

I'm basically a designer now.

Adding the animations requires the ngAnimate module. Once we've added that to our dependencies, we just need to use a little CSS to make the animations happen. In this example, we're using Sass and Bourbon to eliminate vendor prefixes, and structure things nicely. First, let's fade in the backdrop.

@mixin fade($opacity) {
  opacity: $opacity;

  &.ng-enter, &.ng-leave.ng-leave-active {
    opacity: 0;
  }
}

.modal-backdrop {
  @include fade(0.5);
  @include transition(0.15s linear all);
}

Next, we'll both fade and slide the modal container.

@mixin slide($x, $y) {
  @include transform(translate(0, 0));

  &.ng-enter, &.ng-leave.ng-leave-active {
    @include transform(translate($x, $y));
  }
}

.modal-container {
  @include fade(1);
  @include slide(0, -25%);
  @include transition(0.3s ease-out all);
}

Finally, we'll define a flip animation for changes in the content. This one is a bit more complex than the others.

@mixin flip-hidden {
  @include transform(rotateY(190deg) scale(1));
}

@mixin flip($time) {
  @include backface-visibility(hidden);

  &.ng-enter {
    @include animation($time flipIn);
    @include flip-hidden;
  }

  &.ng-leave {
    @include animation($time flipOut);

    &.ng-leave-active {
      @include flip-hidden;
    }
  }
}

@include keyframes(flipOut) {
  0% {
    @include transform(rotateY(0) scale(1));
    @include animation-timing-function(ease-out);
  }

  80% {
    @include transform(rotateY(170deg) scale(1));
    @include animation-timing-function(ease-out);
  }

  100% {
    @include flip-hidden;
    @include animation-timing-function(ease-in);
  }
}

@include keyframes(flipIn) {
  0% {
    @include flip-hidden;
    @include animation-timing-function(ease-in);
  }

  60% {
    @include transform(rotateY(360deg) scale(0.95));
    @include animation-timing-function(ease-in);
  }

  100% {
    @include transform(rotateY(360deg) scale(1));
    @include animation-timing-function(ease-in);
  }
}

.modal-dialog {
  @include perspective(1000);
  @include transform-style(preserve-3d);
}

.modal-content {
  @include flip(0.6s);
}

We'll skip the styles that actually make the modals into modals. It should be noted that the .modal-content needs to be position: absolute, or they will pop down to the bottom of the screen when the flip occurs (both the old modal and the new modal will be on the DOM at the same time)

And that's all there is to it. The end result is a beautiful transition, and 0 conditionals in our code to determine which one occurs.

modal transitions

Animating Modals in Angular.js

Posted 4 months back at GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS - Home

Modal dialogs are popular in rich client-side applications. When you have them, it's nice to have transitions between them. We could even take it a step further, and have separate transitions for opening/closing the modal, and another transition when we switch between them.

Fancy Directives

This is surprisingly simple to accomplish with Angular, using a handful of directives, and a service to encapsulate what we're currently displaying. We'll start by creating a "modal view" directive, with two options. One will control whether or not we're displaying the modal, and another will control what templateUrl to display.

modalView = ->
  restrict: 'E'

  scope:
    _modalShow: '&modalShow'
    _modalContent: '&modalSrc'

  templateUrl: '/templates/modal_view.html'

app.directive('modalView', modalView)

Our template would look like this:

.modal-backdrop(ng-if="_modalShow()")
.modal-container(ng-if="_modalShow()")
  .modal-window
    .modal-dialog
      .modal-content(ng-include="_modalContent()")

We make use of two directives that Angular provides. ngIf will remove the element from the DOM if its expression evaluates to false. ngInclude replaces its contents with the template at whatever URL its expression evaluates to.

Angular directives are small reusable snippets of HTML with some logic attached to them. Often times they simply exist to compose the built-in directives provided by Angular, which are incredibly powerful. Combined with Angular's bindings, they allow us to manipulate the DOM in large ways simply by changing a variables.

Next, we need a service to encapsulate what we're displaying, and a controller to expose that service to our application.

class Modal
  isOpen: => !!@src

  open: (src) => @src = src

  close: => @src = ''

app.service('Modal', Modal)

class ModalCtrl
  constructor: ($scope, Modal) ->
    $scope.modal = Modal

app.controller('ModalCtrl', ['$scope', 'Modal', ModalCtrl])

Both of these classes are incredibly simple. Our modal service exists to allow us to share one src variable across the application. Now in our layout, we would add the following.

%div(ng-controller="ModalCtrl")
  %modal-view(modal-show="modal.isOpen()" modal-src="modal.src")

Now we can change the modal's content by calling Modal.open('/whatever.html'). If the modal isn't already open, it'll place it on the DOM. If it is open, it'll change the content. Because these happen on different elements, we can apply separate animations depending on which element enters the page.

I'm basically a designer now.

Adding the animations requires the ngAnimate module. Once we've added that to our dependencies, we just need to use a little CSS to make the animations happen. In this example, we're using Sass and Bourbon to eliminate vendor prefixes, and structure things nicely. First, let's fade in the backdrop.

@mixin fade($opacity) {
  opacity: $opacity;

  &.ng-enter, &.ng-leave.ng-leave-active {
    opacity: 0;
  }
}

.modal-backdrop {
  @include fade(0.5);
  @include transition(0.15s linear all);
}

Next, we'll both fade and slide the modal container.

@mixin slide($x, $y) {
  @include transform(translate(0, 0));

  &.ng-enter, &.ng-leave.ng-leave-active {
    @include transform(translate($x, $y));
  }
}

.modal-container {
  @include fade(1);
  @include slide(0, -25%);
  @include transition(0.3s ease-out all);
}

Finally, we'll define a flip animation for changes in the content. This one is a bit more complex than the others.

@mixin flip-hidden {
  @include transform(rotateY(190deg) scale(1));
}

@mixin flip($time) {
  @include backface-visibility(hidden);

  &.ng-enter {
    @include animation($time flipIn);
    @include flip-hidden;
  }

  &.ng-leave {
    @include animation($time flipOut);

    &.ng-leave-active {
      @include flip-hidden;
    }
  }
}

@include keyframes(flipOut) {
  0% {
    @include transform(rotateY(0) scale(1));
    @include animation-timing-function(ease-out);
  }

  80% {
    @include transform(rotateY(170deg) scale(1));
    @include animation-timing-function(ease-out);
  }

  100% {
    @include flip-hidden;
    @include animation-timing-function(ease-in);
  }
}

@include keyframes(flipIn) {
  0% {
    @include flip-hidden;
    @include animation-timing-function(ease-in);
  }

  60% {
    @include transform(rotateY(360deg) scale(0.95));
    @include animation-timing-function(ease-in);
  }

  100% {
    @include transform(rotateY(360deg) scale(1));
    @include animation-timing-function(ease-in);
  }
}

.modal-dialog {
  @include perspective(1000);
  @include transform-style(preserve-3d);
}

.modal-content {
  @include flip(0.6s);
}

We'll skip the styles that actually make the modals into modals. It should be noted that the .modal-content needs to be position: absolute, or they will pop down to the bottom of the screen when the flip occurs (both the old modal and the new modal will be on the DOM at the same time)

And that's all there is to it. The end result is a beautiful transition, and 0 conditionals in our code to determine which one occurs.

modal transitions

Optimizing NGINX TLS Time To First Byte (TTTFB)

Posted 4 months back at igvita.com

Network latency is one of our primary performance bottlenecks on the web. In the worst case, new navigation requires a DNS lookup, TCP handshake, two roundtrips to negotiate the TLS tunnel, and finally a minimum of another roundtrip for the actual HTTP request and response — that's five network roundtrips to get the first few bytes of the HTML document!

Modern browsers try very hard to anticipate and predict user activity to hide some of this latency, but speculative optimization is not a panacea: sometimes the browser doesn't have enough information, at other times it might guess wrong. This is why optimizing Time To First Byte (TTFB), and TLS TTFB in particular due to the extra roundtrips, is critical for delivering a consistent and optimized web experience.

The why and the how of TTFB

According to the HTTP Archive, the size of the HTML document at 75th percentile is ~20KB+, which means that a new TCP connection will incur multiple roundtrips (due to slow-start) to download this file - with IW4, a 20KB file will take 3 extra roundtrips, and upgrading to IW10 will reduce that to 2 extra roundtrips.

To minimize the impact of the extra roundtrips all modern browsers tokenize and parse received HTML incrementally and without waiting for the full file to arrive. Stream processing enables the browser to discover other critical resources, such as references to CSS stylesheets, JavaScript, and other assets as quickly as possible and initiate those requests while waiting for the remainder of the document. As a result, optimizing your TTFB and the content of those first bytes can make a big difference to performance of your application:

  • Don't buffer the entire response on the server. If you have partial content (e.g. page header), then flush it as early as possible to get the browser working on your behalf.
  • Optimize the contents of the first bytes by including references to other critical assets as early as possible.

Measuring "out of the box" NGINX TLS TTFB

With the theory of TTFB out of the way, let's now turn to the practical matter of picking and tuning the server to deliver the best results. One would hope that the default “out of the box” experience for most servers would do a good job… unfortunately, that is not the case. Let's take a closer look nginx:

  • Fresh Ubuntu server in ec2-west (micro instance) with nginx v1.4.4 (stable).
  • The server is configured to serve a single 20KB (compressed) file.
  • The TLS certificate is ~5KB and is using a 2048-bit key.
  • The measurements are done with WebPageTest: 3G profile (300ms delay), Chrome (stable channel), Dulles location (~80ms actual RTT to the EC2 instance on the west coast).

The total client to server roundtrip time is ~380ms. As a result, we would expect a regular HTTP connection to yield a TTFB of ~1140ms: 380ms for DNS, 380ms for TCP handshake, and 380ms for the HTTP request and (instant) response. For HTTPS, we would add another two RTTs to negotiate all the required parameters: 1140ms + 760ms, or ~1900ms (5 RTTs) in total. Well, that's the theory, let's now try the theory in practice!

The HTTP TTFB is right on the mark (~1100ms), but what in the world is going on with HTTPS? The TTFB reported by WebPageTest shows ~2900ms, which is an entire extra second over our expected value! Is it the cost of the RSA handshake and symmetric crypto? Nope. Running openssl benchmarks on the server shows that it takes ~2.5ms for a 2048-bit handshake, and we can stream ~100MB/s through aes-256. It's time to dig deeper.

Fixing the “large” certificate bug in nginx

Looking at the tcpdump of our HTTPS session we see the ClientHello record followed by ServerHello response ~380ms later. So far so good, but then something peculiar happens: the server sends ~4KB of its certificate and pauses to wait for an ACK from the client - huh? The server is using a recent Linux kernel (3.11) and is configured by default with IW10, which allows it to send up to 10KB, what's going on?

After digging through the nginx source code, one stumbles onto this gem. Turns out, any nginx version prior to 1.5.6 has this issue: certificates over 4KB in size incur an extra roundtrip, turning a two roundtrip handshake into a three roundtrip affair - yikes. Worse, in this particular case we trigger another unfortunate edge case in Windows TCP stack: the client ACKs the first few packets from the server, but then waits ~200ms before it triggers a delayed ACK for the last segment. In total, that results in extra 580ms of latency that we did not expect.

Ok, let's try the current mainline nginx release (1.5.7) and see if we fare any better...

Much better! After a simple upgrade the TLS TTFB is down to ~2300ms, which is about 600ms lower than our first attempt: we've just eliminated the extra RTT incurred by nginx and the ~200ms delayed ACK on the client. That said, we are not out of the woods yet — there is still an extra RTT in there.

Optimizing the TLS record size

TLS record size can have a significant impact on the page load time performance of your application. In this case, we run into this issue head first: nginx pumps data to the TLS layer, which in turn creates a 16KB record and then passes it to the TCP stack. So far so good, except that the server congestion window is less than 16KB for our new connection and we overflow the window, incurring an extra roundtrip while the data is buffered on the client. Fixing this requires making a quick patch to the nginx source:

diff nginx-1.5.7/src/event/ngx_event_openssl.c nginx-1.5.7-mtu/src/event/ngx_event_openssl.c
570c570
<               (void) BIO_set_write_buffer_size(wbio, NGX_SSL_BUFSIZE);
---
>               (void) BIO_set_write_buffer_size(wbio, 16384);
diff nginx-1.5.7/src/event/ngx_event_openssl.h nginx-1.5.7-mtu/src/event/ngx_event_openssl.h
107c107
< #define NGX_SSL_BUFSIZE  16384
---
> #define NGX_SSL_BUFSIZE  1400

After applying our two-line change and rebuilding the server our TTFB is down to ~1900ms — that's the 5 RTTs we expected at the start. In fact, it's easy to spot the difference from our previous run: the waterfall now shows the second RTT as content download time (blue section), whereas previously the browser couldn't process the HTML document until the very end. Success! But wait, what if I told you that we could do even better?

Enabling TLS False Start

TLS False Start allows us to eliminate an extra roundtrip of latency within the TLS handshake: the client can send its encrypted application data (i.e. HTTP request) immediately after it has sent its ChangeCipherSpec and Finished records, without waiting for the server to confirm its settings. So, how do we enable TLS False Start?

  • Chrome will use TLS False Start if it detects that the server supports NPN negotiation — NPN is an independent feature, but the presence of NPN support is used to guard against broken implementations.
  • Firefox toggled TLS False Start support multiple times, but it will be (re)enabled in M28, and will also require an NPN advertisement and support for forward secrecy.
  • IE10+ uses a combination of blacklist and a timeout and doesn't require any additional TLS features.
  • Apple landed TLS False Start support in OSX 10.9, which hopefully means that its coming to Safari.

In short, we need to enable NPN on the server, which in practice means that we need to rebuild nginx against OpenSSL 1.0.1a or higher — nothing more, nothing less. Let's do just that and see what happens...

We started with a ~1800ms overhead for our TLS connection (nearly 5 extra RTTs); eliminated the extra certificate roundtrip after a nginx upgrade; cut another RTT by forcing a smaller record size; dropped an extra RTT from the TLS handshake thanks to TLS False Start. With all said and done, our TTTFB is down to ~1560ms, which is exactly one roundtrip higher than a regular HTTP connection. Now we're talking!

Yes, TLS does add latency and processing overhead. That said, TLS is an unoptimized frontier and we can mitigate many of its costs - it's worth it. Our quick exploration with nginx is a case in point, and most other TLS servers have all the same issues we've outlined above. Let's get this fixed. TLS is not slow, it's unoptimized.

Episode #426 - December 13th, 2013

Posted 4 months back at Ruby5

thoughtbot open source issues now on Stack Overflow, verifying doubles in RSpec 3, interactive mockups with Stagehand, bundler is stayin' alive (for the time being), and updates to the roar gem all in this episode of the Ruby5!

Listen to this episode on Ruby5

This episode is sponsored by New Relic
New Relic is _the_ all-in-one web performance analytics product. It lets you manage and monitor web application performance, from the browser down to the line of code. With Real User Monitoring, New Relic users can see browser response times by geographical location of the user, or by browser type.

thoughtbot on Stack Overflow
thoughtbot is moving away from mailing lists and towards Stack Overflow posts instead. Check out their blog post explaining why.

New in RSpec 3: Verifying Doubles
Add a little dose of reality to your RSpec doubles.

Stagehand
Easily make interactive mockups with the Stagehand library.

Bundler Not Dead Yet
The rumors of Bundler's death have been greatly exaggerated.

roar
The roar just has received some love lately, including a brand-new and very well-written README.

Phusion Passenger 4.0.29 released

Posted 4 months back at Phusion Corporate Blog

Phusion Passenger is a fast and robust web server and application server for Ruby, Python, Node.js and Meteor. Passenger takes a lot of complexity out of deploying web apps, and adds powerful enterprise-grade features that are useful in production. High-profile companies such as Apple, New York Times, AirBnB, Juniper, American Express, etc are already using it, as well as over 350.000 websites.

Phusion Passenger is under constant maintenance and development. Version 4.0.29 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

4.0.28 has been skipped because a compilation problem on OS X Mavericks as discovered shortly after uploading the tarball. The changes in 4.0.28 and 4.0.29 combined are as follows:

  • Introduced a workaround for a GCC 4.6 bug. This bug could cause Phusion Passsenger to crash during startup. Affected operating systems include Ubuntu 12.04 and Amazon Linux 2013.09.01, though not every machine with this OS installed exhibits the problem. See issue #902.
  • Improved Node.js support: the Sails framework is now supported.
  • Improved Node.js support: the streams2 API is now supported.
  • Introduced support for hooks, allowing users to easily extend Phusion Passenger’s behavior.
  • Fixed a bug in the `passenger start -R` option. It was broken because of a change introduced in 4.0.25.
  • Fixed a bug in PassengerMaxInstancesPerApp. Fixes issue #1016.
  • Fixed compilation problems on Solaris.
  • Fixed compilation problems on OS X Mavericks.
  • Fixed an encoding problem in the Apache autodetection code. Fixes issue #1026.
  • The Debian packages no longer depend on libruby.
  • Application stdout and stderr are now printed without normal Phusion Passenger debugging information, making them easier to read.

Installing or upgrading to 4.0.29

OS X OS X Debian Debian Ubuntu Ubuntu
Heroku Heroku Ruby gem Ruby gem Tarball Tarball

Final

Fork us on Github!

Phusion Passenger’s core is open source. Please fork or watch us on Github. :)

<iframe src="http://ghbtns.com/github-btn.html?user=phusion&amp;repo=passenger&amp;type=watch&amp;size=large&amp;count=true" allowtransparency="true" frameborder="0" scrolling="0" width="170" height="30"></iframe><iframe src="http://ghbtns.com/github-btn.html?user=phusion&amp;repo=passenger&amp;type=fork&amp;size=large&amp;count=true" allowtransparency="true" frameborder="0" scrolling="0" width="170" height="30"></iframe><iframe src="http://ghbtns.com/github-btn.html?user=phusion&amp;type=follow&amp;size=large&amp;count=true" allowtransparency="true" frameborder="0" scrolling="0" width="190" height="30"></iframe>

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.



Capybara Webkit 1.1.0: Screenshots and Better ClickFailed Debugging

Posted 4 months back at GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS - Home

Capybara Webkit 1.1.0 has been released and it contains some great new features like screenshots and better ClickFailed debugging.

ClickFailed

You're writing a nice little Capybara spec, and you innocently try to click on something using Capybara that you can see plainly in your browser:

click_on 'Sign Up'

You're SURE this should work, but Capybara gets sassy:

Failed to click element /html/body/div[1]/button[2] (Capybara::Webkit::ClickFailed)

PC Load Letter

Introducing Capybara Webkit 1.1.0: ClickSuccess edition

These ClickFailed errors are pretty frustrating, and unfortunately there's no easy fix. These errors occur when your Capybara driver tries to click on an element, but it can't find the element or finds a different element where it expects the target element to be.

Although we haven't come up with a definitive fix for these issues, Capybara Webkit includes several changes that will help you to work through them. Let's run through the above scenario again, this time using the latest release of Capybara Webkit.

First, you attempt to click on the element:

click_on 'Sign Up'

You'll still get a ClickFailed error, but this time the error message is much more helpful:

Failed to click element /html/body/div[1]/button[2] because of overlapping
element /html/body/div[@id='myModal']/div/div/div[2] at position 191, 121;
(Capybara::Webkit::ClickFailed)

Hey now, that's interesting! There's some div tag with an ID of myModal where you expect your button to be? That's something you can work with.

But wait! There's more!

Screenshots

You'll also see a line like this:

A screenshot of the page at the time of the failure has been written to
/var/folders/5c/h1zzj9wx70n4y1qcvnzy2h8h0000gn/T/click_failed_C10849.png

If you pop open this file, you'll get to clearly see what Capybara Webkit did when you were trying to click on that button:

ClickFailed

There's even a beautiful mouse cursor illustrating the exact location you attempted to click.

Updating

If you're using Capybara Webkit 1.0.0, you can update easily.

Edit your Gemfile:

gem 'capybara-webkit', '~> 1.1.0'

Update your bundle:

% bundle update capybara-webkit

And you're good to go!

We also included a handful of other bugfixes and improvements in this release.

Props go out to Austen Ito, Jon Rowe, Kazuhiro Nishiyama, Kirill Nikitin, Kohei Suzuki, and Matthew Horan for helping out with this release.

Capybara Webkit 1.1.0: Screenshots and Better ClickFailed Debugging

Posted 4 months back at GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS - Home

Capybara Webkit 1.1.0 has been released and it contains some great new features like screenshots and better ClickFailed debugging.

ClickFailed

You're writing a nice little Capybara spec, and you innocently try to click on something using Capybara that you can see plainly in your browser:

click_on 'Sign Up'

You're SURE this should work, but Capybara gets sassy:

Failed to click element /html/body/div[1]/button[2] (Capybara::Webkit::ClickFailed)

PC Load Letter

Introducing Capybara Webkit 1.1.0: ClickSuccess edition

These ClickFailed errors are pretty frustrating, and unfortunately there's no easy fix. These errors occur when your Capybara driver tries to click on an element, but it can't find the element or finds a different element where it expects the target element to be.

Although we haven't come up with a definitive fix for these issues, Capybara Webkit includes several changes that will help you to work through them. Let's run through the above scenario again, this time using the latest release of Capybara Webkit.

First, you attempt to click on the element:

click_on 'Sign Up'

You'll still get a ClickFailed error, but this time the error message is much more helpful:

Failed to click element /html/body/div[1]/button[2] because of overlapping
element /html/body/div[@id='myModal']/div/div/div[2] at position 191, 121;
(Capybara::Webkit::ClickFailed)

Hey now, that's interesting! There's some div tag with an ID of myModal where you expect your button to be? That's something you can work with.

But wait! There's more!

Screenshots

You'll also see a line like this:

A screenshot of the page at the time of the failure has been written to
/var/folders/5c/h1zzj9wx70n4y1qcvnzy2h8h0000gn/T/click_failed_C10849.png

If you pop open this file, you'll get to clearly see what Capybara Webkit did when you were trying to click on that button:

ClickFailed

There's even a beautiful mouse cursor illustrating the exact location you attempted to click.

Updating

If you're using Capybara Webkit 1.0.0, you can update easily.

Edit your Gemfile:

gem 'capybara-webkit', '~> 1.1.0'

Update your bundle:

% bundle update capybara-webkit

And you're good to go!

We also included a handful of other bugfixes and improvements in this release.

Props go out to Austen Ito, Jon Rowe, Kazuhiro Nishiyama, Kirill Nikitin, Kohei Suzuki, and Matthew Horan for helping out with this release.

Using JavaScript Promises to Reason About User Interaction

Posted 4 months back at GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS - Home

In functional programming, we rarely worry about concurrency primitives like threads. Instead, we use abstractions to make our code easier to reason about. In JavaScript, a Promise is the most common abstraction we encounter. It is usually associated with an Ajax request. We often use abstractions to reason about our concurrent code, but those abstractions can apply in other situations, as well. High level user interactions are essentially large asynchronous events, and can be represented as such in code.

Example: A video storefront

Let's take a look at an example. We're working on a video store front. The user can buy videos, and play videos that they own. If they aren't signed in, they need to sign in to buy a video, and we'd like to use modal dialogs for the sign in and purchasing process.

In order to determine if a user already owns the content, we need them to be signed in. It's also possible that upon signing in, they could already own the content they tried to purchase. This can quickly lead to an extremely complex set of conditionals, but we can simplify it by thinking about the problem like we would think about concurrency.

Making promises about user interactions

Any time we're dealing with user interaction, it is inherently asynchronous. In most code, this begins and ends with event handlers on individual DOM elements. This can be better abstracted if we think about the larger interactions a user can take, and represent that as a single asynchronous operation in the code.

A user may or may not be signed in. We could expose that, and let that conditional bubble throughout our code. However, most of the time, if a user isn't signed in, we're just going to prompt them to sign in. That means that rather than having a user who may or may not be signed in, we've always got a user that will be signed in at some point in the future. Let's look at how we might represent this in code:

class UserSession
  constructor: (@Q, @AuthModals, @Session) ->
    @_session = @Session.get()

  signIn: ->
    @_authDeferred = @Q.defer()
    @_resolveOrPrompt()
    @_authDeferred.promise

  completeSignIn: (data) ->
    @Session.save(data).then(@_completeAuth)

  _resolveOrPrompt: ->
    if @_session?.signedIn
      @_completeAuth(@_session)
    else
      @AuthModals.openSignIn()

  _completeAuth: (session) ->
    @_session = session
    @_authDeferred.resolve(session.user)

There's a lot going on here. Q is Kris Kowal's Q library for working with promises. We'll gloss over the implementation of AuthModals, and Session. We'll just assume that AuthModals opens the modal dialog, and something will call completeSignIn when the form is submitted. Session does two things. It asks the server if we're already signed in, and will submit the Ajax request to the server, and return a promise with the session object.

When code calls the signIn method, we're returning a promise that will eventually be resolved with the current user. If they're already signed in, we resolve that promise immediately. Otherwise, we open the modal dialog for the user to sign in, and resolve the promise once the form is submitted.

Good patterns are made to be built upon

This is incredibly powerful. We've completely removed the need for code to worry about whether or not the user is signed in for almost all cases. We can build upon this further by applying the same concept to purchases.

class UserPurchases
  constructor: (@Q, @UserSession, @PurchaseModals) ->

  purchase: (@video) =>
    @UserSession.signIn().then(@_promisePurchase(video))

  completePurchase: (license)
    @user.addLicense(@video, license)
    @_purchaseDeferred.resolve(license)

  _promisePurchase: (video) => (@user) =>
    @_purchaseDeferred = @Q.defer()
    @_resolveOrPrompt(video)
    @_purchaseDeferred.promise

  _resolveOrPrompt: (video) =>
    if @user.owns(video)
      @completePurchase(@user.licenseFor(video))
    else
      @PurchaseModals.openSaleForm(video)

We apply the same pattern here. If a user already owns the video, we resolve the promise with the license immediately. If not, we prompt the user to buy it, and resolve it when the license is given to us later. A user can only buy one thing at a time. If the user closes the modal and tries to buy something else, the old promise is effectively thrown away.

Finally, we can hide all of this away inside of an object responsible for playing the video.

class VideoPlayer
  constructor: (@UserPurchases, @PlayerModal, @Video) ->

  play: (video) =>
    @UserPurchases.purchase(video).then(@_loadAndPlay(video))

  _loadAndPlay: (video) => (license) =>
    @Video.load(video, license).then(@PlayerModal.openPlayer)

With this in place, code that wants to play a video needs only to call VideoPlayer.play. It doesn't need to concern itself with whether or not the user is signed in, or whether they already own the content. We would still need to have a conditional inside of the template to decide whether the button should say 'Buy' or 'Play'. However, if we use the Null Object pattern, and give the template a Guest when the user isn't signed in, this still remains relatively simple.

By thinking about higher level user interactions the same way we would think about a larger asynchronous computation, we've avoided littering our code with ugly conditionals, and are able to isolate concerns like login and purchasing content to a single place. Testing each of these objects individually also becomes much easier than having to deal with the four cases in one place.

These kinds of situations are everywhere if you look for them. You just have to remember that asynchronicity isn't just for concurrency, and promises aren't just for XHR.

What's next?

If you found this useful, you might also enjoy:

Using JavaScript Promises to Reason About User Interaction

Posted 4 months back at GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS - Home

In functional programming, we rarely worry about concurrency primitives like threads. Instead, we use abstractions to make our code easier to reason about. In JavaScript, a Promise is the most common abstraction we encounter. It is usually associated with an Ajax request. We often use abstractions to reason about our concurrent code, but those abstractions can apply in other situations, as well. High level user interactions are essentially large asynchronous events, and can be represented as such in code.

Example: A video storefront

Let's take a look at an example. We're working on a video store front. The user can buy videos, and play videos that they own. If they aren't signed in, they need to sign in to buy a video, and we'd like to use modal dialogs for the sign in and purchasing process.

In order to determine if a user already owns the content, we need them to be signed in. It's also possible that upon signing in, they could already own the content they tried to purchase. This can quickly lead to an extremely complex set of conditionals, but we can simplify it by thinking about the problem like we would think about concurrency.

Making promises about user interactions

Any time we're dealing with user interaction, it is inherently asynchronous. In most code, this begins and ends with event handlers on individual DOM elements. This can be better abstracted if we think about the larger interactions a user can take, and represent that as a single asynchronous operation in the code.

A user may or may not be signed in. We could expose that, and let that conditional bubble throughout our code. However, most of the time, if a user isn't signed in, we're just going to prompt them to sign in. That means that rather than having a user who may or may not be signed in, we've always got a user that will be signed in at some point in the future. Let's look at how we might represent this in code:

class UserSession
  constructor: (@Q, @AuthModals, @Session) ->
    @_session = @Session.get()

  signIn: ->
    @_authDeferred = @Q.defer()
    @_resolveOrPrompt()
    @_authDeferred.promise

  completeSignIn: (data) ->
    @Session.save(data).then(@_completeAuth)

  _resolveOrPrompt: ->
    if @_session?.signedIn
      @_completeAuth(@_session)
    else
      @AuthModals.openSignIn()

  _completeAuth: (session) ->
    @_session = session
    @_authDeferred.resolve(session.user)

There's a lot going on here. Q is Kris Kowal's Q library for working with promises. We'll gloss over the implementation of AuthModals, and Session. We'll just assume that AuthModals opens the modal dialog, and something will call completeSignIn when the form is submitted. Session does two things. It asks the server if we're already signed in, and will submit the Ajax request to the server, and return a promise with the session object.

When code calls the signIn method, we're returning a promise that will eventually be resolved with the current user. If they're already signed in, we resolve that promise immediately. Otherwise, we open the modal dialog for the user to sign in, and resolve the promise once the form is submitted.

Good patterns are made to be built upon

This is incredibly powerful. We've completely removed the need for code to worry about whether or not the user is signed in for almost all cases. We can build upon this further by applying the same concept to purchases.

class UserPurchases
  constructor: (@Q, @UserSession, @PurchaseModals) ->

  purchase: (@video) =>
    @UserSession.signIn().then(@_promisePurchase(video))

  completePurchase: (license)
    @user.addLicense(@video, license)
    @_purchaseDeferred.resolve(license)

  _promisePurchase: (video) => (@user) =>
    @_purchaseDeferred = @Q.defer()
    @_resolveOrPrompt(video)
    @_purchaseDeferred.promise

  _resolveOrPrompt: (video) =>
    if @user.owns(video)
      @completePurchase(@user.licenseFor(video))
    else
      @PurchaseModals.openSaleForm(video)

We apply the same pattern here. If a user already owns the video, we resolve the promise with the license immediately. If not, we prompt the user to buy it, and resolve it when the license is given to us later. A user can only buy one thing at a time. If the user closes the modal and tries to buy something else, the old promise is effectively thrown away.

Finally, we can hide all of this away inside of an object responsible for playing the video.

class VideoPlayer
  constructor: (@UserPurchases, @PlayerModal, @Video) ->

  play: (video) =>
    @UserPurchases.purchase(video).then(@_loadAndPlay(video))

  _loadAndPlay: (video) => (license) =>
    @Video.load(video, license).then(@PlayerModal.openPlayer)

With this in place, code that wants to play a video needs only to call VideoPlayer.play. It doesn't need to concern itself with whether or not the user is signed in, or whether they already own the content. We would still need to have a conditional inside of the template to decide whether the button should say 'Buy' or 'Play'. However, if we use the Null Object pattern, and give the template a Guest when the user isn't signed in, this still remains relatively simple.

By thinking about higher level user interactions the same way we would think about a larger asynchronous computation, we've avoided littering our code with ugly conditionals, and are able to isolate concerns like login and purchasing content to a single place. Testing each of these objects individually also becomes much easier than having to deal with the four cases in one place.

These kinds of situations are everywhere if you look for them. You just have to remember that asynchronicity isn't just for concurrency, and promises aren't just for XHR.

What's next?

If you found this useful, you might also enjoy:

How to Use Notification for Best Results

Posted 4 months back at entp hoth blog - Home

When creating a new profile in Tender, the email preferences default to notifying the user of changes in the issues/discussions they have participated in (either by creating or commenting on), but you can curate your notifications for any given category or (if support staff) queue that you’d like.

Just go to Edit Your Profile and scroll mid-page where you’ll find Email Preferences. Select as you see fit and Update Permissions.

image

*Tender Tip: Choose your notifications wisely, young Jedi. If you get click happy, you may find your inbox quickly becomes inundated with things you don’t really want to know about.

Here’s more on Notifications in our Knowledge Base article.

Episode #425 - December 10th, 2013

Posted 5 months back at Ruby5

ActionParameter, Purgatory, Promise.rb, Sharing Rails sessions, JRuby 1.7.9

Listen to this episode on Ruby5

This episode is sponsored by Top Ruby Jobs
If you're looking for a top Ruby job or for top Ruby talent, then you should check out Top Ruby Jobs. Top Ruby Jobs is a website dedicated to the best jobs available in the Ruby community.

ActionParameter v0.0.2
Ezequiel Delpero released a new version of ActionParameter. The gem helps you move all your parameter's logic from controllers into it's own class. This way you'll keep your controllers dry and they'll be easier to test.

Purgatory
Purgatory is a Rails gem that allows you to save changes to an ActiveRecord model so that they can be applied at a later time.

Promise.rb
Promise.rb is a Ruby implementation of the Promises/A+ spec.

Sharing Rails Sessions With Non-Ruby Apps
Matt Aimonetti wrote a blog post describing the problem he ran into with sharing Rails sessions with another application written in Go, and how he managed to get around it.

JRuby 1.7.9
JRuby 1.7.9 was released. This release includes a total of 36 issues fixed since the last release, including some Windows specific bugs and some encoding issues. There's lots of improvements to the Enumerable module as well.