Category: Ruby

  • Generating database migrations with Merb

    I’ve been futzing with the goodness that is Merb lately. It’s nifty. Really nifty. The documentation is pretty rough though. I’ll be posting some of my discoveries here. Maybe it will help someone who, like me, was a tad lost early on.

    One of the first things that confused me was migrations. Merb has script/generate just like Rails, but script/generate --help didn’t list a generator for migrations. When I attempted to generate a migration, I was promptly greeted with this pleasantness:

    $ script/generate migration CreateUsers
    Started merb_init.rb ...
    Loading Application...
    Compiling routes..
    Loaded DEVELOPMENT Environment...
    Couldn't find 'migration' generator
    

    Turns out that Merb doesn’t support databases by default. The Merb-specific ActiveRecord plugin has to be installed and switched on before migrations become available.

    (There are several ORM plugins to choose from as documented in the README, but I’ve had very little success getting the others to work so far.)

    Generate your Merb project:

    sudo gem install merb
    merb my_project
    cd my_project
    

    Install the ActiveRecord plugin thusly:

    sudo gem install merb_activerecord
    

    Now open up config/dependencies.rb and uncomment the following line:

    use_orm :activerecord
    

    The first time you run script/generate after doing this, you’ll get:

    Started merb_init.rb ...
    No database.yml file found in my_project/config.
    A sample file was created called database.sample.yml for you to copy and edit.
    

    Copy config/database.sample.yml to config/database.yml and customize as needed. (Don’t forget to create the test and development databases.)

    Now generate your first migration:

    script/generate migration CreateUsers
    

    And you’re off to the races.

  • Introducing the Lindo (response_visualizer) plugin for Rails

    Being at RubyConf this weekend has provided the necessary motivation for me to finally release a new Ruby gem I’ve been building. It’s an extraction from a project I’ve been working on for Relevance.

    I’m a regular user of assert_select in my functional tests. I find myself frequently doing something like this when the assertion is failing and I can’t figure out why:

    def test_something
      post :something
      raise @response.body.inspect
      assert_select "div[id=header]"
    end
    

    Inspecting the response body usually leads me to a solution, but it’s tedious parsing through the huge amount of HTML that gets returned, often in a semi-unreadable format. Enter the response_visualizer plugin (which has since been renamed Lindo):

    script/plugin install http://github.com/adeptware/lindo/
    

    Or clone the project directly:

    git clone http://github.com/adeptware/lindo/
    

    The plugin provides a vr method to your functional tests. When this method is called, the response body is automatically opened in the default browser allowing for easy visual inspection of the page’s content:

    post :new
    vr
    ...
    

    If you’d prefer to jump straight to the source code, passing the :html symbol will open the formatted HTML in the default text editor:

    post :new
    vr(:html)
    ...
    

    This has saved me a lot of time in figuring out why a specific assertion is failing. Instead of parsing through the HTML, I can view the entire page and immediately tell if something is missing or out of place. I find myself calling vr even before I write my assertions now.

    After installing, check out the README file for additional documentation. There is also a GitHub project if you’d like to contribute a patch or fork the code. Enjoy!

  • Use helpers in your Rails PDF templates

    The Rails PDF plugin is a dandy little thing. It wraps the PDF::Writer library for Ruby, allowing PDF templates to be defined like any other Rails view (with a .rpdf extension, of course).

    One thing it doesn’t do is allow access to the parent controller’s helper from within a PDF template. It’s easy enough to patch the plugin to accomplish this, though.

    First, open up vendor/plugins/railspdf/lib/railspdf.rb and take a gander. This is the section we’re interested in:

    ...
    class PDFRender < ActionView::Base
      def initialize(action_view)
        @action_view = action_view
      end
      ...
    

    PDF templates get rendered in the context of this class. All we need to do to gain access to the controller's helper here is include the helper from inside the class initializer, like so:

    ...
    class PDFRender < ActionView::Base
      def initialize(action_view)
        @action_view = action_view
        prefix = action_view.controller.class.to_s.gsub(/Controller/, '')
        self.class.send(:include, "#{prefix}Helper".constantize)
      end
      ...
    

    We first calculate the prefix of the helper based on the class of the controller assigned to the view. Then we include the helper in the current class by constantizing the resulting string.

    We're almost done. Since ApplicationHelper should be available to every controller and helper in the system, let's include it here for good measure:

    ...
    class PDFRender < ActionView::Base
      include ApplicationHelper
      
      def initialize(action_view)
        @action_view = action_view
        prefix = action_view.controller.class.to_s.gsub(/Controller/, '')
        self.class.send(:include, "#{prefix}Helper".constantize)
      end
      ...
    

    And we're done! Piece of cake. Now we can reference methods from inside our controller's helper. We can, of course, modify this hack somewhat so that the same helper (something like "PdfHelper" maybe) is included for all of our templates. This enables us to isolate our PDF-specific helper methods in a single module.

    And before you ask, yes, it's nasty to be modifying the plugin directly. There is a way to inject this patch into the PDFRender class without touching anything in the plugin... but I've gotta leave something for you to figure out! :)

  • Streamlined turns 0.9

    The latest and greatest version of Streamlined was released a few weeks ago. Lots of new features and bug fixes are included in this release, including a handy (and fully configurable) breadcrumb trail implemented in part by yours truly.

    For those who aren’t familiar with it, Streamlined is sort of like Rails scaffolding on steroids. It lets you quickly and declaratively setup an interface for your ActiveRecord models.

    I continue to be amazed by the amount of code I don’t have to write when I’m using Streamlined. In fact, it’s starting to warp me. Whenever I work on a standard Rails project now, I inevitably begin asking myself why I’m having to write all of these actions to do basic CRUD stuff. Streamlined provides it for free.

    Streamlined is quickly approaching a 1.0 release (hopefully this month) so there has never been a better time to jump onboard. One good way to get rolling is with this post that I made a few months ago.

  • Automating file uploads with SSH and Ruby

    Are you fairly new to Ruby programming? Do you want to learn more about how Ruby can be used as the “glue” to script various libraries into harmonious cooperation? Look no further…

    InfoQ recently published an article I wrote last year about how to automate file uploads to a web server with Ruby’s Net::SSH and Net::SFTP libraries. It’s a fairly lengthy tutorial with plenty of code samples.

    Looking back, the script I created could pretty easily be reproduced in Capistrano today. But isn’t it sometimes more fun (not to mention educational) to write something from scratch? I sure think so.

  • Lone Star Ruby Conf now accepting proposals

    For those of you interested in a trip to sunny Austin, the Lone Star Ruby Conf is now accepting speaker proposals. LSRC is a regional conference similar to the Ruby Hoedown that’s coming to Raleigh in August. It’s great to see these regional conferences taking off.

  • Getting started with Streamlined (part 1)

    If you were one of the unfortunate souls who missed RailsConf this year, I’m sorry for you. If you happened to be at RailsConf but missed Justin Gehtland’s excellent Streamlined tutorial then you are truly of all people most pitiable.

    On a more serious note, the tutorial was very good and has sparked a lot of interesting ideas for further enhancing Streamlined beyond its already hefty feature set. For those who don’t know, Streamlined is a Rails plugin that brings the declarative goodness of ActiveRecord to the UI. It enhances your views with full-featured scaffolds that include relationship management, quick adding of associated models, and much more.

    If you haven’t played with Streamlined before, why not give it a try? With several fresh screencasts over at the blog, a bundle of new documentation, a new sample project, and version 1.0 on the horizon… there’s no time like the present.

    Getting started with Streamlined is easy…

    (more…)

  • Slides from my RailsConf talk

    For those who may have missed my talk at RailsConf, you can download the slides to get a better idea of what the talk was all about.

    I had a blast, by the way! The audience seemed to enjoy it, and I was pleasantly surprised at the number of questions people had about Teascript and the process of building it. About a dozen people came up to me afterwards saying that they had an idea they were mulling over, and my talk had inspired them to get started on it.

    I’ll probably be writing a couple of follow up articles that go into more detail on how homesteading worked for me. I didn’t have enough time to cover everything I wanted to at the presentation due to the enthusiastic response from the audience. To those who attended, thanks for being there and making the talk a success!

  • RailsConf ’07 wrap up

    Portland is rapidly fading into the distance as I fly back towards Raleigh. I’ve enjoyed the past six days immensely. The Ruby/Rails community continues to surprise me with its passion, dedication, and downright uber-geekiness. The highlight of the conference for me was the time spent between talks and during meals, sharing ideas and experiences with other developers. I’m totally worn out now, but I’m already looking forward to next year’s Conf.

    Not everything was peachy keen, though. There are several things that bothered me about the Conf this year…

    (more…)

  • Let the Conf begin

    I just arrived in Portland a few hours ago for RailsConf ’07. I’m looking forward to attending the tutorial sessions tomorrow, not to mention watching presentations by fellow Rails geeks on Friday and Saturday. My own talk on homesteading and Teascript will be given on Saturday at 10:45 AM for those who are interested. Hope to see you there!