Module: Blog::BasedUrlFor
- Included in:
- Blog
- Defined in:
- app/models/blog.rb
Instance Method Summary collapse
-
#url_for(options = {}, extra_params = {}) ⇒ Object
Generate a URL based on the
base_url
.
Instance Method Details
#url_for(options = {}, extra_params = {}) ⇒ Object
Generate a URL based on the base_url
. This allows us to generate URLs without needing a controller handy, so we can produce URLs from within models where appropriate.
It also caches the result in the Rails cache, so repeated URL generation requests should be fast, as they bypass all of Rails’ route logic.
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 |
# File 'app/models/blog.rb', line 175 def url_for( = {}, extra_params = {}) case when String = .sub(%r{^/}, "") url_generated = if extra_params[:only_path] root_path else base_url end # They asked for 'url_for "/some/path"', so return it unedited. url_generated += "/#{}" url_generated += "##{extra_params[:anchor]}" if extra_params[:anchor] url_generated when Hash merged_opts = .reverse_merge!(only_path: false, controller: "", action: "permalink", host: host_with_port, script_name: root_path) cache_key = merged_opts.values.prepend("blog-urlfor-withbaseurl").join("-") Rails.cache.fetch(cache_key) { super(merged_opts) } else raise "Invalid URL in url_for: #{.inspect}" end end |