RailsConf 2011 - Day 1 »

Created at: 16.05.2011 22:37, source: OnRails.org, tagged: Ruby on Rails html5 railsconf

RailsConf 2011 - Day 1 Today is the tutorial days.

Tutorial 1 : html5tutorial

I started RailsConf with the "Building Web Apps with HTML5: Beyond the Buzzword" by Mike Subelsky (@subelsky).
He prepared twelve html5 exercises that walked the about 250 attendees through various features of html5 over a 2.5 hour session. It's fun to have time to work on these features. The high point was having about 200 computers using Websockets to send data back and forth with his server. He created a small ruby program that used EventMachine::WebSocket and it was holding up quite well all these connections.
You can download his tutorial and all files from https://github.com/subelsky/html5tutorial. Look at the tutorial.html file for instructions.
Here are a few highlights of his talk:

1 - Feature Detection

By using the Modernizr library, we used modernizr-1.7.js, you can detect difference html5 of your browser.
For example:
  • Modernizr.canvas
  • Modernizr.websockets

2 - Basic Canvas Drawing

You can get a 2d context and draw on the canvas via that context. You can use fillRect and other primitives like moveTo and lineTo to draw.
    var canvas = document.getElementById("main");
    var context = canvas.getContext("2d");
    context.fillRect(0,0,20,20);

Here I just created a loop to generate 180 rectangles. Note they are clipped due to the width of the canvas.

3 - Canvas Image Manipulation

    var img = new Image();
    img.src = "http://www.flickr.com/photos/50183640@N05/5616041841/";
    img.onload = function() {
    context.drawImage(img,0,110);
    };


4 - Basic Animation

In this exercise we first load a new image then trap the keystroke and call the up method. Note we use jquery:
	var characters = new Image();
	characters.src = "http://onrails.org/files/20110516_characters.gif";

	characters.onload = function() {
	  $(window).keyup(move);
	};
In the move the x+y coordinates are updated accordingly and is cleared and redrawn.
	  context.clearRect(0,0,width,height);
	  context.drawImage(characters,33,0,32,32,x,y,32,32);	
Use the left and right arrow keys

5 - Fun With Forms

In this exercise we look at few attributes of the input tag like the placeholder and autofocus attributes.
	<input id="username" placeholder="Your name" autofocus>
	<input id="fn" placeholder="First name">
Use the slider below to scale the image:





We listen to the change event of the size input and call the draw() function. Note the last two of the drawImage below is the new width and height which will give us the scaling effect.
	<input id="size" type="range" min="4" max="320" step="8" value="60">
	function draw() {
	  context.clearRect(0,0,width,height);
	  context.drawImage(characters,33,0,32,32,0,0,sizeAmt,sizeAmt);
	}	

6 - Local Storage

If you are in Google Chrome press option-command-j to bring up the javascript console. The you can enter key-values pair associated with the page. It's like a client side cookie.
	localStorage.setItem('shaz','bot')
	localStorage.getItem('shaz')
	localStorage.length // return 1
	localStorage.clear()

7 - Canvas Cleanup

The canvas itself can be styled like any element. Here we set a black background:

  canvas { 
    background-color: black;
  }

  input { display: block; }	

8 - Web Sockets

That was the fun part of the presentation, mike created the a small ruby application and had over 200 clients connecting to it.
Here is an extract of the ruby program:
  class TutorialServer
    def run
      EventMachine.run do
        EventMachine::WebSocket.start(:host => @host, :port => @port) do |socket|
          socket.onmessage do |msg|
            @logger.info "received: #{msg}"
            broadcast(msg)
          end
        end
        EventMachine::add_periodic_timer(10) { broadcast(JSON.generate({ :type => "ping" })) }
      end
    end

    def broadcast(msg)
      @sockets.keys.each { |socket| socket.send(msg) }
    end
  end
  TutorialServer.new('0.0.0.0',8011).run
Then when the users moved the character image using the keyboard each keystroke was sent to his server.
// create the socket  
var ws = new WebSocket("ws://exp.subelsky.com:8011");

// sent to position+name to server
ws.send(JSON.stringify({ name: name, x: x, y: y, type: "move" }));
Ultimately he wanted to drive multiple clients from his server...but we ran out of time to dive into this.

And much more..

Mike covered additionally these topics: Embedded Media, Geolocation, Web Workers, Offline App

Well that was a couple of hours well spent! Go check out his material on github.

Tutorial 2 : Building Bulletproof Views

