Stupid Simple Debugging

There are all kinds of fancy debugging tools out there, but personally, I get the most mileage out of good old puts statements.

When I started with Ruby, several years ago, I used puts like this to debug:

puts account.inspect

The problem with this is two fold. First, if you have a few puts statements, you don’t know which one is actually which object. This always led me to doing something like this:

puts "account: #{account.inspect}"

Second, depending on whether you are just in Ruby or running an app through a web server, puts is sometimes swallowed. This led me to often times do something like this when using Rails:

Rails.logger.debug "account: #{account.inspect}"

Now, not only do I have to think about which method to use to debug something, I also have to think about where the output will be sent so I can watch

Continue reading “Stupid Simple Debugging”

Stupid Simple Debugging

There are all kinds of fancy debugging tools out there, but personally, I get the most mileage out of good old puts statements.

When I started with Ruby, several years ago, I used puts like this to debug:

puts account.inspect

The problem with this is two fold. First, if you have a few puts statements, you don’t know which one is actually which object. This always led me to doing something like this:

puts "account: #{account.inspect}"

Second, depending on whether you are just in Ruby or running an app through a web server, puts is sometimes swallowed. This led me to often times do something like this when using Rails:

Rails.logger.debug "account: #{account.inspect}"

Now, not only do I have to think about which method to use to debug something, I also have to think about where the output will be sent so I can watch for it.

Enter Log Buddy

Then, one fateful afternoon, I stumbled across log buddy (gem install log_buddy). In every project, whether it be a library, Rails app, or Sinatra app, one of the first gems I throw in my Gemfile is log_buddy.

Once you have the gem installed, you can tell log buddy where your log file is and whether or not to actually log like so:

LogBuddy.init({
  :logger   => Gauges.logger,
  :disabled => Gauges.production?,
})

Simply provide log buddy with a logger and tell it if you want it to be silenced in a given situation or environment and you get some nice bang for your buck.

One Method, One Character

First, log buddy adds a nice and short method named d. d is 4X shorter than puts, so right off the bat you get some productivity gains. The d method takes any argument and calls inspect on it. Short and sweet.

d account # will puts account.inspect
d 'Some message' # will puts "Some message"

The cool part is that on top of printing the inspected object to stdout, it also logs it to the logger provided in in LogBuddy.init. No more thinking about which method to use or where output will be. One method, output is sent to multiple places.

This is nice, but it won’t win you any new friends. Where log buddy gets really cool, is when you pass it a block.

d { account } # puts and logs account = <Account ...>

Again, one method, output to stdout and your log file, but when you use a block, it does magic to print out the variable name and that inspected value. You can also pass in several objects, separating them with semi-colons.

d { account; account.creator; current_user }

This gives you each variable on its own line with the name and inspected value. Nothing fancy, but log buddy has saved me a lot of time over the past year. I figured it was time I send it some love.

Rails 3.1.0 has been released!

Hi everybody!

It’s been 3 Months since RailsConf, so I think it’s time we released Rails 3.1.0. So, here it is! I’ve released Rails 3.1.0!

CHANGES

For a much more attractive and easy to read list of changes, please check out the awesome Rails 3.1.0 Release Notes on the Rails Guides site. For a less attractive list of changes, please continue to read!

Here are some highlights of the major changes in Rails 3.1.0:

ActionPack

  • ActionPack has been updated to include the new asset pipeline. Please see the rails guides on the asset pipeline.

  • Streaming response support has been added. This feature allows you to stream templates to the user before processing has actually finished. See the Rails Guides, or documentation in ActionController::Metal::Streaming for more information. Middleware have been refactored to support this feature.

  • RJS has been extracted to a gem.

ActiveModel

  • attr_accessible and friends now accepts :as as option to specify a role

  • Added ActiveModel::SecurePassword to encapsulate dead-simple password usage with BCrypt encryption and salting.

ActiveRecord

  • Prepared statement caches have been integrated. ActiveRecord::Base#create and simple finders will use a prepared statement and cache for more performant inserts and selects.

  • Associations have been refactored for greater simplicity and maintainability.

  • default_scope can take any object that responds to call.

  • PostgreSQL adapter only supports PostgreSQL version 8.2 and higher.

  • Migrations use instance methods rather than class methods. Rather than defining a self.up method, you should define an instance method up.

  • Migrations are reversible. When a new migration is generated, the migration will contain one method called change. Database changes made in this method will automatically know how to reverse themselves. For more information, see the documentation for ActiveRecord::Migration and ActiveRecord::Migration::CommandRecorder.

  • When a model is generated, add_index is added by default for belongs_to or references columns.

ActiveResource

  • The default format has been changed to JSON for all requests. If you want to continue to use XML you will need to set self.format = :xml in the class.

ActiveSupport

  • ActiveSupport::BufferedLogger set log encoding to BINARY, but still use text mode to output portable newlines.

  • Add Object#in? to test if an object is included in another object.

  • ActiveSupport::Dependencies::ClassCache class has been introduced for holding references to reloadable classes.

  • Added weeks_ago and prev_week to Date/DateTime/Time.

  • JSON decoding now uses the multi_json gem which also vendors a json engine called OkJson. The yaml backend has been removed in favor of OkJson as a default engine for 1.8.x, while the built in 1.9.x json implementation will be used by default.

Railties

  • The default database schema file is written as UTF-8.

  • Rack::Sendfile middleware is used only if x_sendfile_header is present.

  • Add alias r for rails runner.

  • jQuery is the new default JavaScript library.

  • Added config.force_ssl configuration which loads Rack::SSL middleware and force all requests to be under HTTPS protocol

For more info

For a more detailed list of changes, please see each of the CHANGELOG files checked in to the Rails repository on github.

For an even more detailed list of changes, please see the commit list between Rails 3.0.10 and 3.1.0.

The End

