2019-05-03 06:17:27 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2013-06-23 11:35:06 +08:00
|
|
|
module SiteSettings; end
|
|
|
|
|
|
|
|
class SiteSettings::DbProvider
|
|
|
|
|
|
|
|
def initialize(model)
|
2014-03-31 09:34:01 +08:00
|
|
|
model.after_commit do
|
|
|
|
model.notify_changed!
|
|
|
|
end
|
|
|
|
|
2013-06-23 11:35:06 +08:00
|
|
|
@model = model
|
|
|
|
end
|
|
|
|
|
|
|
|
def all
|
|
|
|
return [] unless table_exists?
|
|
|
|
|
2015-09-09 21:34:53 +08:00
|
|
|
# Not leaking out AR records, cause I want all editing to happen via this API
|
2018-06-20 15:48:02 +08:00
|
|
|
DB.query("SELECT name, data_type, value FROM #{@model.table_name}")
|
2013-06-23 11:35:06 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def find(name)
|
|
|
|
return nil unless table_exists?
|
|
|
|
|
2015-09-09 21:34:53 +08:00
|
|
|
# Not leaking out AR records, cause I want all editing to happen via this API
|
2018-06-20 15:48:02 +08:00
|
|
|
DB.query("SELECT name, data_type, value FROM #{@model.table_name} WHERE name = ?", name)
|
2013-06-23 11:35:06 +08:00
|
|
|
.first
|
|
|
|
end
|
|
|
|
|
|
|
|
def save(name, value, data_type)
|
|
|
|
return unless table_exists?
|
|
|
|
|
2015-09-09 18:59:49 +08:00
|
|
|
model = @model.find_by(name: name)
|
2014-03-31 09:34:01 +08:00
|
|
|
model ||= @model.new
|
|
|
|
|
|
|
|
model.name = name
|
|
|
|
model.value = value
|
|
|
|
model.data_type = data_type
|
|
|
|
|
|
|
|
# save! used to ensure after_commit is called
|
2018-04-17 21:06:40 +08:00
|
|
|
model.save! if model.changed?
|
2013-06-23 11:35:06 +08:00
|
|
|
|
|
|
|
true
|
|
|
|
end
|
|
|
|
|
|
|
|
def destroy(name)
|
|
|
|
return unless table_exists?
|
|
|
|
|
|
|
|
@model.where(name: name).destroy_all
|
|
|
|
end
|
|
|
|
|
|
|
|
def current_site
|
|
|
|
RailsMultisite::ConnectionManagement.current_db
|
|
|
|
end
|
|
|
|
|
|
|
|
protected
|
|
|
|
|
|
|
|
# table is not in the db yet, initial migration, etc
|
|
|
|
def table_exists?
|
2017-08-07 15:37:42 +08:00
|
|
|
@table_exists ||= {}
|
2019-06-14 12:20:48 +08:00
|
|
|
@table_exists[current_site] ||= ActiveRecord::Base.connection.table_exists?(@model.table_name)
|
2013-06-23 11:35:06 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
end
|