如何从模型的类方法访问 UrlWriter url/路径生成器?

发布于 2024-09-06 19:02:02 字数 499 浏览 10 评论 0原文

我想从模型的类方法生成 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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

泛泛之交 2024-09-13 19:02:02
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 ?>用户.admin_path

<前><代码>=> “/行政”

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"
谁人与我共长歌 2024-09-13 19:02:02

甜的!

一点重构..

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

Sweet!

a little refactoring..

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

usage...

ModelURL::singleton.send :user_sprockets_url, :thingy => 'blue', :host => DOMAIN
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文