I am personally very proud of this release. I want to say thank you to the people testing our release candidates, the people submitting patches and sending in bug reports. I think that Rails 3.1.0 is the best release of Rails to date, and we could not have done it without you.

Please continue to create amazing things with this framework!

SHA-1

  • b68f74ced662145a4139409edf3c51db1159ead8 actionmailer-3.1.0.gem
  • 136474f270677ae75ad0f9599d26e89cf1d4bc7b actionpack-3.1.0.gem
  • e6b68453c08bb0da52ed1d422ba2f87a5e3aa794 activemodel-3.1.0.gem
  • dfbae15c0d395304812c22fbf18aa9daadbe20b4 activerecord-3.1.0.gem
  • 3f1f547e500d1ffc1f7c3ee4ab9eb1526157a870 activeresource-3.1.0.gem
  • f21627c2f429abfa8685d2147fadab6704c13869 activesupport-3.1.0.gem
  • 21c6592189fb358a066846754a8f7ce7a238fca6 rails-3.1.0.gem
  • 79cfa1eca232de9a45453829287e4438089b7955 railties-3.1.0.gem

<3 <3 <3

RabbitMQ Add-on Now Available on Heroku

Today we’re proud to announce the availability in beta of RabbitMQ add-on by VMWare. RabbitMQ is an open source implementation of the AMQP protocol that provides a robust, scalable and easy-to-use messaging system built for the needs of cloud application developers.

Getting Started

With the add-on, provisioning a fully managed RabbitMQ instance couldn’t be easier to do:

$ cd rabbitdemo
$ heroku addons:add rabbitmq
-----> Adding rabbitmq to rabbitdemo... done, v2 (free)

$ heroku config
RABBITMQ_URL  => amqp://uname:pwd@host.heroku.srs.rabbitmq.com:13029/vhost

Your application’s environment will now have the RABBITMQ_URL set pointing to your new instance. Most modern AMQP clients such as Bunny for Ruby will accept a connection string in URI format, making configuration a breeze. The following is a simple Sinatra app that demonstrates posting and getting messages from the default RabbitMQ exchange. You can grab the source from Github here. Let’s have a look:

Entering a message and hitting "post" will send a message to a RabbitMQ queue, where it will sit until we tell the app to fetch the oldest message from the queue by clicking "get". Examining the application code, the first place to look is in "lib/sinatra_rabbitmq.rb" where we set up the connection from the environment variable, and declare a queue called "messages":

lib/sinatra_rabbitmq.rb

require 'sinatra/base'
require 'bunny'

module Sinatra
  module RabbitMQ
    def rabbitmq_client
      return @rabbitmq_client if @rabbitmq_client
      @rabbitmq_client = Bunny.new(ENV["RABBITMQ_URL"])
      @rabbitmq_client.start
      @rabbitmq_client
    end

    def rabbitmq_exchange
      @rabbitmq_exchange ||= rabbitmq_client.exchange("")
    end

    def rabbitmq_messages_queue
      @rabbitmq_messages_queue ||= rabbitmq_client.queue("messages")
    end
  end

  register RabbitMQ
end

Note that in RabbitMQ a message is never sent directly to a queue. Instead, it passes through an exchange, the type of which defines how messages are distributed to one or more client queues. In this case, we’re side-stepping the concept of exchanges by using the default nameless exchange, which allows us to specify the target queue for our messages using a routing key. Once you get into more advanced usage of RabbitMQ such a broadcasting messages to set of known queues, you’ll definitely want to learn more about exchanges.

With our connection established and queue defined, the main part of our app looks like this:

app.rb

require 'sinatra/base'
require "#{File.dirname(__FILE__)}/lib/sinatra_rabbitmq"

class RabbitmqDemo < Sinatra::Base
  register Sinatra::RabbitMQ

  get "/" do
    haml :index
  end

  post "/" do
    self.class.rabbitmq_exchange.publish params["message"], :key => "messages"
    @notice = "Message has been published."
    haml :index
  end

  get "/message" do
    msg = self.class.rabbitmq_messages_queue.pop
    if msg[:payload] == :queue_empty
      @notice = "No more messages."
    else
      @message = msg[:payload]
    end
    haml :index
  end
end

The first interesting part here is post to "/" where we send the message you typed in to the default exchange, using "messages" as the routing key. Then we pick up any outstanding at "/messages" by popping off the queue, which follows the FIFO principle. The rest, as they say, is just a bit of HTML.

Why would you want to use a messaging system?

The distribution of workloads across different process types is an essential aspect of modern web application architecture. For example, if your app handles file uploads, your web process might receive the upload and signal a background worker to do some processing on it via a queue. While you could use Delayed Job or another database-backed queueing library to do this, a true messaging system gives you much more flexibility, reliability and scalability in defining how your signals are distributed and received by your worker pool.

Finally, messaging is an important tool for the polyglot programmer. Having a language agnostic, data-centric message bus that can orchestrate communications between, say, a web app in Ruby, workers in Java and a chat server in Node.js is a key enabler in allowing application developers choose the right tool for any specific job.

Over the past few years RabbitMQ has emerged as one of the most popular, open source choices for messaging with clients in all major languages, and thousands of enterprises trusting it for mission-critical apps. We’re excited to offer it as a cloud service through the Add-ons Catalog, fully managed and operated by the team who created it.

Programming Concurrency now in print; Agile Web Dvl. updates to 3.1

Programming Concurrency on the JVM: Mastering Synchronization, STM, and Actors now in print; Agile Web Dvl. eBook updates to 3.1

Bill James, Sabermetrics, and You, or At Least Me

I was a nerdy kid.

I suppose that isn’t much of a surprise, given how I turned out. But in those pre-computer days, I was nerdy about math and baseball. I was the kind of kid that kept a daily log of my batting statistics in the recess kickball games.

So you can imagine my surprise and happiness when this image appeared in Sports Illustrated, in May 1981. I was ten:

