Archive for the ‘Rails’ Category

perl modules

Sunday, August 15th, 2010

Adderall onlineLevitra

I am a complete Perl novice.  But there are occasions when I need to install perl modules.  I have learned that

perl -MCPAN -e ‘install (module-name)’

will allow you to install a perl module from the CPAN respository.

Ruby on Rails Performance Tuning -a beginners perspective

Sunday, August 15th, 2010

Adderall onlineLevitra

So I have been developing MemoryMiner (as my introduction to Rails) for almost six months now, and performance issues are starting to become recognizable. In a desperate attempt to kill two birds with one stone, I upgraded my Linux server (bmw) to Fedora Core 5 this past weekend. It was not uneventful but I finished with MySQL 5.0.22 installed and running for my Rails apps. I also now have ruby 1.8.5 and Edge Rails.   Unfortunately, the performance is still inadequate, and while I’m perfectly willing to suffer due to limited hardware, I’m pretty sure there is some bloat that needs to be trimmed -particularly in the area of database query tuning.

The first order of business was to get a handle on where my application was spending time. The classic solution, a profiler, applies to Rails as well. I tried the built-in profiler (script/performance/profiler) but was not blown away. Then I found ruby-prof and its graph profiles. I installed the gem and added a real simple around filter in the controller to generate an HTML Graph Profile. Cool -I could exercise a method/URL in a controller and immediately (in another browser) see the results in an easy-to-digest format.

Unfortunately, I could not find a smoking gun.
References:

  1. http://ruby-prof.rubyforge.org/graph.txt
  2. http://ruby-prof.rubyforge.org/
  3. http://glu.ttono.us/articles/2006/06/23/stefen-kaes-optimizing-rails
  4. http://www.thoughtstoblog.com/articles/2006/10/24/rails-performance-tool-box
  5. http://blog.kovyrin.net/2006/08/28/ruby-performance-results/
  1. Good example of benchmarking -with useful server-vs-server results.

ActiveSupport::Dependencies and plugins

Tuesday, June 22nd, 2010

For the second time this year, I struggled debugging the dreaded “A copy of XXX has been removed from the module tree but is still active”.  Last time, I learned the lesson of letting Rails autoload wherever possible and to not try to manage the loading myself.  Kind of a Zen thing.

But there are limitations with that approach.  For starters, we all know this only applies to Rails, not Ruby in general.  And so when writing gems, require is your friend.  An edge case is plugins.  The auto-dependency mechanism does not reload plugin code (at least not by default), but it will autoload it initially.  That’s a code smell, in my opinion, that leads to the error noted in the first paragraph when “locked in” code references autoloaded code.  It kinda works like this as best I can tell: don’t let Rails autoload code that it is not also reloading.

Given that plugins are (normally) not be reloaded, you need to avoid having Rails grab const_missing and autoload your code.  So, in plugin code, use your normal arsenal of Ruby-standard load/require to load stuff.  Here’s a neat trick to find where you’ve failed to make the grade: start the console and run

>> print ActiveSupport::Dependencies.history.grep(/plugin/).join(”\n”)

Any plugin code listed is probably counting on Rails’ dependency resolution/autoloader.  You may need to muck around with your code a bit to trigger stuff getting autoloaded, but in my case there was plenty to work on just post-initialization.

ActiveRecord fixtures, binary data, SQLite3 and namespaced models are a dangerous combination

Wednesday, June 9th, 2010

I switched the test database for one of my plugins to SQLite3 today -I like the idea of not requiring a database setup step for plugin tests and the in-memory option for SQLite3 nicely sidesteps that requirement.  Immediately my tests all failed with:

ActiveRecord::StatementInvalid: SQLite3::SQLException: unrecognized token: <INSERT statement mixed in with a bunch of binary gobbledygook>

The weak link here is Ruby.  Think about this chain of custody for my binary data:

  1. YAML fixture with “!binary” directive
  2. Ruby String
  3. SQLite3 Blob

The second custodian (prior to 1.9 only, I hope) loses the “binariness” of my data and thus fails to properly quote it for insertion into SQLite3 (interestingly, MySQL does not appear to require special quoting).  Normally ActiveRecord knows how to restore the binariness of the data on insert by looking at the destination column type (you can see this code in fixtures.rb).  But it gets this column information in a strange way: despite knowing the table into which the fixture is to be inserted, ActiveRecord gets the column data by referencing the model class associated with the table.  The model class is guessed from the name of the fixture’s DB table -which fails to find a match whenever the model class is not in the root namespace.  Head spinning yet?