Now I'm at a great presentation from John Athayde & Bruce Williams on how to make elegant html, css and javascript. The slides will be posted online.
Here are some of the topics:
  • The Art of Template Writing
  • Nailing Navigation
  • Maintainable Forms
  • Don't Fear the Object
  • Going Mobile
  • packaging Assets
  • Questions & Discussion

And the day is not over...Ignite Rails tonight.
Enjoy!
Daniel Wanja


more »

RailsConf 2009 Day Two »

Created at: 07.05.2009 06:13, source: OnRails.org, tagged: Ruby on Rails railsconf

Day Two got off to a good start. Engine Yard did a promotional pitch—the speakers could have been a bit more polished, but it was interesting stuff about their one-button-deployment, and overall not bad for an advertisement.

Next up was Chris Wanstrath. He started with a lead in regarding how to become a famous Rails developer—focusing on yourself, your blog readership numbers, your twitter follower count, etc. Later, he talked about how he went from being an unemployed college dropout to co-founder of the very successful GitHub, due to sharing code. His point was that in his eyes, it’s better to focus more on the community: share code, contribute to open source projects, even write documentation for existing projects. Being a good developer trumps being a famous developer. The complete text of the talk is online here .

For the first session of the day, it was a tough call between Rack/Sinatra and Metric Fu. I finally went with:

Using metric_fu to Make Your Rails Code Better – Jake Scruggs

The central theme of this talk was how to use automated code analysis to direct you on where to spend your refactoring cycles. He used Carlin’s law (Anyone going slower than me is stupid; anyone going faster than me is crazy), but applied to programming. As your programming skills change over time, you see the same code differently.

He touched on coverage as a baseline that you should be doing as a part of your code analysis, then went on to complexity analysis, reviewing two tools available to analyze the “complexity” of your code: Flog and Saikuro. Flog examines your code (flog -g app for a Rails app) and gives you a (somewhat arbitrary) numeric range measuring the relative complexity of your code. Basically, 0-10 is awesome (and practically unatainable), 11-20 is okay for real world methods, and it goes downhill from there. If you have 200+ complexity scores, refactor immediately! Flog is somewhat opinionated about what is good/bad or more/less complex, but generally does a good job in helping you avoid the “icebergs”.

Saikuro gives a more concrete result—the “score” is the number of branches through a method, including tertiary operators, foo if/unless bar, etc. This is a plus over Flog, and usually indicates about how many tests you should have (one per branch). The downside to Saikuro is that it does not pick up on dynamically defined methods, where Flog does.

Next, we walked through a refactoring example, where Jake showed using high Flog scores as a hit list of where to refactor next. He also mentioned that better readability trumps lower complexity scores, one thing to keep in mind—as being generated by automated tools, the scores should be taken as a guide, not a law. A good point was brought up during Q&A: there is currently no way to “flag” a high-scoring method as acceptable, so if you have a justifiably complex method that you choose to live with (e.g. for readability), then you’ll have to live with the flogging you will receive. I’m sure patches would be welcome if someone wanted to fix this!

On to code smell and Reek and Roodi, tools to identify smells (overly large methods, etc.) Reek tends to warn over smaller issues than Roodi, and can indicate false positives. Roodi generally tends to have fewer complaints—if it warns about something, it should probably be fixed!

Next up was Flay, which detects non-DRY-ness in code, anything from strict copy-n-paste to functionally identical blocks with different variable names to do..end blocks matching curly-brace blocks.

Also covered was a way to track source control churn. At this point, you’re probably thinking “How can I keep up with all this?” Luckily, there’s metric_fu, a way to wrap all this up into one package and get all this code analysis goodness in your project. Install the gem, then run rake metrics:all. For more info, installation instructions, etc., see: http://metric-fu.rubyforge.org/ Looking forward to adding this bag of tricks to our CI toolset.

Rails 3: Step off of the Golden Path – Matt Aimonetti

Matt started off with a history of programming languages and how Ruby came to be, including some of Matz’ core philosophies embodied in the language. Moving along to Rails, he talked about the growth of Rails and the desire for increased performance and options that led to the split between Rails and Merb. This led us in to the discussion of the current and future state of affairs for Rails 3.

Currently, as DHH mentioned in the opening keynote, there is no official release for Rails 3. However, much work has been done, and a direction / ideas are emerging that will be implemented once an official release is ready. These include:
  • improved performance
  • increased modularity
  • agnosticism
  • public api
  • mountable apps