Bill James in Sports Illustrated

The man in the foreground is Bill James, who would soon go on to be one of the most influential baseball writers of the last thirty years. At the time, though, he was self-publishing his baseball book to a small but fiercely loyal group of fans, one of whom actually wrote the SI article.

In the background, on the scoreboard, was one of James’ inventions – a formula called Runs Created that purported to be the most accurate way to measure a baseball player’s contributions.

Okay, I’m getting carried away. The relevant point is that I was dazzled enough by the original article to start looking for James’ annual book once he started getting published and distributed nationally. As I said, I was young, and the books cost like seven dollars of my own money, so this was kind of a big deal.

I got lucky in my choice of baseball writers. Not only was James iconoclastic and funny, but he was very good at explaining his methods. And I don’t mean that he was good at explaining the math – James is the first to admit that he is no mathematician (admittedly joking, he once described the “standard deviation” of batting average as “about what your standard deviant would hit”). James’ skill was in explaining why he did his experiments in a particular way. In a very real way, the most important things I learned about how science works were from reading Bill James.

In, I think, the first book of James’ that I read, he responds to criticism of earlier work:

“Journalists start with the answer… [Sabermetrics] starts with the question”

Sabermetrics, by the way, was the word that James coined for the search for objective knowledge about baseball – “saber” from SABR, the Society for American Baseball Research".

In other words, where a journalist would start with “Derek Jeter should be in the Hall of Fame”, James would start with “Should Derek Jeter be in the Hall of Fame?”, and not in the lazy-local-news-headline way where you know from the question where the answer is. More likely, James would start with “What kind of player is in the Hall of Fame? Does Derek Jeter meet that standard?”

I suspect that this distinction is obvious to most of you reading this (though it’s easy to find places in our public discourse where nobody seems to understand it.) But it was a big deal to 12-year-old me.

Later, I remember an epic dismantling of the phrase “Pitching is 75% of Baseball”, starting with wondering what that even meant, and then going one by one through the things that would be implied of that statement was true, determining that none of them actually were, and eventually concluding that even the baseball traditionalists who were fondest of the claim didn’t act in any way consistent with actually believing it. I can still quote large chunks of that one.

Some quotes didn’t really become meaningful to me until I started writing myself:

“One of the operating assumptions of this book is that you either own McMillan’s Baseball Encyclopedia or don’t care what it has to say. In either case, you don’t need me to tell you what an outfielder’s assist totals are”

I’ve used some variant of that comment for every book I’ve written (though it didn’t always make into the final version). I’ve also used in when reviewing books. It’s a really useful way to think about your audience, to realize that you can assume knowledge of or disinterest in certain information.

Another quote that was big with me when I used to read academic papers all the time, but that I also keep in mind when I write.

“This isn’t a bull session, this is science. I only write like it’s a bull session because I don’t like how scientists write”

James is always been a little cranky on the subjects of professionalism and expertise, which he sees as often being used as nothing barriers to keep out the riff-raff.

“When you write something it is either true or false and being an expert or not being an expert has nothing to do with it”

What’s really stuck with me, though is the way James went about seeking more objective knowledge. The process was simple.

  • Ask a question.
  • Determine something that is observable that would be true if the answer to the question is true.
  • Use small, empirical measurements. James is the king of quick-and-dirty measurements that favor ease of calculation and understanding over multi-digit precision.
  • Compare similar items that differ in one aspect. In the mid 80-s James was more excited about a method to measure how similar two players were than almost anything else, because it allowed him to create controlled studies.
  • Follow the data. You probably won’t learn what you expect. Respect the data and respect its limitations.

If you are interested in James’ baseball work, the best introduction right now is probably the Historical Baseball Abstract, which is an overview of both his statistical methods and his historical interests. A more biographical look at his effects can be found in Moneyball, by Michael Lewis, which is about how the Oakland A’s applied James-style methods to actually win games. It’s a great non-fiction narrative, and Lewis is, as far as I can tell, unusually factually accurate.

James’ most recent book is Popular Crime, which is not about baseball, but rather a historical overview of crime stories that become pop-culture touchstones, and also the books that have been written about them. It’s cranky, scattershot, obsessive, and hard to put down.

Filed under: Books, Me

Writing tests is not fun. Anyone who tells you otherwise is a liar….

At least so says my good friend Sean Voisen in his latest blog entry Thoughts on test-driven development.

What, you are calling me a liar? 🙂 I must respectfully disagree with Sean. Not on the fact that he may think it’s not fun, that’s his opinion like many other Flex developers that don’t do testing. I disagree because I see many developers, in other communities, that actually really enjoy testing. If you look at the Ruby community you will see many developpers enjoying doing test driven development, enjoying writing tests, and even expanding the way you can write tests. Check out rspec, Cucumber, and the many of books and screencast on the subject. Checkout all the ruby libraries, they are all pretty well tested. There are many training classes on people that really want to improve doing testing. Many Rails projects are extremly well tested. Many Ruby developers cannot even code without writing tests first.

This said as they are many examples on how to test Ruby and Rails code it’s easier to get going on with testing in that environment. On the other hand, there are not many example of tested Flex applications and libraries. Not many toturoials on how to test your Flex application.
I happend to do a lot of unit testing for my Flex apps, but I do not test everything, I use tests for more difficult aspects, when I’m not sure how to design something, when it’s slow to access a part of the application just to verify that my new code works. Then I write tests and it’s fun. How many times do you manually repeat a sequence on the UI like start the application, perform a search, click on the grid, open a record, click the calculate button…Oh no, that not right…go change some code and do it again. Well that’s not fun. Every developer I know does that thousands a time a day. Well, write a test and your workflow becomes more fun.

