RailsBlaster

RailsBlaster has moved!

December 21, 2007 · Leave a Comment

We’ve moved! We’re going to be hosted at http://www.nuclearpanda.com. This blog will remain here for Google’s sake.

→ Leave a CommentCategories: Uncategorized

AJAX forms and file uploading in Rails

September 20, 2007 · 3 Comments

One very nice thing about Ruby on Rails is the support for AJAX. I consider myself a backend guy, so I don’t generally like to touch Javascript (though I’ve written my fair share of XMLHttpRequest calls without the help of frameworks – which is probably why I dislike Javascript so much).

 

The other day I was working on AJAXifying some forms, because it didn’t make sense to refresh the entire browser window for these functions. Here’s my original view:

<% form_for :message, :url =>{:controller => :message,:action => :post },
:html => { :multipart => true } do |form| %>
<% fields_for :image do |image| %>
<%= image.file_field :file_data, :size => 20  %>
<% end %>
<%= form.text_area :body, :cols => 40, :rows => 2 %>
<%= submit_tag "Send", :class => :submit %>
<% end %>

Pretty straightforward stuff. The controller method wasn’t much more complex:

MessageController.rb

def send
if request.post?
  @message = Message.new(params[:message])
  unless params[:image].blank? or
    params[:image][:file_data].blank?
    @message.images << Image.new(params[:image])
  end
  @message.save
end
end

I won’t get too much into the Message or Image models; these can be found anywhere. A decent Image model is available inside the Rails Recipes book. As a rule of thumb, NEVER start your development with AJAX. Javascript can be a harsh mistress, and you’re better off degrading to a non-AJAX page that fully functions rather than running into Javascript problems and having to rebuild anyway.

The very first thing I did was change the form. Instead of using form_for, I changed it to form_remote_for. No problems!

<% form_remote_for :message, :url => {:controller => :message, :action => :post },
:html => { :multipart => true } do |form| %>
<% fields_for :image do |image| %>
<%= image.file_field :file_data, :size => 20  %>
<% end %>
<%= form.text_area :body, :cols => 40, :rows => 2 %>
<%= submit_tag "Send", :class => :submit %>
<% end %>

As you can see all I’ve done here is change the method name. A quick ‘tail -f development.log’ shows us that the form is indeed being sent to the server. But what is the point of AJAX without some crazy cool thing going asynchronously? Rails makes this easy too:

<% form_remote_for :message, :url =>
 {:controller => :message,
 :action => :post },
 :loading => "Element.show('status')",
 :success => "Element.hide('status')",
 :html => { :multipart => true } do |form| %>
<% fields_for :image do |image| %>
 <%= image.file_field :file_data, :size => 20  %>
 <% end %>

<%= form.text_area :body, :cols => 40, :rows => 2 %>
<%= submit_tag “Send”, :class => :submit %>
<% end %>

<div id='status' style='display:none;'>Sending ...</div>
<div id='last_sent_message' style='display:none;'>
</div>

Let’s also make the controller render an RJS template:

send.rjs

page.replace_html “last_sent_message”, :partial =>’message’, :o bject => @message

Again, I won’t bore you with the details of the partial or the models. For the most part, this did what I needed it to do … until I tried to upload an Image. Exception throwing time …

This is where Google comes in. The best link I could find for Rails AJAX file uploading was Dave Naffis’s Rails blog:

http://www.naffis.com/2006/12/11/ajax-uploads-image-manipulation-drag-and-drop-sorting#comments

The primary takeaway here is that pure Javascript form uploading is impossible because Javascript does not have access to a client filesystem (for security reasons), and thus, file form fields. To work around this, sites that allow “AJAX” file uploads are actually posting to an IFRAME, not sending the file via XHR.

Dave does a pretty good job, but as he says in his blog, he wrote the code in about 20 minutes. To allow AJAX like file uploads, you must do the following:

1. Install the Responds to Parent plugin. This allows any RJS rendered in an IFRAME to access the DOM of the parent document. This is not mandatory, but it allows the POST response to manipulate the main page to show that an upload completed (or whatever … ).

http://agilewebdevelopment.com/plugins/responds_to_parent

To install, type:

ruby script/plugin      http://sean.treadway.info/svn/plugins/responds_to_parent/

2. Create a file called ‘remote_uploads.rb’ in your lib/ directory. Dave Naffis has a version of code on his site, but I’ve gone the extra step and modified it a bit:

module ActionView
  module Helpers
    module PrototypeHelper
      alias :form_remote_tag_old :form_remote_tag
      def form_remote_tag(options = {}, &block)
        unless options[:html] && options[:html][:multipart]
           form_remote_tag_old(options, &block)
        else
          uid = "a#{Time.now.to_f.hash}"
          <<-STR    
true})}” enctype=”multipart/form-data” target=”#{uid}” #{%(onsubmit=”#{options[:loading]}”) if options[:loading]}> STR end end end end end

There were two problem with the original code, at least for me. First, nothing inside the form_for{} block was being rendered for some reason for a regular, non-multipart form. The method has been changed to accept &block as a second parameter, and pass this along appropriate to form_for.

The second problem was that, for whatever reason, in the original code, form_remote_tag_old just seemed to never get called. I didn’t have time to debug this, and I’m going to be accused of being incomplete, but reversing the IF and the UNLESS solved this problem for me.

3. Add

require 'remote_uploads.rb'

To environment.rb.

4. Change the controller action to render the response in a responds_to_parent block:

def send
  if request.post?
    @message = Message.new(params[:message])
    unless params[:image].blank? or
        params[:image][:file_data].blank?
      @message.images << Image.new(params[:image])
    end
    @message.save
    responds_to_parent do
      render :action => 'post.rjs'
    end
  end
end

5. Restart your server to load the environment.rb changes.

Voila! You are done. More importantly, “AJAX” form uploads are now enabled in the future anytime you call form_remote_tag with :html => { :multipart => true }.

Now go out there and write some form_remote_tag forms with pseudo-AJAX uploads!

→ 3 CommentsCategories: AJAX · ActionView

Ruby Procs: Part I

August 30, 2007 · Leave a Comment

In high school, I had a computer programming teacher who described variables as ‘mailboxes’, with values being ‘postcards’. In my four years of college, I don’t think I’ve ever heard that term or comparison again – though, in retrospect, I think the ‘mailbox’ analogy helped my understanding of more advanced variable topics, such as pointers (a postcard with another mailbox’s address) or pass-by-reference (a postcard with instructions to read another postcard at another mailbox). Interestingly enough, as I became a more advanced developer, I forgot about the mailbox analogy, because I didn’t need it anymore to understand what I was doing.

Recently, I started working with Ruby Procs. Ruby Procs aren’t explained very well, at least not in any book or website I’ve read, so I’ll do my best to explain what a Proc is. Incidentally, I find that the ‘mailbox’ analogy works pretty well again: a ‘Proc’ is a postcard with a set of instructions that the Postman must obey (or, I’d imagine, suffer some horrible fate). Come again? Maybe I need to rewind a bit and talk in code …

Anyone that has been working with Ruby for a bit is familiar with the concept of ‘yield’ and ‘blocks’. First, the block:

array = [1,2,3]

array.each do { |value| puts 'Doing stuff.' }

The code between the brackets {} is a block. This same code can be written as:

array.each do |value|

puts 'Doing stuff.'

end

A block is a block of code, is a block of code, is a block of code. Nothing too special see here.

But let’s combine the block of code with the yield statement:

def is_polygamous?

if yield >= 1

   true

else

   false

end
my_wives = 5

The block of code:

is_polygamous? { my_wives }

Would thus produce true. Yield effectively takes the block of code after the method call, evaluates the code inside in the context of the calling scope, and executes it. This seems kind of pointless – why would anyone write a method this way, when we could simply have passed the value as a parameter? For starters, the code inside the block is not called until the function reaches the yield statement. Let’s look at another example:

def power_rangers_right

    puts 'Go, go'

    yield

end
def power_rangers_wrong(output_method)

    puts 'Go, go'

    output_method

end

Now let’s call each of the methods, passing puts(’Power Rangers!’) as a parameter:

power_rangers_right { puts('Power Rangers!')}

output:

Go, go

Power Rangers!
power_rangers_wrong(puts('Power Rangers!'))

 output:

Power Rangers!

Go, go

As you can see, when you pass a parameter into a method, the code is executed before the method is actually called. When we use yield and code blocks, the execution is deferred until the method reaches the yield statement.

The reason I went into this long winded discussion about blocks and yields is because a function block is a Proc object. The function definition, power_rangers_right, implicitly carries a parameter in the form of power_rangers_right(&proc_object).

The real power behind the Proc, however, is not just that it is a block of code whose execution is deferred. The real power behind Proc is that Proc is a standard Ruby Object. Yes, that’s right, a Proc is a standard Ruby Object and can be passed in a method parameter, people – thus, the mailbox analogy applies. Let’s look at an actual non-trivial example of this in action:

def Lion

end
end
def TinMan

 def Scarecrow

enddef JustinTimberlake

end
def wants?(person_type)

   types_i_know = { :Lion => 'Courage',  :TinMan => 'A Heart', :Scarecrow => 'Brain'}

   complaint = Proc.new { raise ArgumentError("I don't know what #{person_type} wants.")}

   types_i_know.find(complaint) { |person, value| person.is_a?(Object.const_for(person))}.last

end

There’s a lot of code going on here, so I’ll break down what we are trying to accomplish. We want to pass a class of person to a method wants?, which returns what that Person truly desires. To do this, we look up values against a Hash. If we do not know what the person wants, we want to raise an Exception. Line by line, this is what we are doing:

   complaint = Proc.new { raise ArgumentError("I don't know what #{person_type} wants.")}

Remember what I said about Procs just being standard Ruby Objects? Here we are setting the Proc to a variable complaint. We will not raise the Exception unless someone calls this Proc.

   types_i_know.find(complaint) { |person, value| person.is_a?(Object.const_for(person))}.last

Lots of Ruby shorthand going on here. We want to look for the String representing what a person wants, so we want to go through the Hash values and return the first value for which the conditional in the block returns true. To do this, we use the following:

find(value) { |i| condition_with_i }

Find iterates over the contents of the Enumerable, returning the first Object which fulfils the conditions set forth. If no conditions match, ‘value’ is returned. Thus, the code:

array = [1, 2, 3]

array.find(100){ |i| i % 2 =0}

returns 2, and the code:

array = [1, 2, 3]

array.find(100){ |i| i % 4 =0}

returns 100.

Object.const_for(:symbol) takes a symbol and returns a class. The code:

User.find(:all)

could be written as:

type = 'User '

Object.const_for(type.to_sym).find(:all)

Why would you want to do this? I use this almost all the time in my Rake tasks, especially if I don’t know what types of classes I will be dealing with, or if I need to read a Class name from the command line.

person.is_a?(Class)

This is a very handy method. This will return true if person is an instance of the Class or one of a subclass of Class.

Enough beating around the bush. Let’s call some code!

 lion = Lion.new

 jt = JustinTimberlake.new
wants?(lion)

=> 'Courage'

wants?(jt)

=> ArgumentError: I don't know what JustinTimberlake wants.

Wow! What did we just do here? We passed an instance of an Object to a wants? method, which in turn delegated the logic to Enumerable’s find method, returning a Proc Object throwing an Exception if we couldn’t find what the Person wanted – deferred unless no Object was actually returned by find. How insane is that?

Now go out there and write some Ruby.

→ Leave a CommentCategories: Object Oriented Programming · ruby

Rails Controller inheritance and Modules

August 28, 2007 · Leave a Comment

The topic of Controller inheritance may be straightforward for more advanced developers, but it isn’t completely straightforward for people new to Rails or the Ruby language in general.

