views:

24

answers:

2

I want to generate urls from a model's class method. I've done this before from an instance method by simply including ActionController::UrlWriter -- I tried including this in the instance definition scope and also the class definition scope, to no avail.

class Foo < ActiveRecord::Base
  # only works for instance methods
  # include ActionController::UrlWriter

  class << self
    # results in this error: undefined method `default_url_options' for Class:Class
    # include ActionController::UrlWriter
    def my_method
      return user_sprockets_url(:thingy => 'blue')
    end
  end    
end
+2  A: 
class ModelURL
  include ActionController::UrlWriter
end

class User
  @url_generator = ModelURL.new
  class << self
    def admin_path
      @url_generator.send :admin_path
    end
  end
end

ruby-1.9.1-p378 ?> User.admin_path

=> "/admin"
TJ Singleton
A: 

Sweet!

a little refactoring..

class ModelURL
  include ActionController::UrlWriter
  @@singleton = ModelURL.new
  class << self
    def singleton
      @@singleton
    end
  end
end

usage...

ModelURL::generator.send :user_sprockets_url, :thingy => 'blue', :host => DOMAIN
John