So why are Flex developers not testing? As I mentioned above, there is not much peer pressure to do so as not many Flex developers do testing. Also they are not many examples. In addition it’s not obvious how to test applications in many case. Often they are not written in a testable manner. Flex/ActionScript is asynchronous and event driven, that’s harder too.

They are solutions for that and Flex applications are very well suited to testing…but the sweet spot must be found. And you should start by testing the simple things that have lots of added value. Anywhere you have logic in your code that does filtering, calculation, transform data, write a test…You gonna like it. FlexUnit 4 as great support for asynchronous or event driven programming, but I agree, at first it’s not obvious how to best us that support. So again, start with the simple thing, refactor your code so that you can test it in a non-asynchronous way, that will already be helpfull.

So I came to the conclusion that I won’t be able to convince Flex developers that testing is needed and even fun. I can only hope that as a Flex developer you will start using FlexUnit 4 and try to add tests to your application and persevere and find the sweet spot on where testing is fun and makes you more productive. If you persevere you will like many Ruby developers become a better developer, write better code and faster.

I finally like Sean’s balanced view on test driven development: “But would I use TDD for every project I work on? Probably not. For personal “one-off” projects or projects I know will not see much future maintenance, the slower development time is simply not worth it. For serious, long-term projects however, TDD is now a must.”

Testing remains hard, but it’s just essential if you want to become a great, agile, developer.

Persevere and testing will become your friend!

Enjoy!
Daniel

Writing tests is not fun. Anyone who tells you otherwise is a liar….

At least so says my good friend Sean Voisen in his latest blog entry Thoughts on test-driven development.

What, you are calling me a liar? 🙂 I must respectfully disagree with Sean. Not on the fact that he may think it’s not fun, that’s his opinion like many other Flex developers that don’t do testing. I disagree because I see many developers, in other communities, that actually really enjoy testing. If you look at the Ruby community you will see many developpers enjoying doing test driven development, enjoying writing tests, and even expanding the way you can write tests. Check out rspec, Cucumber, and the many of books and screencast on the subject. Checkout all the ruby libraries, they are all pretty well tested. There are many training classes on people that really want to improve doing testing. Many Rails projects are extremly well tested. Many Ruby developers cannot even Continue reading “Writing tests is not fun. Anyone who tells you otherwise is a liar….”

Play! on Heroku

Developers with experience in both Java and Ruby web development often ask the question: Why is web app development so complicated in Java, and so much simpler in Ruby, with Rails?

There are many ways to answer this question. But importantly, none of them should blame the Java language itself. The people behind Play! Framework proved this by creating a Java based web framework that is as elegant and productive as Rails for Ruby.

It is our pleasure to announce Play! on Heroku in public beta.

Play! on Heroku Quickstart

Download and install Play! version 1.2.3 or later. Then, create a new Play! app:

$ play new helloworld
~        _            _ 
~  _ __ | | __ _ _  _| |
~ | '_ \| |/ _' | || |_|
~ |  __/|_|\____|\__ (_)
~ |_|            |__/   
~
~ play! 1.2.3, http://www.playframework.org
~
~ The new application will be created in /Users/jjoergensen/dev/tmp/helloworld
~ What is the application name? [helloworld] 
~
~ OK, the application is created.
~ Start it with : play run helloworld
~ Have fun!
~
$ cd helloworld

Create a Procfile:

web: play run --http.port=$PORT $PLAY_OPTS

Commit to Git, then create an app on the [Cedar] stack and deploy:

$ git init
$ git add .
$ git commit -m init

$ heroku create --stack cedar

$ git push heroku master
Counting objects: 30, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (22/22), done.
Writing objects: 100% (30/30), 35.95 KiB, done.
Total 30 (delta 1), reused 0 (delta 0)

-----> Heroku receiving push
-----> play app detected
-----> Installing Play!..... done
-----> Building Play! application...
       ~        _            _ 
       ~  _ __ | | __ _ _  _| |
       ~ | '_ \| |/ _' | || |_|
       ~ |  __/|_|\____|\__ (_)
       ~ |_|            |__/   
       ~
       ~ play! 1.2.3, http://www.playframework.org
       ~
       1.2.3
       Play! application root found at ./
       Resolving dependencies: .play/play dependencies ./ --forceCopy --sync --silent -Duser.home=/tmp/build_2rgcv7zjrtyul 2>&1
       ~ Resolving dependencies using /tmp/build_2rgcv7zjrtyul/conf/dependencies.yml,
       ~
       ~
       ~ No dependencies to install
       ~
       ~ Done!
       ~
       Precompiling: .play/play precompile ./ --silent 2>&1
       Listening for transport dt_socket at address: 8000
       16:14:33,716 INFO  ~ Starting /tmp/build_2rgcv7zjrtyul
       16:14:34,372 INFO  ~ Precompiling ...
       16:14:37,656 INFO  ~ Done.

-----> Discovering process types
       Procfile declares types -> web
-----> Compiled slug size is 26.2MB
-----> Launching... done, v5
       http://blazing-water-545.herokuapp.com deployed to Heroku

Visit your app’s URL to see it running on Heroku.

A Radical Approach to Java Web Framework Design

For as long as developers have been writing web apps in Java, web frameworks have proliferated to try to make web development easier. But no existing frameworks have taken a clean-room approach. They’ve been bound by various self-imposed restrictions such as compatibility with servlet containers, support for JSP, compatibility with the standard Java web app layout, and conformance to Java and OO principles even when they don’t make sense.

Play! is the first Java web framework to start fresh. It is a built-for-deployment framework that borrows heavily from Rails. Play! applications are meant to be deployed, not packaged and distributed. This allows developers to throw away deeply nested Java package structures, control flow in XML, forget about packaging WAR files, and instead structure projects for optimal clarity and developer productivity.

For example, the helloworld app created above contains a single Java class, the controller:

package controllers;

import play.*;
import play.mvc.*;

import java.util.*;

import models.*;

public class Application extends Controller {

