2

我想从模型的类方法生成 url。我之前通过简单地包含在实例方法中完成了此操作ActionController::UrlWriter- 我尝试将其包含在实例定义范围和类定义范围中,但无济于事。

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
4

2 回答 2

3
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"
于 2010-06-25T06:27:34.927 回答
1

甜的!

一点重构..

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

用法...

ModelURL::singleton.send :user_sprockets_url, :thingy => 'blue', :host => DOMAIN
于 2010-06-25T06:32:32.787 回答