Generated by spec.rb at: Thu Sep 01 19:01:13 CEST 2005

Rails reloadable custom models (non-descendants of ActiveRecord::Base)

Table of contents

Obsoleted!

This solution is obsoleted in favor of:

http://dev.rubyonrails.com/ticket/2098

Problem

When in development mode, Rails doesn't reload models that aren't descendant of ActiveRecord::Base.

Solution

Straightforward one:

lib/reloadable_model.rb

class ReloadableModel
end

class Dispatcher
    class <<self
        unless method_defined?(:orig_reset_application!)
            alias_method :orig_reset_application!, :reset_application!

            def reset_application!
                orig_reset_application!
                Dependencies.remove_subclasses_for(::ReloadableModel)
            end
        end
    end
end

app/controllers/application.rb

require_dependency "reloadable_model"

class ApplicationController < ActionController::Base
end

app/models/noreloadable.rb

class Noreloadable
    @@reloaded = Time.now

    def to_s
        "Reloaded at: " + @@reloaded.to_s
    end
end

app/models/reloadable.rb

class Reloadable < ReloadableModel
    @@reloaded = Time.now
    
    def to_s
        "Reloaded at: " + @@reloaded.to_s
    end 
end 

app/controllers/show_controller.rb

class ShowController < ApplicationController
    def index
        render :text => \
            [Reloadable.new.to_s, Noreloadable.new.to_s].join("<br/>\n") +
            "<br/>\n"
    end
end

Result

wejn@ns ~/tmp/x $ f() { curl localhost:3000/show 2>/dev/null; }; f; echo; sleep 1; f
Reloaded at: Thu Sep 01 03:24:25 CEST 2005<br/>
Reloaded at: Thu Sep 01 03:24:25 CEST 2005<br/>

Reloaded at: Thu Sep 01 03:24:27 CEST 2005<br/>
Reloaded at: Thu Sep 01 03:24:25 CEST 2005<br/>