Module: FlycalCli::Locale
- Defined in:
- lib/flycal_cli/locale.rb
Constant Summary collapse
- FALLBACK_LOCALE =
"en"
Class Method Summary collapse
- .current_locale ⇒ Object
- .day_abbr(date_or_time) ⇒ Object
- .day_name(date_or_time) ⇒ Object
- .format_long_date(date_or_time) ⇒ Object
- .interpolate(value, vars) ⇒ Object
- .lookup(hash, dotted_key) ⇒ Object
- .month_name(date_or_time) ⇒ Object
- .override!(locale) ⇒ Object
- .t(key, vars = {}) ⇒ Object
- .translations(locale) ⇒ Object
Class Method Details
.current_locale ⇒ Object
40 41 42 43 44 |
# File 'lib/flycal_cli/locale.rb', line 40 def current_locale Thread.current[:flycal_locale_override] || Config.locale rescue StandardError FALLBACK_LOCALE end |
.day_abbr(date_or_time) ⇒ Object
22 23 24 25 26 |
# File 'lib/flycal_cli/locale.rb', line 22 def day_abbr(date_or_time) idx = date_or_time.to_date.wday days = t("common.weekdays.abbr") days[idx] || date_or_time.strftime("%a") end |
.day_name(date_or_time) ⇒ Object
16 17 18 19 20 |
# File 'lib/flycal_cli/locale.rb', line 16 def day_name(date_or_time) idx = date_or_time.to_date.wday days = t("common.weekdays.full") days[idx] || date_or_time.strftime("%A").downcase end |
.format_long_date(date_or_time) ⇒ Object
34 35 36 37 38 |
# File 'lib/flycal_cli/locale.rb', line 34 def format_long_date(date_or_time) t = date_or_time.respond_to?(:to_time) ? date_or_time.to_time : date_or_time d = t.to_date "#{day_abbr(d).downcase} #{d.day} #{month_name(d)} #{d.year}" end |
.interpolate(value, vars) ⇒ Object
65 66 67 68 69 70 71 |
# File 'lib/flycal_cli/locale.rb', line 65 def interpolate(value, vars) return value unless value.is_a?(String) value.gsub(/%\{(\w+)\}/) do vars.fetch(Regexp.last_match(1).to_sym, Regexp.last_match(0)).to_s end end |
.lookup(hash, dotted_key) ⇒ Object
59 60 61 62 63 |
# File 'lib/flycal_cli/locale.rb', line 59 def lookup(hash, dotted_key) dotted_key.to_s.split(".").reduce(hash) do |acc, part| acc.is_a?(Hash) ? acc[part] : nil end end |
.month_name(date_or_time) ⇒ Object
28 29 30 31 32 |
# File 'lib/flycal_cli/locale.rb', line 28 def month_name(date_or_time) idx = date_or_time.to_date.month - 1 months = t("common.months.full") months[idx] || date_or_time.strftime("%B") end |
.override!(locale) ⇒ Object
46 47 48 |
# File 'lib/flycal_cli/locale.rb', line 46 def override!(locale) Thread.current[:flycal_locale_override] = locale.to_s if locale && !locale.to_s.strip.empty? end |
.t(key, vars = {}) ⇒ Object
11 12 13 14 |
# File 'lib/flycal_cli/locale.rb', line 11 def t(key, vars = {}) value = lookup(translations(current_locale), key) || lookup(translations(FALLBACK_LOCALE), key) || key interpolate(value, vars) end |
.translations(locale) ⇒ Object
50 51 52 53 54 55 56 57 |
# File 'lib/flycal_cli/locale.rb', line 50 def translations(locale) @cache ||= {} loc = locale.to_s @cache[loc] ||= begin path = File.("../../locales/#{loc}.json", __dir__) File.exist?(path) ? JSON.parse(File.read(path)) : {} end end |