<fixture file name> => <database table> => <model class> => <column details>

(The irony is that a model class knows its column types because it inspected the table during initialization.  Why doesn’t the Fixtures class (which also knows which table to inspect) do the same thing?  Like this:

<fixture file name> => <database table> => <column details>

Who knows?)Anyway, without a model class and thus column type hints, ActiveRecord happily inserts fixtures with generic quoting.  Ruby strings, for example, are assumed to be destined for plain string columns.  For blob columns in SQLite3, this causes a shower of sparks.All hope is not lost, however.  Rails provides the #set_fixture_class method which allows you to explicitly link the fixture file to a model class.  For example:

set_fixture_class {:widgets => My::Deeply::Nested:Widget, :thingys => My::Deeply::Nested::Thingy}

Problem solved.

ActiveResource::HttpMock doesn’t mock hard enough

Thursday, November 19th, 2009

I’ve got a family of (ARes) resources that are available through an external web service.  These resources are used pervasively throughout my site -they appear on about 75% of my site’s pages.  When testing, of course I don’t want to hit the web service and endure the vagaries of performance and availability.  The nice people developing ActiveResource seem to have accommodated this desire by providing the HttpMock class.

But…  HttpMock is very exacting in its demands for matching requests -it’s all or nothing.  That means that if I make fifty different requests, all identical save for a tiny change in the URL params, I need to make fifty different mocks.  Ouch.

So I decided to mock the mocker.  No, really.  Using mocha, I mock the HttpMock::Request#== method to always return true.  Now, regardless of the request path, HttpMock always sees a match and returns my mock data.

The denouement, using the Rails docs as a starting point:

def setup
  @matz  = { :id => 1, :name => "Matz" }.to_xml(:root => "person")
  ActiveResource::HttpMock.respond_to do |mock|
    mock.post   "/people.xml",   {}, @matz, 201, "Location" => "/people/1.xml"
    mock.get    "/people/1.xml", {}, @matz
    mock.put    "/people/1.xml", {}, nil, 204
    mock.delete "/people/1.xml", {}, nil, 200
    req_res = mock.get "/", {}, "Constant Data Goes Here", 200
    req_res.last.first.stubs(:==).returns(true)
 end
end

Aptana RadRails and the test_helper.rb LoadError

Thursday, July 17th, 2008

Since moving to more recent versions of Rails, I’ve noticed that the auto-generated Rails tests assume that the myapp/test directory is on the load path.  And the bundled Rake testing tasks do indeed take care of that requirement.  But the Aptana RadRails plugins for Eclipse don’t.  The result is that whenever you run a test, either with the test buttons or the Run As | Test::UnitTest context menu, you get something like the following:

./test/unit/user_test.rb:1:in `require': no such file to load -- test_helper (LoadError)

There is an open issue on the Aptana issue tracker, but it doesn’t seem to be resolved yet.  Some people have suggested prefixing your requires with the test directory when requiring the test_helper file at the start of your test files -but I don’t think that’s a good solution, especially if you’re working with multiple developers.  Frustrated by not getting my daily green bar fix, I found this work-around:

  1. From the Eclipse Preferences option, choose Ruby | Installed Interpreters
  2. Select your interpreter (I use the Standard VM default interpreter named usr) and choose ‘Edit’. 
  3. Add -Itest to the Default VM Arguments option.  Don’t forget the leading dash!
  4. Click ‘OK’. 

You should now be able to run your tests without having to edit each one to include the test directory.  The downside is that you now have an ‘extra’ directory in your load path which will give you a (tiny) performance hit to all your ruby ops -not just tests.  Conceivably this could also introduce an incompatibility if you have some conflicting stuff in the test directory -extremely unlikely if you only have test_helper.rb in there.

Tested against Edge Rails (d37e6413366c9a3fafa02c4298a2946dc8327a42), Aptana RadRails 1.0.3.200807071913NGT, Ruby 1.8.6 patchlevel 114 running under Darwin 9.4.0

Ruby, Rails and MySQL with Leopard 10.5.2 and XCode 3.0

Wednesday, March 19th, 2008

I’m pretty new to Macintosh development but I’ve been working in Ruby for a couple of years under Win32 and Linux. I was excited by the concept of Ruby and Rails being supported “out-of-the-box” on Leopard with the installation of XCode 3.0. But it didn’t take long for the luster to wear off.I first knew things were not going to be easy when I tried to install MySQL. Since I have a recent MacBook Pro with a Core 2 Duo processor, I went for the x86_64 disk image package (ominous background music starts now). It installed without too many difficulties (but not painless w.r.t the system preference pane). I then went to install the C-based ruby mysql bindings gem:

bimota:lib cch1$ sudo gem install mysql
Building native extensions.  This could take a while...
ERROR:  Error installing mysql:	ERROR: Failed to build gem native extension.
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby extconf.rb install mysql
checking for mysql_query() in -lmysqlclient... nochecking for main() in -lm... yes
checking for mysql_query() in -lmysqlclient... nochecking for main() in -lz... yes
checking for mysql_query() in -lmysqlclient... nochecking for main() in -lsocket... no
checking for mysql_query() in -lmysqlclient... nochecking for main() in -lnsl... no
checking for mysql_query() in -lmysqlclient... no
Gem files will remain installed in /Library/Ruby/Gems/1.8/gems/mysql-2.7 for inspection.
Results logged to /Library/Ruby/Gems/1.8/gems/mysql-2.7/gem_make.out

…and thus began the disenchantment.The failure above is caused by the gem command attempting to compile the native MySQL extensions but not being able to find the necessary library and header files. This can be caused by several more fundamental problems:

  1. The path used by default to find the MySQL library files (/usr/local/lib/mysql) does not match the default MySQL installation directory (/usr/local/mysql) on Leopard. This could be remedied by passing command line options to the gem command which would ultimately passed to the configurator (extconf.rb).
  2. The default gem installation tries to build a fat binary with code for four architectures (ppc, ppc64, i386 and i86_64). But, assuming you installed the x86_64 MySQL package, the library file /usr/local/mysql/lib/libmysqlclient.dylib only supports i86_64. This can be remedied either by setting the ARCHFLAGS environment variable before starting the gem command, or by helping the configurator learn the architecture with another command line option.

Both of the above problems can apparently be solved nicely with one command line option that helps the configurator learn the appropriate build options directly from the MySQL installation:

bimota:mysql cch1$ sudo gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config
Building native extensions.  This could take a while...
Successfully installed mysql-2.7
1 gem installed

But you would be foolish to believe that it actually works. Run the same command with the verbose option enabled, and you can see that there is trouble on the horizon despite the apparent success:

bimota:mysql cch1$ sudo gem install -V mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config
Installing gem mysql-2.7/Library/Ruby/Gems/1.8/gems/mysql-2.7/COPYING/Library/Ruby/Gems/1.8/gems/mysql-2.7/COPYING.ja/Library/Ruby/Gems/1.8/gems/mysql-2.7/README.html/Library/Ruby/Gems/1.8/gems/mysql-2.7/README_ja.html/Library/Ruby/Gems/1.8/gems/mysql-2.7/extconf.rb/Library/Ruby/Gems/1.8/gems/mysql-2.7/mysql.c.in/Library/Ruby/Gems/1.8/gems/mysql-2.7/test.rb/Library/Ruby/Gems/1.8/gems/mysql-2.7/tommy.css/Library/Ruby/Gems/1.8/gems/mysql-2.7/mysql.gemspec
Building native extensions.  This could take a while...
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby extconf.rb install -V mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config
checking for mysql_ssl_set()... no
checking for mysql.h... yes
creating Makefile
makegcc -I. -I. -I/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/universal-darwin9.0 -I. -DHAVE_MYSQL_H  -I/usr/local/mysql/include -Os -arch x86_64 -fno-common -fno-common -arch ppc -arch i386 -Os -pipe -fno-common  -c mysql.ccc -arch ppc -arch i386 -pipe -bundle -undefined dynamic_lookup -o mysql.bundle mysql.o -L"." -L"/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib" -L. -arch ppc -arch i386    -lruby -L/usr/local/mysql/lib -lmysqlclient -lz -lm  -lpthread -ldl -lm
ld: warning in /usr/local/mysql/lib/libmysqlclient.dylib, file is not of required architecture
ld: warning in /usr/local/mysql/lib/libmysqlclient.dylib, file is not of required architecture
make install/usr/bin/install -c -m 0755 mysql.bundle /Library/Ruby/Gems/1.8/gems/mysql-2.7/libSuccessfully installed mysql-2.71 gem installed

Indeed, when you go to use (not just ‘require’) the gem, you are likely to see this nasty error:

bimota:mmweb cch1$ rake db:version(in /Users/cch1/Documents/Development/mmweb)dyld: lazy symbol binding failed: Symbol not found: _mysql_init  Referenced from: /Library/Ruby/Gems/1.8/gems/mysql-2.7/lib/mysql.bundle  Expected in: dynamic lookup
dyld: Symbol not found: _mysql_init  Referenced from: /Library/Ruby/Gems/1.8/gems/mysql-2.7/lib/mysql.bundle  Expected in: dynamic lookup
Trace/BPT trap

I’m still have no idea what causes this specific failure, but I suspect it’s related to the compiler options suggested by mysql_config being ignored/munged by the configurator. The gcc command above tries to build for three different architectures (ppc, i386, x86_64) despite mysql_config’s “recommendation” of just x86_64:

bimota:mysql cch1$ /usr/local/mysql/bin/mysql_config
Usage: /usr/local/mysql/bin/mysql_config [OPTIONS]
Options:
        --cflags         [-I/usr/local/mysql/include -Os -arch x86_64 -fno-common]
        --include        [-I/usr/local/mysql/include]
        --libs           [-L/usr/local/mysql/lib -lmysqlclient -lz -lm]
        --libs_r         [-L/usr/local/mysql/lib -lmysqlclient_r -lz -lm]
        --socket         [/tmp/mysql.sock]
        --port           [3306]
        --version        [5.0.51a]
        --libmysqld-libs [-L/usr/local/mysql/lib -lmysqld -lz -lm]

I then try forcing the issue by setting the environment variable as well:

bimota:lib cch1$ sudo env ARCHFLAGS="-arch x86_64" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_configBuilding native extensions.  This could take a while...Successfully installed mysql-2.71 gem installed

Again, it looks promising. But now when Rails asks Ruby (1.8.6 from the default XCode 3.0 install) to load the mysql gem, the OS generates a load error due to some kind of a mismatch:

bimota:mmweb cch1$ script/console
Loading development environment (Rails 2.0.2)
>> require_library_or_gem 'mysql'
LoadError: dlopen(/Library/Ruby/Gems/1.8/gems/mysql-2.7/lib/mysql.bundle, 9): no suitable image found.  Did find:
	/Library/Ruby/Gems/1.8/gems/mysql-2.7/lib/mysql.bundle: mach-o, but wrong architecture - /Library/Ruby/Gems/1.8/gems/mysql-2.7/lib/mysql.bundle
	from /Library/Ruby/Gems/1.8/gems/mysql-2.7/lib/mysql.bundle
	from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:32:in `require'
	from /Users/cch1/Documents/Development/mmweb/vendor/rails/activerecord/lib/../../activesupport/lib/active_support/dependencies.rb:496:in `require'
	from /Users/cch1/Documents/Development/mmweb/vendor/rails/activerecord/lib/../../activesupport/lib/active_support/dependencies.rb:342:in `new_constants_in'
	from /Users/cch1/Documents/Development/mmweb/vendor/rails/activerecord/lib/../../activesupport/lib/active_support/dependencies.rb:496:in `require'
	from /Users/cch1/Documents/Development/mmweb/vendor/rails/activerecord/lib/../../activesupport/lib/active_support/core_ext/kernel/requires.rb:7:in `require_library_or_gem'
	from /Users/cch1/Documents/Development/mmweb/vendor/rails/activerecord/lib/../../activesupport/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnings'
	from /Users/cch1/Documents/Development/mmweb/vendor/rails/activerecord/lib/../../activesupport/lib/active_support/core_ext/kernel/requires.rb:5:in `require_library_or_gem'
	from (irb):1
>> ^Dbimota:mmweb cch1$

Why the mismatch? Some googling led me to this post that notes that the Ruby interpreter bundled in XCode 3.0 is in fact only compiled as a 32-bit i386 executable. That’s right: the latest and greatest Macs (with Intel Core 2 Duo processors) running the latest and greatest OS (Leopard 10.5.2) are shipping with a neutered Ruby interpreter.At this point, I see two solutions:1. Install the i386/32-bit only version of MySQL (boo!). I’ve confirmed that this allows a nice working mysql binding to be built with the following command:

bimota:mysql cch1$ sudo env ARCHFLAGS="-arch i386" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config
Building native extensions.  This could take a while...Successfully installed mysql-2.71 gem installedbimota:mysql cch1$

And not only does it compile, it actually works.2. Recompile Ruby with x86_64 support. That sounds like a bigger job -but there are web sites that show you how to get started. For now though, I’m leaving XCode alone until I know what works -that way, when it breaks, I can assign the failure to the 64-bit ruby interpreter.

Validating the presence of exactly one of a list of attributes

Thursday, November 8th, 2007

I read Eric’s blog on creating an ActiveRecord validation for an exactly-one-of predicate.  I myself had just recently gone through a similar exercise and found a straightforward way of expressing it using the validate method:

validate :exactly_one_of?

def exactly_one_of?
  attrs = [:url, :file, :blob]
  returning (attrs.inject(false){|m, o| m^self[o]}) do |bool|
    self.errors.add(:base, “Exactly one of #{attrs} must be set.”) unless bool
  end
end

While this worked nicely for me, Eric went to the trouble of building a semantically clean validation method that mimics the options of the standard validations.  I prefer using Ruby’s Exclusive OR operator combined with inject instead of the looping in Eric’s method, but I like the semantic style he defined.  Combining his semantics with my logic yields something slick and DRY like this:

def self.validate_exactly_one_of(*attrs)
  options = attrs.last.is_a?(Hash) ? attrs.pop : {}
  configuration = { :message => “one of #{attrs.to_sentence :connector => ‘or’} must be set”, :on => :save }
  configuration.update(options)

  send(validation_method(options[:on] || :save)) do |record|
    returning (attrs.inject(false){|m, o| m^record[o]}) do |bool|
      self.errors.add(:base, configuration[:message]) unless bool
    end
  end
end

I also fiddled the options logic because I think otherwise it would have been possible to have an attribute listed in the error message list that was in fact an option.

More on Full Circle REST

Tuesday, September 18th, 2007

Some time ago I frothed on (hip people call this blogging) about how Rails was missing an opportunity to exploit the modelling work done in routes.rb. You can see my post here.

Anyway, in the intervening month or so, I have been working with Ian White’s nifty ResourcesController plugin. As is my wont, I bitch and moan a lot about what is wrong with ResourcesController (RC). The nice thing is that Ian listens and crafts some pretty damn nice code -a lot of my vision of Full-circle REST is starting to appear in RC. In fact, RC is so promising I have abandoned my own plugin and jumped into bed with Ian (in a manner of speaking).

RC can identify many of the RESTful resources of a concrete request with an increasingly concise invocation. It can handle singleton resources, arbitrary nesting and polymorphic nesting. For these features alone, I suggest you look into it.

RC identifies the abstract resources of the URI by examining the inbound request (it has evolved from doing this in a purely textual fashion to examining the matched route’s structure). But it could be better. It could identify the route (when the request arrives) more efficiently. It could link this concrete route directly and unambiguously to the abstract resource that generated it (keeping RC nice and DRY w.r.t routes.rb). And critically, the abstract resource could refer to its parents in the hierarchy of resources in routes.rb, allowing even more direct determination of the complete chain of abstract resources that is being supplied by the URI. Then we could have full-circle REST.

But at this point, RC is hampered by Rails itself. Three patches to edge are required to get us there. I’ve written the first two, and the third shouldn’t be to hard (volunteers?). I’m presenting them in reverse order because I think they’re easier to understand that way.

Patch #3 - Store the hierarchy of abstract REST resources that generate named routes. Currently, only a few strings (name_prefix) provide circumstantial evidence of the parents. Let’s be explicit and store a reference to the the parent in each ActionController::Resources::Resource instance. Then the abstract REST resources will be represented by a forest of trees -and that is pretty close to ideal.

Patch #2 - Store the generating abstract resource in the generated named route. I’ve written the code to do this, but I’m not proud. In fact, I think it is kinda ugly.

module ActionController
  module Resources
      def action_options_for(action, resource, method = nil)
        default_options = { :action => action.to_s, :resource => resource }
        require_id = !resource.kind_of?(SingletonResource)
        case default_options[:action]
          when “index”, “new” : default_options.merge(add_conditions_for(resource.conditions, method || :get)).merge(resource.requirements)
          when “create”       : default_options.merge(add_conditions_for(resource.conditions, method || :post)).merge(resource.requirements)
          when “show”, “edit” : default_options.merge(add_conditions_for(resource.conditions, method || :get)).merge(resource.requirements(require_id))
          when “update”       : default_options.merge(add_conditions_for(resource.conditions, method || :put)).merge(resource.requirements(require_id))
          when “destroy”      : default_options.merge(add_conditions_for(resource.conditions, method || :delete)).merge(resource.requirements(require_id))
          else                  default_options.merge(add_conditions_for(resource.conditions, method)).merge(resource.requirements)
        end
      end
  end
end

module ActionController
  module Routing
    class Route
      attr_accessor :resource
    end
    class RouteBuilder      # Construct and return a route with the given path and options (including the resource option)
      def build(path, options)        # Wrap the path with slashes
        path = “/#{path}” unless path[0] == ?/
        path = “#{path}/” unless path[-1] == ?/    

        path = “/#{options[:path_prefix]}#{path}” if options[:path_prefix]

        resource = options.delete(:resource)
        segments = segments_for_route_path(path)
        defaults, requirements, conditions = divide_route_options(segments, options)
        requirements = assign_route_options(segments, defaults, requirements)

        route = Route.new
        route.segments = segments
        route.requirements = requirements
        route.conditions = conditions
        route.resource = resource

        if !route.significant_keys.include?(:action) && !route.requirements[:action]
          route.requirements[:action] = “index”
          route.significant_keys << :action
        end

        if !route.significant_keys.include?(:controller)
          raise ArgumentError, “Illegal route: the :controller must be specified!”
        end

        route
      end
    end
  end
end

The actual code change is minimal, but it is not very clean in RouteBuilder -in fact, that code really should not have been required. FYI, this code was working about a month ago and I assume it should still work. Still, beware!

Patch #1 - Store the recognized route in the abstract request. Testing aside (see below), this one is simple:

module ActionController
  class AbstractRequest
    attr_accessor :recognized_route
  end

  module Routing
    class RouteSet
      def recognize(request)
        params, recognized_route = recognize_path(request.path, extract_request_environment(request))
        request.path_parameters = params.with_indifferent_access
	request.recognized_route = recognized_route
        "#{params[:controller].camelize}Controller".constantize
      end

      def recognize_path(path, environment={})
        routes.each do |route|
          result = route.recognize(path, environment) and return result, route
        end

        allows = HTTP_METHODS.select { |verb| routes.find { |r| r.recognize(path, :method => verb) } }

        if environment[:method] && !HTTP_METHODS.include?(environment[:method])
          raise NotImplemented.new(*allows)
        elsif !allows.empty?
          raise MethodNotAllowed.new(*allows)
        else
          raise RoutingError, "No route matches #{path.inspect} with #{environment.inspect}"
        end
      end
    end
  end
end

I’ve changed the return signature of recognize_path so there may be some undesired side-effects. But I haven’t found any yet. Also, the TestRequest object would need to be modified as well to set the recognized_route attribute appropriately because recognize is not invoked in testing (another volunteer?).

So, a quick recap: Rails invites us to model our REST resources (in routes.rb) and uses that information for recognizing inbound routes and generating routes in views. But there is a much value to our modeling work to be found in the controllers themselves. And to harvest that value, we need visibility into the abstract resources that generated the invoked route. Rails needs to evolve in this direction I call full-circle REST.

Technorati Tags:

Full Circle REST

Friday, August 3rd, 2007

The support that Rails has provided for developing RESTful applications is nothing short of amazing considering it was added on long after Rails had an established URL-mapping mechanism (Routes.draw).  But I want more.  Specifically, I want my resources to have a more complete life.

Warning: I am not an expert in Rails or REST, but sometimes I think there has to be a better way.

Background: in the current (late summer 2007) Edge Rails, RESTful resources (ActionController::Resources) are defined primarily for the purpose of creating named routes with a DSL (map.resource …).  A very important by-product of generating named routes is the helper methods available to generate routes in views and controllers.  The net result is a tidy means of generating and recognizing RESTful URIs.  A typical exploitation of these features looks like this:

  1. Define Routes per Resource
  2. Recognize Incoming Request’s Route
  3. (process request in controller)
  4. Generate view, typically with one or more links

Repeat steps 2 through 4 as required.

In step one, the Rails programmer does the hard work: modeling the resources, the interface to those resources, the mapping of resources to controllers, etc.  Rails honors our work and uses these abstract resources to recognize routes (in step two) and to help up generate routes (in step four).  But what about step three?  Can we exploit our abstract resource model here?  Let’s recast the typical methods in a controller that backs a resource:

def index
  identify resource
  manipulate resource
end

def destroy
  identify resource
  manipulate resource
end

def create
  identify resource
  manipulate resource
end

For the index action, the identified resource is a collection represented by a Class or an association.  For the destroy (and show and edit) actions, the identified resource is a member represented by an ActiveRecord model instance.  For the create (and new) actions, the resource is a new, unsaved, AR model instance.  Every controller action that handles a REST request starts with the identification of the resource.  For the following examples, let’s define some resources:

map.resources users do |user|
  user.resources groups, :controller => ‘groups’ do |group|
    group.resources tags, :controller => ‘tags’
  end
end

map.resources groups do |group|
  group.resources users, :controller => ‘users’ do |user|
    user.resources tags, :controller => ‘tags’
  end
end

map.resources vehicles do |vehicle|
  vehicle.resources wheels, :controller => ‘wheels’
end

map.resources unicycles do |unicycle|
  vehicle.resource wheel, :controller => ‘wheels’
end

As these resource definitions show, sometimes resource identification is trivial and sometimes it’s not…

  1. /vehicles/567/wheels
  2. /unicycle/234/wheel
  3. /users/17/groups/2/tags
  4. /groups/2/users/17/tags

In example #1, wheels is a has_many association of a vehicle instance.  It would be nice if Rails helped us find the vehicle instance and pointed us towards its has_many association.  What we get is the params hash, which indicates the vehicle instance, and the invocation of WheelsController.index, which implies the wheels collection association.  Indirect, but adequate.

In example #2, wheel is a has_one association of a unicycle instance.  Rails should help us find the vehicle instance and point us towards the association.  Much as in the first example, Rails gives us a params hash and invokes the WheelsController.show method.  Again, indirect but adequate. 

Examples one and two together illustrate the first ugly problem with resource identification:

Problem One: The arity of resources is implied by the invoked controller method instead of being explicit.

In example #3, tags is a has_many association of a Group instance.  In example #4, tags is a has_many association of a User instance.  The params hash and invoked method  are identical for these two requests.  Rails really lets us down here: short of parsing the request path, there is nothing to distinguish these two requests.

Problem Two: The hierarchy of the request’s resource chain is not preserved.

I believe these two problems stem from the outdated perception of the URL only as a means of triggering a specific controller action and providing some unordered key-value parameters.  In the RESTful world, however, the URL has become a resource specifier.  And that means hierarchy matters and parameters are not limited to key-value pairs.  In a nutshell, Rails needs to help us match a concrete request with our abstract resource model.  Until it does, identification of RESTful resources will continue to be a pain in the ass.

In the meantime, I have taken two steps to help the programmer match an abstract resource to the concrete request by providing some extra information to the controller.  First, I have made the matched route available to the controller as an attribute of the request by monkey patching ActionController::Routing::RouteSet and ActionController::AbstractRequest.  Now I can see the specific components of the request in an abstract way instead of as a string.

But once I had made that change, I realized I was getting very close to the holy grail of the actual abstract resource definition (from routes.rb) used to generate the route.  It was only a couple of more monkey patches before I had the source ActionController::Resources::Resource instance available to the controller as well.

Now in my controllers I can see which of my abstract resources (as defined in routes.rb) matches the incoming request.  That goes a long way towards getting the matching AR model instances instantiated. 

My only remaining beef is that the abstract route definitions (in routes.rb) do not store any meaningful hierarchy information.  In my example above, the subordinate collection resource beneath a group and called ‘users’ is only aware of its parent resource (a group) though a couple of strings (name_prefix and one other).  That means that even when I know the abstract resource that matches the incoming request, I can’t really see its enclosing resources with inferring them from string pattern matching.  Rails should store the parent resource for any nested resources.  That will be my next monkey patch.

Resources
    Jamis Buck’s awesome tutorial on Rails Routing
    Discussion of some of these issues from a different angle
    Group trying to improve REST resource identification

Technorati Tags: