strapyourself.in and flouri.sh

Rendering views without a web request in rails

November 13th, 2007

Why the heck do you want to do that?

Views are very well integrated into the rails framework, but they're only typically rendered when an http request comes in. ActionMailer is the main exception, but what if you want to render a view for use in another backend application? These days, document fragments are being used everywhere, and often times I'll need rendered HTML for a use other than just sending it back to the requesting user.

A solution: instantiate a controller and view

Controllers are just objects, and so are views. We can instantiate a controller, instantiate a view, then point the view to the controller and we're ready to go. The only think we're missing is the session and the request objects, but not every view needs those. I used this once for updating a facebook profile using a backgroundrb worker:

class FakeView < ActionView::Base
  include SomeHelper
  include SomeOtherHelper
end

class FakeController < ActionController::Base
  def render_some_view
    action_view = FakeView.new(File.join(RAILS_ROOT, "app", "views"), {})
    action_view.instance_variable_set("@controller", self)
    markup = action_view.render(:partial => 'facebook/your_profile')    
  end
end

By subclasses ActionView::Base, you can mix helpers into the view class, making their methods available.

Another solution: use the test framework!

The rails TestProcess is the only place where views are rendered. If you really want to simulate a real experience when rendering a view, use the test process. First, you'll need an actual controller with an actual action you want to render in it, like this one:

class FacebookController
  before_filter :login_required
  
  def your_profile    
  end
end

Then, we create and instante a test as follows:

class FacebookTest
  include ActionController::TestProcess
  attr_reader :response
  
  def initialize
    require_dependency 'application' unless defined?(ApplicationController)
    @controller = UserScheduleEntryController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
  end
  
  def render_your_profile(user)
    @controller.instance_variable_set("@user", user) # bypass login required
    get :your_profile
    @response
  end  
end

test = FacebookTest.new
test.render_your_profile(user)
markup = test.response.body

The require_dependency was something I threw in because backgroundrb didn't have some of the required classes loaded at that point, it may not be something you need in your application.

I originally posted this article on ELC's blog

Duplicate Migrations in Rails

November 6th, 2007

Why we need duplicate migrations

Have you ever been working on a large project, and had people check in migrations with the same numbers? It's happened to me probably no less than 10 times in the last year. In each case, the situation is recoverable, but sometimes requires a lot of manual rolling back of specific migrations on possibly several machines. Then you have to renumber all the migrations after the conflict, of course.

An even worse situation is when a project is branched and remerged. For example, you might want to branch out several complicated features from trunk for a few weeks, then bring them back when complete. Assuming you create 2 feature branches (for adding profiles and friends to your users), you could end up with something like this:

  • 036_modify_users_to_include_first_name.rb
  • 037_create_profiles.rb
  • 037_create_friendships.rb
  • 037_fix_a_bug.rb
  • 038_add_timestamps_to_friendships.rb
  • 038_modify_accounts_to_limit_length.rb
  • 039_modify_users_to_include_gender.rb

In the above situation, the person merging the two branches has a very difficult situation ahead. Everyone working on the project is probably on revision 37 (profiles branch), 38 (friends branch), or 39 (trunk). The safe way to proceed with traditional rails migrations is to force all machines be migrated down to 36. No new migrations can be added while the migrations are then renumbered so they range from 036 to 042. Finally, all users can update from trunk and run rake db:migrate. Of course, people often forget to migrate down, and end up stuck in the middle of a sequence of migrations that has been renumbered (I am so tired of reversing migrations by hand).

Solution: Allowing duplicate migration version numbers

In the above example, the 3 migrations numbered 37 are not dependent in any way. Because they had to be developed independently, duplicate version numbers are very rarely dependent. For this reason, we beleive that it is usually safe to create a "partial ordering" of migrations rather than an exact ordering. In this partial ordering (which can be represented as a lattice), migrations with the same version number will be run in an arbitrary order:

lattice

Since all of the dependencies in the above lattice flow downward, we can satisfy the partial ordering by running the migrations alphabetically by filename, alphabetizing them first by version number and then by class name. This will only work if we can make the assumption that when new migrations are added, they can only be dependent on those with smaller version numbers.

How the plugin works

Traditional rails schema_info table cannot hold enough information to keep track of which migrations have been run, so we need to adopt a new schema format, which we place in a new schema_infos table:

schema_infos schema

In this new schema, every record represents a migration that has been run. By traversing this table, we can get an accurate picture of the state of the system, and decide which migration to run next.

