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 に答える