Skip to content

Instantly share code, notes, and snippets.

@ugisozols
Created November 14, 2012 12:11
Show Gist options
  • Save ugisozols/4071782 to your computer and use it in GitHub Desktop.
Save ugisozols/4071782 to your computer and use it in GitHub Desktop.
Refinery::Pages::Url
# app/models/refinery/page.rb
# ... code ...
def url
@url ||= Refinery::Pages::Url.build(self)
end
def uncached_nested_url
[parent.try(:uncached_nested_url), to_param.to_s].compact.flatten
end
# Returns an array with all ancestors to_param, allow with its own
# Ex: with an About page and a Mission underneath,
# ::Refinery::Page.find('mission').nested_url would return:
#
# ['about', 'mission']
#
alias_method :nested_url, :uncached_nested_url
# Returns the string version of nested_url, i.e., the path that should be generated
# by the router
def nested_path
['', nested_url].join('/')
end
# ... code ...
# lib/refinery/pages/url.rb
module Refinery
module Pages
class Url
class Localised < Url
def self.handle?(page)
page.link_url.present?
end
def url
current_url = page.link_url
if current_url =~ %r{^/} &&
Refinery::I18n.current_frontend_locale != Refinery::I18n.default_frontend_locale
current_url = "/#{Refinery::I18n.current_frontend_locale}#{current_url}"
end
current_url
end
end
class Marketable < Url
def self.handle?(page)
Refinery::Pages.marketable_urls
end
def url
url_hash = base_url_hash.merge(:path => page.nested_url, :id => nil)
with_locale_param(url_hash)
end
end
class Normal < Url
def self.handle?(page)
page.to_param.present?
end
def url
url_hash = base_url_hash.merge(:path => nil, :id => page.to_param)
with_locale_param(url_hash)
end
end
def self.build(page)
klass = [ Localised, Marketable, Normal ].detect { |d| d.handle?(page) } || self
klass.new(page).url
end
def initialize(page)
@page = page
end
def url
raise NotImplementedError
end
private
attr_reader :page
def with_locale_param(url_hash)
if (locale = Refinery::I18n.current_frontend_locale) != ::I18n.locale
url_hash.update :locale => locale if locale
end
url_hash
end
def base_url_hash
{ :controller => '/refinery/pages', :action => 'show', :only_path => true }
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment