Skip to content

Instantly share code, notes, and snippets.

@scarfacedeb
Created February 11, 2014 12:16
Show Gist options
  • Save scarfacedeb/8933768 to your computer and use it in GitHub Desktop.
Save scarfacedeb/8933768 to your computer and use it in GitHub Desktop.
Custom view object
# An encapsulated class for i18n-related widgets in the footer
#
# It includes:
# - Locale switcher
# - Currency switcher
#
# Also it's state stores available translated locales for current pages
#
class I18nWidgets
delegate :params,
:t, :content_tag, :link_to, :current_currency, # general helpers
:root_path, :settings_update_path, # path helpers
to: :@template
# Sets a context for helpers and gets available locales for the record, if it's present
#
# @param template [ActionView] the context
# @param record [ActiveRecord]
#
def initialize(template, record=nil)
@template = template
unless record.nil?
# fallback to the default globalize method
@available_locales = record.respond_to?(:available_locales) ? record.available_locales : record.translated_locales
end
end
# Renders and concatenates locale and currency widgets
def render
render_locales + render_currencies
end
private
# Renders locales switcher
def render_locales
wrapper(:locale) do
Rails.application.config.i18n.available_locales.collect do |locale|
if locale == I18n.locale
content_tag :span, locale
else
locale_path = available_in?(locale) ? params.merge(locale: locale) : root_path(locale: locale)
link_to locale.to_s, locale_path
end
end.join.html_safe
end
end
# Renders currency switcher
def render_currencies
wrapper(:currency) do
Rails.application.config.available_currencies.collect do |currency|
if currency == current_currency.id
content_tag :span, current_currency.symbol
else
link_to Money::Currency.find(currency).symbol, settings_update_path(currency: currency, locale: nil) unless current_currency.id == currency
end
end.join.html_safe
end
end
# Checks if the current record is available in given locale.
#
# No need to check if translated_record is unset --> current action is always translated
#
# @param locale [Symbol]
# @return [Boolean] availability
#
def available_in?(locale)
@available_locales.nil? || @available_locales.include?(locale)
end
# Wraps i18n options into a common markup
def wrapper(name)
content_tag :div, class: "select-i18n select-i18n--#{name}" do
t("shared.footer.#{name}").html_safe +
content_tag(:div, class: 'select-i18n__options') do
yield
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment