Class: Omniconf::Adapter::ActiveRecord
- Inherits:
-
Base
- Object
- Base
- Omniconf::Adapter::ActiveRecord
show all
- Defined in:
- lib/omniconf/adapters/active_record.rb
Instance Attribute Summary
Attributes inherited from Base
#configuration, #source_id
Instance Method Summary
collapse
Methods inherited from Base
#reload_configuration!
Constructor Details
#initialize(id, params) ⇒ ActiveRecord
Returns a new instance of ActiveRecord.
6
7
8
9
10
11
12
13
14
15
16
|
# File 'lib/omniconf/adapters/active_record.rb', line 6
def initialize id, params
@source_id = id
defaults = {
:model => 'ConfigValue'
}
defaults.merge!({
:environment => Rails.env,
:config_file => File.join(Rails.root, 'config/database.yml')
}) if defined? Rails
@params = defaults.merge params
end
|
Instance Method Details
#load_configuration! ⇒ Object
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
# File 'lib/omniconf/adapters/active_record.rb', line 18
def load_configuration!
setup
@configuration = Configuration.new self
begin
records = @model.all
rescue ::ActiveRecord::StatementInvalid => e
Omniconf.logger.warn "Could not load #{@params[:model]} model, ignoring this configuration source."
return
end
hash = {}
records.map do |record|
key, value = record.key.split('.'), record.value
el = key[0..-2].inject(hash) {|r,e| r[e] ||= {} }
raise unless el[key.last].nil?
el[key.last] = value
end
@configuration = Configuration.new self, hash
Omniconf.merge_configuration! @source_id
end
|
#set_value(key, value) ⇒ Object
44
45
46
47
48
49
50
51
52
53
|
# File 'lib/omniconf/adapters/active_record.rb', line 44
def set_value(key, value)
key = key.join('.')
if item = @model.find_by_key(key)
item.value = value
else
item = @model.new(:key => key, :value => value)
end
item.save!
item.value
end
|
#setup ⇒ Object
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
# File 'lib/omniconf/adapters/active_record.rb', line 55
def setup
unless Object.const_defined? @params[:model]
unless ::ActiveRecord::Base.connected?
::ActiveRecord::Base.configurations = YAML::load(IO.read(@params[:config_file]))
::ActiveRecord::Base.establish_connection(@params[:environment])
end
klass = Class.new ::ActiveRecord::Base do
validates_uniqueness_of :key
serialize :value
end
Object.const_set @params[:model], klass
end
@model ||= @params[:model].constantize
end
|