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.



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'app/models/blog.rb', line 165

def url_for(options = {}, extra_params = {})
  case options
  when String
    url_generated = if extra_params[:only_path]
                      root_path
                    else
                      base_url
                    end
    url_generated += "/#{options}" # They asked for 'url_for "/some/path"', so return it unedited.
    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('-')
    Rails.cache.write(cache_key, super(merged_opts)) unless Rails.cache.exist?(cache_key)
    Rails.cache.read(cache_key)
  else
    raise "Invalid URL in url_for: #{options.inspect}"
  end
end