Class: BlueprintConfig::Backend::ActiveRecord

Inherits:
Base
  • Object
show all
Defined in:
lib/blueprint_config/backend/active_record.rb

Constant Summary collapse

MISSING_TABLE_WARNING =
<<-WARNING.gsub(/^ */, '')
  =======================================================================
  Settings table not found. Please add the configuration table by running:

  rails generate blueprint_config:install
  rake db:migrate
  =======================================================================
WARNING

Instance Method Summary collapse

Methods inherited from Base

#nest_hash, #source

Constructor Details

#initialize(options = {}) ⇒ ActiveRecord

Returns a new instance of ActiveRecord.



19
20
21
22
23
24
25
# File 'lib/blueprint_config/backend/active_record.rb', line 19

def initialize(options = {})
  @options = options
  @updated_at = nil
  @last_checked_at = nil
  @configured = true
  @mutex = Thread::Mutex.new
end

Instance Method Details

#fresh?Boolean

Returns:

  • (Boolean)


52
53
54
55
56
57
58
59
60
61
# File 'lib/blueprint_config/backend/active_record.rb', line 52

def fresh?
  # if database is not create/configured yet - don't try to refresh settings from it
  return true if !@configured
  return true if @last_checked_at.present? && @last_checked_at > 1.second.ago

  @mutex.synchronize do
    @last_checked_at = Time.now
  end
  @updated_at.present? && @updated_at >= Setting.maximum(:updated_at)
end

#load_keysObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/blueprint_config/backend/active_record.rb', line 27

def load_keys
  @configured = true
  update_timestamp

  data = Setting.all.map { |s| { s.key => s.parsed_value } }.reduce(:merge) || {}
  return data.transform_keys(&:to_sym) unless @options[:nest]

  nest_hash(data, @options[:nest_separator] || '.')
rescue ::ActiveRecord::NoDatabaseError => e
  # database is not created yet
  @configured = false
  {}
rescue ::ActiveRecord::StatementInvalid => e
  @configured = false
  Rails.logger.warn(e.message)
  Rails.logger.warn(MISSING_TABLE_WARNING)
  {}
end

#update_timestampObject



46
47
48
49
50
# File 'lib/blueprint_config/backend/active_record.rb', line 46

def update_timestamp
  @mutex.synchronize do
    @updated_at = Setting.maximum(:updated_at)
  end
end