    public static void index() {
        render();
    }

}

This class defines a single HTTP entry point processed by the index() method which delegates rendering of output to an index.html template using the render() method.

No boilerplate classes or XML config files are needed. The framework takes a fresh approach to packaging conventions, and uses static code where it makes sense. For example, since controller entry points are stateless, and HTTP-oriented instead of object-oriented, they are implemented as static methods (the index() method above).

Add in developer-convenience features like automatic compilation during development, and you’ll find that Play! is dramatically more productive to work with than any existing Java web framework.

A Containerless World

Jetty has always been at the forefront of containerless deployment, but it has been a lonely place for more than a decade. And the experience can be clunky, because little attention has been paid to optimizing the developer experience for containerless apps. Play! shows how simple and elegant containerless development and deployment can be when it’s directly supported by a framework. Running your app locally is as simple as executing play run. Running it in production is as simple as pushing the entire project to production and executing play run --%prod.

Heroku was designed exactly for this model. Play! applications find a natural home on the Heroku platform. When developing on Heroku, you test your app locally with play run, or foreman start. When you are ready to deploy, you simply push your whole project with git push heroku master and heroku will execute play run in production mode. This results in a deployment workflow with minimal and easily understandable differences between deployment and production. In fact, you can run it locally exactly the same way it runs on Heroku eliminating any problems caused by environment differences.

More Than Just Sugar

One might jump to the conclusion that Play! is overly focused on ease of use at the cost of performance and robustness. After all, isn’t that the reason other frameworks were built on existing, highly optimized libraries?

Look under the covers of Play! and you will find that the start-for-scratch approach gives performance benefits as well. Play! is designed from the ground up to support asynchronous processing of web requests, a technique that is gaining widespread adoption with Node.js, Python’s Twisted, and Ruby’s EventMachine.

Play! uses Netty, a non-blocking I/O protocol library built by the JBoss team. It combines non-blocking I/O with an elegant continuation-based programming model to deliver asynchronous processing of requests.

For example, the rendering of a PDF can be done in the background while suspending the incoming request as simple as this:

public static void generatePDF(Long reportId) {
    Promise<InputStream> pdf = new ReportAsPDFJob(report).now();
    InputStream pdfStream = await(pdf);
    renderBinary(pdfStream);
}

Play! also does away with the use of stateful sessions, which are so common in other Java web frameworks. By embracing a share-nothing model, Play! makes it easy to scale out applications horizontally by adding more nodes.

Further Reading

We think you’ll find Play! not only productive, but fun. Dive in and start building apps!

Special Thanks

Special thanks to the Play! Framework team at Zenexity, in particular Guillaume Bort for his support and stewardship and Erwan Loissant for accepting and integration several feature requests.

The Ruby on Rails API Switches to SDoc

The Ruby on Rails API is switching to SDoc starting with 3.1.

SDoc is a RDoc format created by Володя Колесников (@voloko) that has been powering railsapi.com for a long time.

Among other things, SDoc provides a search box with fuzzy match completion, tree browsing, keyboard navigation, and a really nice template.

You can already see the upgrade in the edge API.

We’d like to thank very much Володя for his work updating SDoc for the official API. Thanks man!

[ANN] Rails 3.1.0.rc8

Hi everyone,

Rails 3.1.0.rc8 has been released (we’ve an issue with rc7). This is
the final release candidate. Please give it a try, it’s our last
chance to fix regressions and severe issues. We will be releasing
final 3.1.0 next August 30th.

CHANGES

Check the CHANGELOG file of each framework to see what we’ve changed.

You can find an exhaustive list of changes on
github.
Along with the closed issues marked for
v3.1.0
.

You can also see issues we haven’t
closed
.

A comprehensive CHANGELOG will be announced when 3.1.0 final is released.

Thanks!

#281 Foreman

Foreman can help manage multiple processes that your Rails app depends upon when running in development. It also provides an export command to move them into production.

Cloud based services – the future of the Internet

Fred Wilson has a response today to Eric Schmidt’s declaration in Edinburgh that Google+ is an “identity service”. He asks and answers his own question.

“whom Google built this service for? You or them. And the answer to why you need to use your real name in the service is because they need you to.”

Of course Facebook is also an identity service. Facebook Connect is the means of distributing it. And of course Facebook too is built using real names because “they need you to”.

At this level FaceBook and Google have much in common, and both are vying for us to use them for online authentication. Facebook is far ahead of course.

Late yesterday I posted an opinion piece as a guest author on TechCrunch. It is about the uncertain future of web services as mobile devices proliferate globally. We will soon all have awesome identity machines in our pocket. They will be capable of being used to authenticate us (even using 2 step authentication). Any cloud-based 3rd party identity system will be unnecessary.

The future of identity is distributed, under user control, and owned and managed by the user from their device. It will be capable of supporting anonymity and real names and will be able to be trusted by sites requiring you to authenticate. The idea of any 3rd party dictating how you can present yourself online will no longer be applicable. Of course, it still has to be built…..

Having said that, there is absolutely nothing wrong with Google and/or Facebook building an identity system that dictates how we present ourselves. Our choice is to use it or not…..We don’t have to.

22 Ruby and Rails Jobs for August 2011 (With Even Some Junior Ones)

jobs.pngIt seems the Ruby and Rails job scenes are on fire! I don’t remember running so many jobs across a single month before. 22 Ruby and Rails jobs are here and they’re spanning the world. US West Coast, East Coast, England, Scotland and Germany are all represented. It’s definitely not the common “San Francisco or nothing” roundup 🙂

Also fresh this time around is the mention of “all levels” or “junior” roles. At least a few of the jobs listed here today are open to all skill levels or are explicitly junior in nature. I’ve had a lot of readers get in touch requesting more listings like these so I’m glad they’ve come along.

To promote a job, see the Post A Job page. A bonus is your ad gets into the 7563 subscriber Ruby Weekly for free (as a bonus) and our 6201 follower @rubyinside Twitter account.

Sr and Jr Ruby Developers – Clifton Park, New York

Internet Marketing Ninjas (Formally We Build Pages) is hiring expert Ruby Developers (and Jr Developers too!). They’re one of the world’s premier companies providing Internet marketing services and the salary range is listed as $60k-150k — click here to learn more.

Great Ruby Developer – London, UK

Econsultancy is a rapidly expanding online publisher based in London and New York. They’re looking for a proactive Rubyist to join their team in London. You’ll be working with a myriad of technologies including RSpec, Sass, Rack, and Rails. A flexible working arrangement is standard and the salary is listed as up to £60k — click here to learn more.

Econsultancy is also looking for a junior Ruby developer. A lot of readers ask why there aren’t more junior level roles out there.. I don’t know why but here’s one to check out! 🙂

Ruby on Rails Developer – Berlin, Germany

Wimdu (Europe’s leading online marketplace for private accommodation) is looking for a Ruby on Rails Developerclick here to learn more.

Senior Frontend Web Developer – Denver, Colorado

Digitally Imported, a family of online radio stations, is looking for a Senior Frontend Web Developer to work on a full time basis from the comfort of their own home. Developers outside of the US are welcome, but they do require candidates to be fluent in English — click here to learn more. P.S. I recommend DI’s Electro House channel, it’s awesome!

Ruby Engineer – San Francisco, California

Samasource, a nonprofit organization that brings dignified, computer-based work opportunities to people living in poverty around the world, is looking for a Ruby Engineer with significant software development and API design experience — click here to learn more.

Ruby On Rails Developer – Irvine, California

RevSource Solutions is looking for a Ruby On Rails Developerclick here to learn more.

Ruby on Rails Developer – San Mateo, California

Motista, the world’s first consumer connection environment, is looking for a Ruby on Rails Developerclick here to learn more.

Full-time Ruby on Rails Developer – Boston, Massachusetts

District Management Council, a strategic advice and consulting company for public schools, is looking for a Full-time Ruby on Rails Developerclick here to learn more.

Senior Rails (and JRuby) Software Engineer – Oakland, California

Outbid is a unique peer-to-peer auctioning platform designed to allow users to host live online auctions. They’re looking for a Senior Rails Software Engineer with JRuby experience — click here to learn more.

Rails Developer at the #2 Rails Site – San Francisco, California

Scribd, the hugely popular social publishing site, is looking for a Rails Developer at the world’s 2nd busiest Rails siteclick here to learn more.

Scribd is also looking for a Senior Rails Developer with a strong knowledge of SQL, and extensive experience with performance and scalability, including front-end web browser performance analysis — click here to learn more.

Senior Developer – Berlin, Germany

1000jobboersen specializes in individual consultation and performance oriented posting of job advertisements. They’re looking for a Senior Developer. Trivia: Durran Jordan, creator of Mongoid, works there, so you’ll be in good company! — click here to learn more.

Ruby on Rails or Python Django superstar for web+mobile startup – New York, New York

Collectrium, a technology company focused on elegant tools for art collectors, galleries, and art fairs is looking for a Ruby on Rails or Python Django superstar for their Web + mobile startup — click here to learn more.

Ultimate Agile Developer Job – New York, New York

Pivotal Labs, a premier software development consultancy, is looking for a Ultimate Agile Developer Jobclick here to learn more.

Ruby on Rails Developer for Media Applications – Fairfax, Virginia

Gannett Co., Inc. is looking for a Ruby on Rails Developer for Media Applicationsclick here to learn more.

Ruby on Rails Developer – Troy, New York

Enable Labs is looking for a Ruby on Rails Developerclick here to learn more.

Front-End Software Engineer – Arlington, Virginia

HealthCentral‘s mission statement is to “empower people to improve and take control of their health and well-being.” They run many different health related Web sites and are looking for a Front-End Software Engineer to work on them — click here to learn more.

Rails Web Developer – Seattle, Washington

Elastic Suite is looking for an experienced Rails software engineer to work on custom order entry/digital catalog applications. Your primary role will be enhancing and implementing the Rails 3 application which is built upon MongoDB and provides web services for consumption by various client applications — click here to learn more.

Front End Developer – Silver Spring, Maryland

Webs, Inc. is looking for a Front End Developerclick here to learn more.

Senior Web Developer – New York, New York

SkillSlate.com is a site that will find great people for anything you need done. They’re looking for a Senior Web Developer to take their site to the next level — click here to learn more.

Ruby and Rails Engineers (of all levels) – Edinburgh, Scotland

FreeAgent, leading pioneers in web-based accounting, are looking for full-time Ruby engineers of all levels to join their engineering team in a brand new office in beautiful Edinburgh. It’s a fantastic opportunity to join a young, exciting and fast-growing company, helping to develop a much-loved and high-traffic customer-facing web app. We pay well and you’ll have the best kit, flexible hours, 33 days annual leave, pension scheme and more — click here to learn more.

To promote a job, see the Post A Job page. A bonus is your ad gets into the 7563 subscriber Ruby Weekly for free (as a bonus) and our 6201 follower @rubyinside Twitter account.

Termistat : a status bar for your terminal

When running background processes that produce detail logging, it’s often difficult to strike the right balance between providing overall status information and details about the current step in the process. It’s helpful to be able to see “tail-like” information at the detail level to monitor and debug your processes; however, it’s also helpful to be able to know summary information, such as the overall progress through the entire task. You can intersperse “record 1 of n” lines in your output, but they are easy to miss in all the noise.

In order to be able to display both types of information concurrently, I built a simple gem called termistat, which allows you to display a status bar for summary information at the top of your terminal in addition to the original detailed output. It was meant to be a whyday contribution, but I didn’t quite finish it in time to be released on whyday…oh well.

Here’s a screenshot of termistat in action:
termistat screenshot

Termistat requires the ffi-ncurses gem (which requires the ncurses library to be on your system), and has a configuration DSL to customize the appearance somewhat. Check it out and let me know if you have any ideas for improvement!

Termistat : a status bar for your terminal

When running background processes that produce detail logging, it’s often difficult to strike the right balance between providing overall status information and details about the current step in the process. It’s helpful to be able to see “tail-like” information at the detail level to monitor and debug your processes; however, it’s also helpful to be able to know summary information, such as the overall progress through the entire task. You can intersperse “record 1 of n” lines in your output, but they are easy to miss in all the noise.

In order to be able to display both types of information concurrently, I built a simple gem called termistat, which allows you to display a status bar for summary information at the top of your terminal in addition to the original detailed output. It was meant to be a whyday contribution, but I didn’t quite finish it in time to be released on whyday…oh well.

Here’s a screenshot of termistat in action:
termistat screenshot

Termistat requires the ffi-ncurses gem (which requires the ncurses library to be on your system), and has a configuration DSL to customize the appearance somewhat. Check it out and let me know if you have any ideas for improvement!

Termistat : a status bar for your terminal

When running background processes that produce detail logging, it’s often difficult to strike the right balance between providing overall status information and details about the current step in the process. It’s helpful to be able to see “tail-like” information at the detail level to monitor and debug your processes; however, it’s also helpful to be able to know summary information, such as the overall progress through the entire task. You can intersperse “record 1 of n” lines in your output, but they are easy to miss in all the noise.

In order to be able to display both types of information concurrently, I built a simple gem called termistat, which allows you to display a status bar for summary information at the top of your terminal in addition to the original detailed output. It was meant to be a whyday contribution, but I didn’t quite finish it in time

termistat screenshot

Continue reading “Termistat : a status bar for your terminal”

Heroku for Java

We’re pleased to announce the public beta of Heroku for Java. Java is the fourth official language available on the Cedar stack.

Java is, by many measures, the world’s most popular programming language. In addition to its large and diverse developer base, it offers a huge ecosystem of libraries and tools, an extremely well-tuned VM for fast and reliable runtime performance, and an accessible C-like syntax.

But there are also many criticisms commonly leveled against the language. We’ll take a closer look at Java’s strengths and weaknesses in a moment, but first:

Heroku for Java in 2 minutes

Create a project with three files:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <version>1.0-SNAPSHOT</version>
    <artifactId>helloworld</artifactId>
    <dependencies>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlet</artifactId>
            <version>7.6.0.v20120127</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.4</version>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals><goal>copy-dependencies</goal></goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

src/main/java/HelloWorld.java

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.*;

public class HelloWorld extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.getWriter().print("Hello from Java!\n");
    }

    public static void main(String[] args) throws Exception{
        Server server = new Server(Integer.valueOf(System.getenv("PORT")));
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        server.setHandler(context);
        context.addServlet(new ServletHolder(new HelloWorld()),"/*");
        server.start();
        server.join();   
    }
}

Procfile