If we want to migrate to version 10, for example, we create an alphabetical listing of migrations up to and including version 10(s). Then we traverse that list in order, running "up" on migrations which have not been previously run, and inserting a record into schema_infos. Finally, we create a list of migrations with version numbers larger than 10, and run "down" on those in reverse alphabetical order, removing the entries in schema_info.

A little under the hood

Below is the main migrate function. It does exactly what is discussed in the previous section:

def migrate_with_duplicates
  migration_classes_before(@target_version).each do |(version, migration_class)|    
    next if schema_information_contains?(migration_class)
    ActiveRecord::Base.logger.info "Migrating up #{migration_class} (#{version})"
    migration_class.migrate(:up)
    insert_schema_information(migration_class)
  end
  
  migration_classes_after(@target_version).each do |(version, migration_class)|              
    next if !schema_information_contains?(migration_class)
    ActiveRecord::Base.logger.info "Migrating down #{migration_class} (#{version})"
    migration_class.migrate(:down)
    remove_schema_information(migration_class)
  end
end

What would be even better...

I've always wanted to write a migration system based on partial orderings where dependencies are explicit, and version numbers are history. Such a system would work nicely on top of the new schema_infos table format. The tricky part would be how to state the dependencies without forcing the migration author to work too hard.

Download

From the ELC plugin repository: http://wush.net/svn/public/plugins/duplicate_migrations

To install:
./script/plugin install -x http://wush.net/svn/public/plugins/duplicate_migrations
(installing automatically creates the schema_infos table and populates it, but does NOT delete your old schema_info table... don't panic!)

Originally posted on ELC's blog

Writing view helpers with 'yield'

November 3rd, 2007

Ever wanted to pass in blocks of view code to a helper? Think of the power! Say we want to make a helper method which surrounds whatever block you pass in with a firefox html designer iframe, here's how I'd imagine a user would want to use it:

<% html_editor(:width => 600, :height => 400) do %>
  <p><b>This html should be editable by the user!</b></p> 
<% end %>

Here's how you could write such a helper function:

class ApplicationHelper
  def html_editor(options = {}, &block)
    concat("<IFRAME WIDTH=#{options[:width] || 400} HEIGHT=#{options[:height || 200]} ID=myEditor>")
    yield
    concat("</IFRAME>")
    concat("<script>frames.myEditor.document.designMode = 'On'</script>")
  end
end

Notice that I pass the block in as the last parameter "&block", but I never use it in the function! Ruby doesn't require that you pass the name of the block in when you yield, because it only supports the passing in of 0 or 1 blocks to a function (hence it always knows which one you're talking about). I like to pass it in as a named method parameter because it makes the method signature more clear.

Now let's improve on our initial version, by passing an object back to the view. This is exactly the way form_for passes back a |form| object to the view. Our updated use case is as follows:

<% html_editor(:width => 600, :height => 400) do |editor| %>
  <p><b>This html should be editable by the user!</b></p>
  <% editor.command_button("Bold", "bold") %>
<% end %>

The "command_button" method above should insert a standard html button with the text "Bold" that executes the "bold" command on the selected text range inside the html editor. Let's see how this can be implemented:

class JsHtmlEditor
  attr_reader :output
  def command_button(name, command)
    @output ||= ""
    @output << "<button 
        onclick='javascript: frames.myEditor.document.selection.createRange().execCommand(\"#{command}\")'>
        #{name}</button>\n"
  end
end

module ApplicationHelper
  def html_editor(options = {}, &block)
    editor = JsHtmlEditor.new("myEditor")
    concat("<IFRAME WIDTH=#{options[:width] || 400} HEIGHT=#{options[:height || 200]} ID='myEditor'>")
    yield editor
    concat("</IFRAME>")
    concat("<script>frames.myEditor.document.designMode = 'On'</script>")
    concat(editor.output) unless editor.output.blank?  # stick the user buttons at the bottom
  end
end

Pretty cool huh? When we create a new editor and yield it, we make its methods accessible to the view block. In this example, the user can execute editor.command_button whereever they want inside the block, but we collect the output of those statements and force them all to the bottom of the iframe (where they probably belong).

Another common use of blocks inside view helpers is simply to control whether or not they get yielded at all. If you don't call yield, the block never executes and never gets rendered. Often times we have complex conditions determining when a certain block of code should be rendered, and this approach can clean that up immensely.

I work at ELC

November 2nd, 2007

I've been working at ELC Technologies/Rightcart.com since February of 2006... and I love it there! In this section of my blog, you'll find all the posts that I did on the request of ELC.

original design by gorotron ported by railsgrunt powered by mephisto