Rails Controllers generally come in the following flavor:

 class SomeController < ApplicationController
      some_declarations_here

 def public_method
 end

 private

 def private_method
 end

 end

The Rails Controller inherits from a superclass, ApplicationController, which can be found in the app/controllers/application_controller.rb file. Anyone that is familiar with Object Oriented Programming knows, thus, that any method defined in ApplicationController is available in its subclasses. Take the following ApplicationController definition:

class ApplicationController < ActionController::Base
   def dance
   end
end

Now we can access the method ApplicationController#dance in SomeController by way of the URI /some/dance. We can actually this this one step further:

class ApplicationController < ActionController::Base
   layout 'fancy_pickle'
   around_filter :check_for_fanciness

   def dance
   end

   protected

   def check_for_fanciness
      if session[:fancy]
         yield
      else
         render(:text => 'You are not fancy enough'
      end
   end
end

What did we just do here? With a few simple and powerful lines of code, we’ve done all of the following:

  1. We’ve defined a universal default layout for all the controllers in our application. The best part about this is that nothing is set in stone. We can easily override this in a sub controller with the definition:
    layout 'fancier_pickle'
  2. We’ve defined an ‘around_filter’ that gets executed before ALL public actions in ALL controllers. This is very useful for almost any application requiring some kind of authentication or authorization matrix. The ‘yield’ statement is where the method being called is executed. In my example, if the session variable :fancy is set, that is the only way these methods would execute.

Let’s apply this into practice by defining two more controllers:

 class OtherController < ApplicationController

 def sing
 end

 end
 class AnotherController < ApplicationController
     def yodel
     end
 end

What have we done? We’ve defined 2 more controllers that inherit from ApplicationController. That’s right, our Application now has methods at the following URIs:

/some/dance
/some/public_method
/other/sing
/other/dance
/another/yodel
/another/dance

All of which are wrapped in a ‘check_for_fanciness’ around filter.

Let’s add one more level of complexity to our project. Suppose we need a method, ‘drink_water’, in our controllers which Yodel and Sing. One way we could do this would be to define it in ApplicationController, in accordance with DRY principles:

BAD!! BAD!!!

class ApplicationController < ActionController::Base
   layout 'fancy_pickle'
   around_filter :check_for_fanciness

   def dance
   end

   def drink_water
   end

   protected

   def check_for_fanciness
      if session[:fancy]
         yield
      else
         render(:text => 'You are not fancy enough'
      end
   end
end

While this will work, this is horrible style for at least two reasons. First, the method ‘drink_water’ will be available in SomeController, which does not have a Sing or Yodel method. Secondly, any future controllers we define will automatically inherit the method whether they should or not. How do we resolve this issue?

Enter Modules. In C++, we would use multiple inheritance. In Java, we would probably use some combination of Interfaces and Object aggregation. In Ruby, because Ruby is a weakly typed language (officially called ‘Duct Typing” – I’ll probably write about this in a future post), we would import a Module. It’s interesting, actually, that Ruby, which touts itself as such an Object Oriented language, would have a feature like this. For those developers familiar with PHP, this is basically the same thing as defining a bunch of methods in a file and then calling ‘require’ on the file. But – I digress. Let’s solve our problem at hand:

module DrinkMethods
   def drink_water
   end
end

This defines our Module. Let’s save it as drink_methods.rb, in /app/controllers, for simplicity’s sake – but for future reference it probably does not belong in that directly.

Now let’s modify our Controllers that need this method:

 require 'drink_methods'
 class OtherController < ApplicationController
 import DrinkMethods
 def sing
 end

 end
require 'drink_methods'
class AnotherController < ApplicationController
     import DrinkMethods
     def yodel
     end
 end

Voila! Now we have access to the following URIs without introducing unnecessary inheritances:

/other/drink_water
/another/drink_water

Now get out there and write some Ruby.

→ Leave a CommentCategories: ActionController · Object Oriented Programming

has_many :finder_sql

August 27, 2007 · 2 Comments

SQL can be a beautiful thing. That being said, I do try to avoid using native SQL as much as possible when writing applications, because for non-DBA types, it really doesn’t have the most readable syntax in the world.

In ActiveRecord Models, I make heavy use of Models to represent Join tables – this isn’t necessary because of the has_and_belongs_to_many association, however, has_and_belongs_to_many can be very problematic to create Observers for (especially with the limited capabilities of the :after/before_add/remove set of callbacks). In most cases, a HABTM relationship can be defined using only has_many relationships and the :through parameter. Take, for instance, the following representation:

 class ZooTycoon < ActiveRecord::Base
end

Let’s think of the relationships here – a ZooTycoon owns many Zoos, which themselves contain Cages, which have Animals which belong in the cage. Using a minimalist approach, how do we attack this problem such that we can build logical relationships between the different classes? We’d probably do something like this:

 class ZooTycoon < ActiveRecord::Base
	has_many :zoos
 end
 class Zoo < ActiveRecord::Base
        belongs_to :zoo_tycoon
	has_many :cages
 end
class Cage < ActiveRecord::Base
	has_many :animals
	belongs_to :zoo
 end
class Animal < ActiveRecord::Base
	belongs_to :cage
 end

Humanitarian concerns aside, this is more or less an accurate representation of how the classes are represented. Now, in our application, we can do the following to find out all the animals a particular ZooTycoon owns:

joey = ZooTycoon.find_by_name('Joey')
zoos = joey.zoos
cages = zoos.collect {|zoo| zoo.cages}
animals =  (cages.flatten.each {|cage| cage.animals }).flatten

Bear with me, I know there are about a million ways to shorthand this code. What a freakin’ pain! Luckily, we can use the has_many :through association to make this a bit simpler. Let’s redefine zoos to be able to retrieve animals directly, rather than having to iterate through all the cages:

 class Zoo  :cages,
                       :source => :animals
 end

What does this tell our application? It tells us that we don’t need to create a join table between Zoos and Animals; we already have one! The Cages. We can effectively call the following:

joeys_zoos.animals

Yeah, this is nice, but what if we wanted to directly find out all the animals Joey owned? Well, naturally we’d assume we could do this:

DOES NOT WORK:

 class ZooTycoon < ActiveRecord::Base
	has_many :zoos
        has_many :animals, :through => :zoos
 end

It breaks. ActiveRecord is pretty smart, but ActiveRecord isn’t smart enough to correctly create 3 JOINs. If we take a look at the log, we realize that ActiveRecord is trying to directly join the ZooTycoon with the Zoo with the Animals, bypassing the Cages completely. What do we do? Looks like finder_sql to the rescue. SQL can be ugly, but SQL can also be a beautiful thing when you need something very specific:

 class ZooTycoon  'Animal',
                       :finder_sql = 'SELECT * FROM zoo_tycoons
                                           JOIN zoos ON zoo_tycoons.id = zoos.zoo_tycoon_id
                                           JOIN cages ON zoos.id = cages.zoo_id
                                           JOIN animals ON animals.cage_id = cages.id
                                           WHERE zoo_tycoon.id = #{id}'

  end

NOTE THE SINGLE QUOTES. Note the single quotes. Note the single quotes. You MUST use single quotes. To understand why this is, you have to understand that the ‘configuration’ methods in ActiveRecord models are actually function calls that get executed before any Models are actually instantiated. Finder_sql is effectively a function that goes something like, set_some_value_to(’#{self.id}’) that gets called before any Objects are created, so the instance variable @some_value is set to ‘#{self.id}’ rathern than the Object id of the class, which will probably be some ridiculous 11 digit number rather than the Model’s ID. By passing a single quoted parameter, we ensure that the #{id} value substitution happens during an Object’s lifecycle.

What does this mean for us? We can now call:

joey.animals

What’s totally awesome about this is that now we get the entire suite of ActiveRecord methods and callbacks for free! What if Joey wants his animals to be destroyed when he is destroyed? We just append a :dependent => :destroy.

Now go out there and write some Ruby.

→ 2 CommentsCategories: ActiveRecord · SQL