Sha256: dfb2904e684e16ed15248b9e0c0e1d9d10812cb9886491489d0d68efb20c937a

Contents?: true

Size: 1.19 KB

Versions: 1

Compression:

Stored size: 1.19 KB

Contents

require 'active_support/core_ext/hash/reverse_merge'

module Titlezilla
  class Translator
    attr_reader :namespace, :controller_name, :action_name, :context

    def initialize(controller_path, action_name, context = {})
      @namespace, @controller_name = parse_namespace_and_controller_name(controller_path)
      @action_name = action_name.to_s.freeze
      @context = context
    end

    def title
      lookup(controller_name, map(action_name))
    end

    def application_title
      lookup('application')
    end

    def meta_title
      [title, application_title].compact.join(::Titlezilla.configuration.separator)
    end

    private

    def parse_namespace_and_controller_name(controller_path)
      parts = controller_path.to_s.split('/')
      parts.size > 1 ? parts.map(&:to_s).map(&:freeze) : [nil, parts[0].to_s.freeze]
    end

    def lookup(*key)
      t_key = [:titles, namespace, key].flatten.compact.join('.')
      i18n_set?(t_key) ? I18n.t(t_key, context) : nil
    end

    def map(action_name)
      (::Titlezilla.configuration.action_map[action_name.to_sym] || action_name).to_s.freeze
    end

    def i18n_set?(key)
      I18n.t(key, raise: true) rescue false
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
titlezilla-0.1.0 lib/titlezilla/translator.rb