Module: Blog::BasedUrlFor

Included in:
Blog
Defined in:
app/models/blog.rb

Instance Method Summary collapse

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.



172
173
174
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 172

def url_for(options = {}, extra_params = {})
  case options
  when String
    options = options.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 += "/#{options}"
    url_generated += "##{extra_params[:anchor]}" if extra_params[:anchor]
    url_generated
  when Hash
    merged_opts = options.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("-")
    unless Rails.cache.exist?(cache_key)
      Rails.cache.write(cache_key, super(merged_opts))
    end
    Rails.cache.read(cache_key)
  else
    raise "Invalid URL in url_for: #{options.inspect}"
  end
end