John Medina – Ruby on Rails Podcast

Developmental molecular biologist Dr. John Medina talks about his new book, Brain Rules. Learn about the need for exercise, attention-grabbing events, and our inability to multitask.

John Medina – Ruby on Rails Podcast

Developmental molecular biologist Dr. John Medina talks about his new book, Brain Rules. Learn about the need for exercise, attention-grabbing events, and our inability to multitask.

gemedit version 0.0.1 has been released!

Check out my first published gem: gemedit

A utility to view a gem’s source in your favorite editor

Changes:

<ol>
    <li>0.0.1 2008-02-27</li>
</ol><ul>
<li>1 major enhancement:
<ul>
    <li>Initial release</li>
</ul></li>

Specials thanks go to the following gems for making it easy to put this out there:

WebSnapshot and RailsLogVisualizer ported to AIR 1.0

I ported the WebSnapshot and RailsLogVisualizer application to AIR 1.0

20080225_WebSnapshot.jpg

20080225_RailsLogVisualizer.jpg

Enjoy,
Daniel

#94 ActiveResource Basics

ActiveResource allows you to easily communicate between multiple Rails applications. See how in this episode.

#94 ActiveResource Basics

ActiveResource allows you to easily communicate between multiple Rails applications. See how in this episode.

Something in the AIR?

360Flex in Atlanta starts this monday. I was at the first 360Flex conference last year and it was a blast. I will miss going to that one. Also it seems that many Flex User Groups meetings around the world (Atlanta, Bangalore, London, Denver, Amsterdam) will held on this monday. When so many planets will align perfectly something special is bound to occur.

So more specifically from the Special Meeting invites:

  • Exclusive user group video presentation by Adobe Chief Software Architect, Kevin Lynch
  • In-person presentation from Adobe Platform Evangelist, Kevin Hoyt
  • And…important product news!

That can mean only one thing. It’s gonna be soon time to recompile all my apps 😉

Update 1: the Denver meeting is not on the 25th but on March 11th.
Update 2: Ted Patrick announces yesterday that the Flex 3.0 and AIR 1.0 releases is days away.
Update 3: Flex 3.0 and AIR 1.0 are out. Go try out FlexBuilder if you haven’t yet, it’s the easiest way to get started.

Heroku.com – An impressive online Ruby on Rails Platform.

You’ve have to try it to believe it. It’s awesome that you can create a Rails application and deploy it all online. Nothing to install, it’s all there. I think it’s an awesome addition to the Rails world. It may not replace your development environment, but for deployment it’s pretty flexible and is based on Amazon EC2.

From their website the feature description is as follows:

  • Instant Deployment
  • Create and Edit Online
  • Integrated Stack
  • Elastic Performance
  • Share and Collaborate
  • Import & Export
  • Full Ruby Environment
  • Gems & Plugins
  • Rails Console
  • Generate Code
  • Painless Migrations
  • Rake Console

But you gotta see this to believe it. I made a quick screencast, so if you are not scared of a thick (swiss) french accent, have a look: (click image to open screencast in separate browser):

20080220_HerokuSmall.jpg

I can foresee, at least hope, that they will quickly add support for subversion and for Capistrano based deployment, hence becoming the ultimate deployment platform for Rails in addition to the powerful and flexible environment they already provide.

I signed up and received my invite three days later. If you can’t wait send me an email daniel[at]onrails.org, and I sign you up, that will allow to skip the wait.

Enjoy,
Daniel.

Dealing with HTTP errors in a Flex with Rails application.

The Flash Player is restricted in the way it deals with HTTP errors. This is mainly due to provide cross browser consistency and I believe is due to the restrictions the browser imposes on the Flash Player plugin. In fact when your Flex application performs HTTP requests using the HTTPService class, the request is passed by the Flash Player to the browser and in case of an Rails error (500, 404, …) the response is somehow crippled on the way back.

Problem

So let’s consider that the Flex application requests to update a Person but the validation fails. In the update method of our Rails controller the HTTP Status is set to :unprocessable_entity. This corresponds the HTTP error code 422.

  1. PUT /people/1
  2. PUT /people/1.xml
    def update
    @person = Person.find(params[:id])

respond_to do |format|
if @person.update_attributes(params[:person])
flash[:notice] = ‘Person was successfully updated.’
format.html { redirect_to(@person) }
format.xml { head :ok }
else
format.html { render :action => “edit” }
format.xml { render :xml => @person.errors, :status => :unprocessable_entity }
end
end
end

Now in our Flex application by default we cannot identify that the error 422 occured, more annoyingly we cannot retrieve the Rails error messages. All we get back is the following:

