How can I access UrlWriter url/path generators from a model's class method?
-
29-09-2019 - |
Question
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
Solution
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"
OTHER TIPS
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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow