代码之家  ›  专栏  ›  技术社区  ›  John Bachir

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

  •  2
  • John Bachir  · 技术社区  · 15 年前

    我想从模型的类方法生成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
    
    2 回复  |  直到 14 年前
        1
  •  3
  •   TJ Singleton    15 年前
    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
    

    鲁比-1.9.1-p378?>user.admin_路径

    => "/admin"
    
        2
  •  1
  •   jamiew    14 年前

    甜美!

    一点重构……

    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
    
    推荐文章