[FaultEvent fault=[RPC Fault faultString=“HTTP request error” faultCode=“Server.Error.Request” faultDetail=“Error: [IOErrorEvent type=”ioError" bubbles=false cancelable=false eventPhase=2 text=“Error #2032: Stream Error. URL: http://localhost:3000/people/8.xml?_method=put”]. URL: http://localhost:3000/people/8.xml?_method=put"] messageId=“65EBBA92-5911-68D2-1710-18A687C28455” type=“fault” bubbles=false cancelable=true eventPhase=2]

Solution

I haven’t found a way to have the status code and error message appear in the Flex application without having to change the Rails application. But fortunately, I was able to deal with that by using an after_filter at the application controller level, hence having only one place in the application to take care of all controllers and requests. The trick is to “hide” the HTTP Status error code in Rails and as the Flex application deals with XML responses, simply check in Flex if the response starts with <errors>. This can then also be dealt with in the Flex application in one place of the application. In a Cairngorm application I had the Delegate transform these “errors” responses to Faults.

Here is an example of the change to the Rails ApplicationController.

class ApplicationController < ActionController::Base
after_filter :flex_error_handling

def flex_error_handling
response.headers[‘Status’] = interpret_status(200) if response.headers[‘Status’] == interpret_status(422)
end

def rescue_action_in_public(exception)
render_exception(exception)
end
def rescue_action_locally(exception)
render_exception(exception)
end
rescue_from ActiveRecord::RecordNotFound, :with => :render_exception
def render_exception(exception)
render :text => “#{exception}”, :status => 200
end

end

Flexible Rails: A book on using Flex with Rails.

As many of you know I really enjoy using Flex with Rails. So I finally picked-up a copy of FlexibleRails which is written by Peter Armstrong and started browsing through it last week-end. For anyone out there trying to enrich their application with some Flex or even writing the whole UI in Flex, check out this book as it’s a good starting point and Peter addresses many of the aspects that you will be faced with. Peter goes through several iterations of creating an application and introduces the reader to using Flex against a RESTful Rails application, he refactors the application to Cairngorm, uses AMF. So congratulations Peter of getting this done!

MicroPlace – Ruby on Rails Podcast

An eBay-funded microfinance company connects small investors with entrepreneurs in the developing world, powered by Rails.

MicroPlace – Ruby on Rails Podcast

An eBay-funded microfinance company connects small investors with entrepreneurs in the developing world, powered by Rails.

#93 Action Caching

Action caching behaves much like page caching except it processes the controller filters. You can also make it conditional as seen in this episode.

#93 Action Caching

Action caching behaves much like page caching except it processes the controller filters. You can also make it conditional as seen in this episode.

Sugary Adapters

Very recently, Simon Harris had an idea: nil? for Ambition. Tasty sugar.

Let’s figure out what it takes to make

User.select { |x| x.nil? }

behave just like

User.select { |x| x == nil }

in Ambition.

Short and Sweet

Simon’s approach was to modify Ambition directly to add support for nil?. While this is for sure ambitious, nil? is just another method. Not special. The adapter should decide what to do with it.

Easy. Here’s what we added to the ActiveRecord adapter’s Select translator:

def nil?(column)
  left = "#{owner.table_name}.#{quote_column_name column}" 
  negated? ? not_equal(left, nil) : self.==(left, nil)
end

See it in action on lines 84 to 87.

The tests, of course, can be found in types_test.

Chaining Stuffs

So, how does this work?

Every adapter’s Select translator has a special chained_call method. Ambition invokes chained_call and passes it an array of symbols when a chained.method.call is executed on itself.

In this case, the chain is m.name.nil?. Ambition knows that m is itself and ignores it, passing [ :name, :nil? ] to chained_call.

The ActiveRecord adapter’s chained_call method takes the passed array and, if it can find the second element, sends it the first element.

Basically:

# methods = [ :name, :nil? ]
if respond_to? methods[1]
  send(methods[1], methods.first)
end

Which translates to:

self.nil? :name

Cool. Adapters don’t need to set themselves up this way, but it works for ActiveRecord.

Notice: the ActiveRecord adapter doesn’t support anything more than chains two methods deep. It calls the second element and passes the first, ignoring the rest. Almost discouraging, but chin up – this is ActiveRecord specific. Ambition itself supports chains of arbitrary length, and your adapter can, too.

So array.include?, right?

The thing is, chained_call is only invoked when a chained method call is executed on an object Ambition owns.

User.select { |x| x.nil? }

In the above, Ambition owns the x. It’s self as far as the translator is concerned.

User.select { |x| [1,2,3].include? x.id }

Ambition does not own the array, only the x.id. So what happens?

Well, it’s the same as [1,2,3] == x.id to Ambition. The dude really doesn’t care. Any time there is something like left op right, Ambition calls op(left, right) on your translator.

Here’s an idea of the call:

include?([1,2,3], x.id)

Luckily x.id is translated for you prior to this. The call really looks more like:

include?([1,2,3], 'users.id')

The include? definition, then, on ActiveRecord’s translator is very straightforward:

def include?(left, right)
  left = left.map { |element| sanitize element }.join(', ')
  "#{right} IN (#{left})" 
end

Beautiful.

Join the Fun

While the Err twitter is great for general stuff, you should really hop on the Ambition mailing list if you want in on this action. Or just watch the project on GitHub.

Til next time.

#92 make_resourceful

The make_resourceful plugin is a great way to DRY up the 7 RESTful actions common in most controllers. Learn how to use it in this episode.

#92 make_resourceful

The make_resourceful plugin is a great way to DRY up the 7 RESTful actions common in most controllers. Learn how to use it in this episode.

Heroku – Ruby on Rails Podcast

What if your server resources were metered like your electric bill? Heroku has set out to build a metered cloud computing deployment solution for Rails.
Stick around for the last 10 minutes where we talk about the economics of startups.

Heroku – Ruby on Rails Podcast

What if your server resources were metered like your electric bill? Heroku has set out to build a metered cloud computing deployment solution for Rails.
Stick around for the last 10 minutes where we talk about the economics of startups.

Mediacast Deployment Diagram

During our last meeting, Arun suggested that I publish the high-level deployment diagram of mediacast.sun.com. So here it is:

I described everything in textual form in my previous blog entry about mediacast.