Matt emphasized that there will be no drastic changes, and by default, rails app will generate a very similar application to what you would get today under 2.x. However, there will no longer be the idea of “the one true Rails way” of building an app—the framework will be less opinionated. However, you should go through a process of justification to see if you really need something different than the default stack.

Some of the options you will be able to choose from:
  • JavaScript frameworks, including jQuery, YUI, ExtJS, MooTools, Prototype, or the ability to write your own, and plug it in.
  • Different templating engines: HAML, ERb (this is already doable in Rails)
  • Different ORMs: ActiveRecord, DataMapper, SEQUEL, Hibernate, non-RDBMS stores like CouchDB, Tokyo Cabinet, etc.
At this point, Matt gave a demo of some of the nicer features in DataMapper, contrasted with ActiveRecord:
  • DataMapper re-uses existing Ruby object for both sides of a has_many / belongs_to relationship. In other words, if I load parent and child records from the database, and look at parent.object_id as compared to child.parent.object_id, under DataMapper, these will point to the same object automatically, while with ActiveRecord, these will be separate objects. (Note that inverse_of was recently checked into rails, which enables this in ActiveRecord as well )
  • DataMapper does automatic lazy loading as well as strategic eager loading, so in this scenario:
@parent = Parent.find(12345)
@parent.children.each do |child|
  puts child.name
end
ActiveRecord would need some hints (:include => :children) to be added to the original query to avoid the N+1 iteration problem, where DataMapper is clever enough to figure that out and generate 2 SQL queries for you automatically.
  • The ability to have multiple repositories (which looks like it means databases), and a copy method on models to clone data from one database to another—one use case would be an automatic archive or backup process that copies data generated within the last week to a backup database.
  • Query Path, allowing more flexibility in SQL condition generation (WHERE name LIKEfoo‘)
  • one potential gotcha that was mentioned: DataMapper does not support STI and Polymorphic associations as well as ActiveRecord does
Finally, he highlighted some options that would be available for even further customization, such as defining your own:
  • file structure
  • router DSL
  • request handling But he voiced the opinion that the vast majority of Rails apps will not need anything like this—make sure your need justifies coloring outside the lines.

All in all a good presentation, maybe a bit much focus on DataMapper specifically. However, I personally enjoyed the DataMapper bits, and might have to try it out on a project, if it’s a fit.

Art of the Ruby Proxy for Scale, Performance, and Monitoring – Ilya Grigorik

I skipped out on the afternoon sessions, so my next talk was Ilya’s—never disappointing. Ilya spoke about EM-Proxy, his event machine based proxy. He gave good example code of how EM proxy could be used to implement transparent and intercepting proxies.

It started with an itch at PostRank, Ilya’s blog aggregation solution. An effective staging environment should closely resemble the production environment—the problem was that their production environment spanned nearly 80 (virtual) servers on EC2’s cloud. Spinning up that many servers just as a staging environment was an expensive proposition. Also, simulating production traffic then becomes a challenge, as you end up trying to store production logs and “replay” them into the staging environment. The way that they chose to solve the problem was to separate a group of the servers into a staging app server pool, set up a proxy that would transparently (to the end user) intercept incoming requests, send them to both the production and staging pools simultaneously, then return only the production response to the user, using the staging response internally for benchmarking, testing output, etc. With this strategy, the more static parts of the system (web servers, load balancers, etc.) can be shared across environments, and the staging environment is testing the part that actually changes (the application servers).

The first example code was a transparent proxy that simply forwarded a request from one port to another. Ilya built on this to show how you could dynamically alter request/response data on the fly. Finally, he built up to the original scenario: duplexing a single request across two (or multiple) backend servers, but returning only a specific response. As he mentioned in the talk, one strategy for servicing a specific request as fast as possible might be to send the request to all machines in your pool, then respond with whichever request completed first.

These examples were centered around HTTP requests, but he went on to show some other examples of how this is not protocol-specific: you are just dealing with data over a socket connection, so as long as you understand the underlying protocol, EM-Proxy could be useful. His examples showed SMTP proxies for accepting/rejecting incoming mail by email address and implementing a spam filter by forwarding the incoming mail to Defensio before passing it along to your real SMTP server. The final example was pretty clever: an implementation of EM-Proxy to reduce the memory overhead of beanstalkd by selectively delaying queue inserts based on the scheduled execution time—basically buffering far future jobs into the database instead of immediately inserting into the work queue.

Slides are available here: http://bit.ly/ruby-proxy

Another packed day at RailsConf 09, one more to go!


more »

A Public “Thank You” »

Created at: 06.05.2009 09:04, source: Rails Dog, tagged: Uncategorized github phusion railsconf resource_controller

@GreggPollack put together an excellent RubyHeroes presentation before the keynote.  In addition to recognizing some of the great contributions these individuals made, Gregg suggested that we all take a moment to thank at least three people whose work has made our lives that much easier.  So instead of getting caught up in minor complaints about the accomodations or speeches, I decided to throw out some more positive energy.

  1. GitHub - I’m not going to waste a lot of space talking about how much of an impact GitHub has made on the Rails community.   Its not like these guys are toiling away in anonymity but their contribution has been so important that I’m just going to go on record as saying “Thanks.”

  2. Phusion - Again, everyone knows what these guys have done for simplifying Rails deployment.  Just because they get plenty of “Thank Yous” doesn’t mean I can’t throw my own two cents in here.  I also had the opportunity to thank one of the Phusion guys in person at dinner this evening.

  3. ResourceController - James Golick’s plugin finally convinced me to embrace REST.  If you’re not familiar with it, its a great way to simplify the implementation of your standard RESTful controller.  My controllers became way more DRY as a result.  Again, saw James at dinner and shook his hand in person but it doesn’t hurt to say it here.

Honorary Mentions:

  • DHH and RailsCore for Rails (DUH)
  • Chad Fowler and company for organizing RailsConf
  • Gregg Pollack for the Ruby Heroes presentation, conference videos and the entertaining RailsEnvy podcasts (along with Jason Seifer.)


more »

RailsConf Kicks Off »

Created at: 06.05.2009 08:28, source: Rails Dog, tagged: Uncategorized railsconf

Well today was the first day of talks here at RailsConf.  DHH kicked things off with an opening speech.  He spent some time talking about Rails 3.0 features but unfortunately it was hard to follow the slides in the back.  Somebody on #railsconf thought it would be cool if you could broadcast slides to everyoene’s laptop during the live talk.  That would have come in handy for this.

The talk was good despite the sound and slide difficulties.  I always enjoy hearing how other programmers approach the challenges of their job.  DHH was talking about how “renogiation of requirements” can ultimately lead to a huge productivity gain.  He described a time at 37 signals where he spent two weeks trying to solve an impossible task.  He ultimately came up with a much simpler solution and proposed it to the client.  Client was indifferent (”Sure, whatever”) and he was done in 48 hours.

The talks this morning have been pretty good so far.  Mercifully there is no smoking in the conference center so that is a welcome change of pace from the rest of the hotel.  My main complaint so far would be that the chairs have metal backs with no cushion so they’re extremely uncomfortable.

One last thing I would like to mention is the state of the Rails community.  There are lots of first time RailsConf attendees here this year which is a great sign.  People also seem to be mixing a lot better instead of hanging out exclusively with the people that they came here with.  The Rails community really seems to be moving in a more positive direction, despite minor flare ups and distractions along the way.

I really think the whole Rails - Merb merger sets a good example for how much everyone stands to gain when setting aside ego and just work together to write the best possible software.  Constructive criticism is fine but collaboration is even more productive.


more »

Vegas: First Impressions »

Created at: 06.05.2009 00:20, source: Rails Dog, tagged: Uncategorized railsconf

I’ve been in dozens of airports around the world but stepping off the plane at LAS conveys the immediate impression that you have arrived somewhere different.  The first thing you see as you come out of the jetway are tons of slot machines.  I have nothing nice to say about the airport ground transportation options.  I used the 30 minute ride to my hotel (which was like 5 miles from the airport) to come up with about half a dozen ways to design a better system.  You can start by knocking down the worthless fucking monorail that they have and replace it with a proper light rail system that would actually connect people to the one place everyone wants to go - the airport!

Went out last night with @hackerchic, @tunagami and Sonny (twitter account not shown.)  Took the afore mentioned monorail to the MGM where we had a good time at the Centrifuge bar.  Every 20 minutes or so some dance song would come blasting on and the bar tenders would all jump up on the bar and start dancing.  So that seemed to be a pretty authentic Vegas experience.

Cigarette smoking is completely out of hand here.  I’m really not used to people smoking indoors and it seems to be everywhere.  My eyes and throat are really irritated from all of the second hand smoke.  On the plus side, you can drink beer anywhere you want (including in the middle of the street.)  Its kind of strange to be drinking a beer while in line to check in to your hotel (next to the guy smoking a cigarette.)  Even stranger is the notion of just walking outside with a giant 32 oz. beer in your hand.


more »