Posts tagged patches

Rails 2.3 and theme_support part 3: Layouts

In my ongoing efforts to bring my fork of theme_support in line with Rails 2.3 I’ve covered the core views and email, but when I left off earlier today layouts still weren’t working.

The key problem with overriding layouts is that the process of identifying them relies on some class methods on ActionController::Base (provided in the ActionController::Layout module). Roughly put we have:

  1. ActionController::Base#render calls ActionController::Base#pick_layout
  2. ActionController::Base#pick_layout checks to see if there’s a specific layout requested and calls ActionController::Base#active_layout
  3. ActionController::Base#active_layout checks whether there’s a candidate layout for this controller or action and makes sure the layout exists by calling ActionController::Base.find_layout
  4. ActionController::Base.find_layout (class method) is called which checks the view_paths to find the appropriate layout in there

The issue is that as a class method ActionController::Base.active_layout has no knowledge of the specific controller instance, or the request object it contains, and so it can’t access our logic to determine the current theme.

One option would be to patch a number of these methods to hand a controller instance around which could be queried for the theme, but that seems rather clunky.

Another option is to wrap the active_layout method so that it (as an instance method) checks whether there is a current theme and if so, adds that theme’s path to the class level view_paths, removing it again after that check:

  class ActionController::Base
    alias_method :theme_support_active_layout, :active_layout
 
    def active_layout(passed_layout = nil)
      if current_theme
        theme_path = File.join(RAILS_ROOT, "themes", controller.current_theme, "views")
        if File.exists?(theme_path) and ! self.class.view_paths.include?(theme_path)
          self.class.view_paths.unshift(theme_path)
          result = theme_support_active_layout(passed_layout)
          self.class.view_paths.shift
          return result
        end
      end
 
      theme_support_active_layout(passed_layout)
    end
  end

And it works!

So that’s views, emails and now layouts all working with theme_support on Rails 2.3. As before, you can get the results in the branch on github:

http://github.com/jystewart/theme_support/tree/rails-2-3-support

Over the next couple of weeks I’m hoping to test my patches on other releases in the 2.x series, probably using a test app with specs or stories that will put it through its paces. Once that’s done I may turn my attention to the other corners of the plugin (that I don’t personally use) like the asset helper methods, but if anyone wants to contribute patches in the meantime I’d love to get them.

The Array Argument (aka. *)

Wednesday’s post on acts_as_locateable didn’t do much to explain what the patch to the plugin’s methods was doing to allow us to pass extra arguments to ActiveRecord#find. The secret is in the *, or array argument.

A normal method will have a fixed number of arguments:

def simple_method(first, second, third)
  puts "#{first} : #{second} : #{third}"
end
 
simple_method('one', 'two', 'three')
 
>> one : two : three

and sometimes we can develop that by allowing default values for those arguments:

def simple_method(first, second, third = 'four')
  puts "#{first} : #{second} : #{third}"
end
 
simple_method('one', 'two')
 
>> one : two : four

but sometimes we want to allow an arbitrary number of arguments, and that’s where * (the Array Argument) comes in.

def simple_method(first, *others)
  puts "#{first} : " + others.join(' : ')
end
 
simple_method('one', 'two', 'three')
 
>> one : two : three

If you pass in keyed parameters then you will get a hash within the others array:

def simple_method(*others)
  puts others.inspect
end
 
simple_method('one', :two => 'three')
>> ["one", {:two=>"three"}]

So in the case of acts_as_locateable, the find_within_radius can take an arbitrary number of parameters to allow for different types of input:

def find_within_radius(radius_in_miles, *args)

All we needed to do to allow in more parameters was to extract our extra arguments which I knew would be grouped together in a Hash, so that the rest of the internals would still get the input they’re expecting:

# standard_args will be the args input minus any arguments of type Hash
# (our addition to the input)
standard_args = args.reject { |arg| arg.kind_of?(Hash) }
 
# query_args will then be the first Hash found in the arguments
query_args = (args - standard_args).first

and then we can pass our query_args hash to the find call later on:

find(:all, query_args)

Extending acts_as_locateable

There have been quite a few geographically-themed Rails plugins emerging over the past few months and I decided it was time to try out acts_as_locateable.

Acts_as_locateable is based on ZipCodeSearch. It loads in a database mapping US zip codes to coordinates and then adds convenience methods to ActiveRecord objects that let you search by distance. eg.

Event.find_within_radius(50, '49503')

will return all events within 50 miles of me.

What the standard plugin doesn’t allow is the passing in of more search parameters. So if I wanted to limit that search to future events I’d have to retrieve all the results and iterate over them. In a large system that could be very inefficient.

It turns out it’s not too hard to hack the plugin to make it accept other ActiveRecord parameters. By just adding a couple more checks to the parameter decoding, and adding an extra argument to the call to find. For my use it turned out to be easier to patch the original than re-open the class and add extra methods, though that would obviously be possible. For anyone who may want it, the patch is:

Index: lib/acts_as_locateable.rb
===================================================================
--- lib/acts_as_locateable.rb   (revision 29)
+++ lib/acts_as_locateable.rb   (working copy)
@@ -48,9 +48,13 @@
         # Find instances of the locatable class within radius_in_miles of your target.
         # Target can be specified in a number of ways, see expand_radius_args for options
         def find_within_radius(radius_in_miles, *args)
-          lat, lon = expand_radius_args(args)
+          standard_args = args.reject { |arg| arg.kind_of?(Hash) }
+          query_args = (args - standard_args).first
+          
+          lat, lon = expand_radius_args(standard_args)
+          # query_args = args.find { |arg| arg.kind_of?(Hash) }
           within_radius_scope(radius_in_miles, lat, lon) do
-            find(:all)
+            find(:all, query_args)
           end
         end

Now I can use:

Event.find_within_radius(50, '49503', 
	:conditions => ['starts_at > ?', DateTime.now], 
	:order => 'starts_at')

and get much more useful results.