Class: Locomotive::Steam::Middlewares::MissingTranslations

Inherits:
Object
  • Object
show all
Defined in:
lib/locomotive/steam/middlewares/missing_translations.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, opts = {}) ⇒ MissingTranslations

Returns a new instance of MissingTranslations.


7
8
9
# File 'lib/locomotive/steam/middlewares/missing_translations.rb', line 7

def initialize(app, opts = {})
  @app = app
end

Instance Method Details

#call(env) ⇒ Object


11
12
13
14
15
# File 'lib/locomotive/steam/middlewares/missing_translations.rb', line 11

def call(env)
  find_and_persist_missing_translations(env['locomotive.site']) do
    @app.call(env)
  end
end

#find_and_persist_missing_translations(site) ⇒ Object


17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/locomotive/steam/middlewares/missing_translations.rb', line 17

def find_and_persist_missing_translations(site)
  translations = []

  subscription = ActiveSupport::Notifications.subscribe('steam.missing_translation') do |name, start, finish, id, payload|
    translations << { key: payload[:input], values: { payload[:input] => false } }
  end

  yield.tap do
    ActiveSupport::Notifications.unsubscribe(subscription)
    persist_missing_translations(site, translations) unless translations.empty?
  end
end

#persist_missing_translations(site, translations) ⇒ Object


30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/locomotive/steam/middlewares/missing_translations.rb', line 30

def persist_missing_translations(site, translations)
  new_translations = []

  translations.each do |attributes|
    if existing = site.translations.where(key: attributes[:key]).first
      # don't need to call the DB if we already have the values in DB
      next if existing.values == attributes[:values]

      existing.update_attribute :values, existing.values.merge(attributes[:values])
    else
      new_translations << attributes
    end
  end

  site.translations.create(new_translations) unless new_translations.empty?
end