web:    java -cp target/classes:target/dependency/* HelloWorld

Commit these files to Git:

$ git init
$ git add .
$ git commit -m init

Create an app on the Cedar stack and deploy. Your Java program and all its dependencies will be built at slug compile time:

$ heroku create --stack cedar
Creating hollow-dawn-737... done, stack is cedar
http://hollow-dawn-737.herokuapp.com/ | git@heroku.com:hollow-dawn-737.git
Git remote heroku added

$ git push heroku master
Counting objects: 9, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (5/5), done.
Writing objects: 100% (9/9), 1.36 KiB, done.
Total 9 (delta 0), reused 0 (delta 0)

-----> Heroku receiving push
-----> Java app detected
-----> Installing Maven 3.0.3..... done
-----> Installing settings.xml..... done
-----> executing .maven/bin/mvn -B -Duser.home=/tmp/build_yiuhjlk5iqs4 -s .m2/settings.xml -DskipTests=true clean install
       [INFO] Scanning for projects...
       [INFO]                                                                         
       [INFO] ------------------------------------------------------------------------
       [INFO] Building helloworld 1.0-SNAPSHOT
       [INFO] ------------------------------------------------------------------------
       ...
       [INFO] ------------------------------------------------------------------------
       [INFO] BUILD SUCCESS
       [INFO] ------------------------------------------------------------------------
       [INFO] Total time: 5.377s
       [INFO] Finished at: Mon Aug 22 16:35:58 UTC 2011
       [INFO] Final Memory: 12M/290M
       [INFO] ------------------------------------------------------------------------
-----> Discovering process types
       Procfile declares types -> web
-----> Compiled slug size is 13.6MB
-----> Launching... done, v3
       http://hollow-dawn-737.herokuapp.com deployed to Heroku

Then view your app on the web:

$ curl http://hollow-dawn-737.herokuapp.com
Hello from Java!

For more detail see:

Why Java?

Java is a solid language for building web apps:

  • The JVM is one of the best runtime VMs in the world, offering fast performance and a reliable memory footprint over time.
  • Java boasts an estimated population of six million developers, with a vast ecosystem of tools, libraries, frameworks and literature. It is the most mature and established programming language for building server-side applications in existence today.
  • Born at the beginning of the Internet age, Java began with the goal of "write once, run anywhere." Though it took a long time to get there, this goal has been largely achieved. The universal JVM runtime environment is available on an incredibly wide range of platforms and offers near-perfect portability between those platforms with no changes in application code, and even build artifacts are binary-compatible.

Despite these strengths, Java faces criticism from many sides. Partially, this is an inescapable effect of popularity. But many of these criticisms are valid, and reflect the downside of being a mature community: substantial legacy baggage.

To understand this better, we need to tease apart Java (the programming language) from J2EE (the "enterprise" application container interface).

How J2EE Derailed Java

Java took off as a server-side programming language with the emergence of the JDBC and Servlet APIs in the late 1990s. Since then a vast number of web applications have been built using these basic APIs combined with other technologies like JSP, JSF, Struts, Spring and more. The emergence of J2EE and J2EE application servers boosted Java’s presence in the enterprise and created a lucrative software segment of J2EE middleware vendors. But it also added complexity to applications and deployment processes.

J2EE was built for a world of application distribution — that is, software packaged to be run by others, such as licensed software. But it was put to use in a world of application development and deployment — that is, software-as-a-service. This created a perpetual impedance mismatch between technology and use case. Java applications in the modern era suffer greatly under the burden of this mismatch.

As one illustration, consider the J2EE Development Roles document. It suggests an assembly-line model for development and deployment of apps, with the code passing along a chain of eight different people. This was a fairly complex and bureaucratic model that didn’t match how software was developed a decade ago, let alone today.

In Stop Wasting Money On WebLogic, WebSphere, And JBoss Application Servers, Forrester analyst Mike Gualtieri writes:

Traditional application servers or containers such as Tomcat will fast become legacy methods for deploying Java applications. The next generation is elastic application platforms (EAP) that are containerless.

In recent years, J2EE vendors have attempted to fix the problems (including a re-branding from J2EE to JEE). Unfortunately, it was too little too late. The Java space is now ripe for disruptive innovation by cloud application platforms.

Heroku for Java

If you’ve worked with Java before, the content of the hello-world sample app shown above may have surprised you. There is no "application container" in the J2EE sense; the app uses Jetty as an embedded webserver, just as one might use Unicorn for Ruby or Tornado for Python, or Jetty itself for Clojure.

The capabilities promised by J2EE application containers for managing your app include deployment, restart, logging, service binding (config), and clustering (horizontal scaling). Running your Java app on Heroku, you achieve these ends via the platform instead.

But unlike J2EE, Heroku is a polyglot platform. Techniques for deployment, logging, and scaling are applicable to all app deployments, regardless of language. A common deployment infrastructure reduces language choice to just a question of syntax and libraries. Reduced coupling between app and infrastructure enables picking the right language for each job.

A New Era for Software Delivery

Using Heroku’s platform to run Java apps finally solves the impedance mismatch between application containers designed for traditional software distribution, and the modern world of software-as-a-service.

In the classic software delivery process (development → packaging → distribution → install → deployment), code passes through many hands before it finally reaches the end user. Developers build, QA verifies, ops deploys, and finally end users can access. In this environment, the feedback loop for information about how code behaves in production is slow and inefficient — it may take weeks or months for this to make it back to developers, and often in a highly-filtered format.

Heroku is built for the new era of software-as-a-service. An app is built by a small, cross-functional, relatively independent team which builds and deploys everything itself, with few or no hand-offs to other teams. There is no packaging, distribution, or install element because the code never leaves the team/organization. This keeps developers who build the software in close touch with how it behaves in production. And it enables continuous delivery, for a tight feedback loop between customer needs and resulting software built for those needs.

Java teams are often still stuck with the classic process because it’s built into the toolchain. Heroku for Java is optimized for compact applications that require robust, yet agile deployment and rapid iterations. You can deploy any Java application to Heroku, including J2EE applications, but you aren’t constrained by the J2EE deployment process.

Other JVM Languages

This announcement is official support for Java the language, but developers familiar with the JVM have already seen that it’s possible to deploy any other JVM-based language, by bootstrapping with pom.xml. The JVM is becoming popular as the runtime VM for both new and existing languages, so Java support on Heroku makes it much easier to bootstrap into running any JVM language on our platform.

For example, JRuby is one of the most frequently-requested languages on Heroku. Matthew Rodley has already put a Rails app onto JRuby on Heroku by adding JRuby to pom.xml. Scala, another common request, could be done the same way. We do look forward to being able to offer the same kind of first-class support for JRuby and Scala that we offer for Clojure; but in the meantime, bootstrapping via Java is a reasonable strategy.

Learning From Each Other

With the rise of polyglot programming, cross-talk between language communities has become much more common. Heroku’s polyglot platform further reinforces that trend.

Younger language communities have much they can learn from a mature community like Java. For example, Java began working on build automation and dependency management (via Ant, and later Maven) long before Ruby/Rails got Gem Bundler, Python got Pip, or Clojure got Leiningen. These tools owe much of their underlying theory to the learning (and battle scars) accumulated by Java build tools.

At the same time, Java has much it can learn from younger languages which are unencumbered by legacy baggage. Patterns, frameworks, and build systems in newer languages are already optimized for cloud application deployment with no left-over cruft from past eras. Java has already borrowed ideas in the framework space — see Play! or Grails for two examples. But sharing common deployment infrastructure between languages opens up the possibility for Java developers to get more exposure to deployment and scaling best practices from other communities.

The Future

Java is another milestone on the polyglot platform path, but there’s more to come. Future language packs will span the gamut from venerable (like Java) to cutting-edge (like Clojure and Node.js) to squarely in-between (like Ruby). Our desire is to be as inclusive as possible. Choice of language is up to the developer.

Heroku is driven by a simple first principle: do what’s best for developers. Supporting Java is what’s best for the large world of Java developers; it’s what’s best for developers who want to use other JVM languages; and it’s even good for users of other languages, who will benefit indirectly from the learning their community may gain from contact with Java. We’re pleased to welcome Java developers to Heroku.

Get Going

Ready to get started building Java apps on Heroku? Start with these articles in the Dev Center:

RubyShift, IE9, Letters from _why, and more

In this episode, Peter and Jason go over Ruby Shift, CarrierWave for uploads, IE9’s policy on the DELETE method, and cover the usual round up of projects.

Pragmatic Guide to Sass now in beta

Pragmatic Guide to Sass now available in beta