我想从模型的类方法生成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
答案 0 :(得分: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?&gt; User.admin_path
=> "/admin"
答案 1 :(得分: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