2019-05-03 06:17:27 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2013-08-26 10:52:36 +08:00
|
|
|
# API to wrap up plugin store rows
|
|
|
|
class PluginStore
|
2017-11-15 23:10:20 +08:00
|
|
|
attr_reader :plugin_name
|
|
|
|
|
|
|
|
def initialize(plugin_name)
|
|
|
|
@plugin_name = plugin_name
|
|
|
|
end
|
|
|
|
|
|
|
|
def get(key)
|
|
|
|
self.class.get(plugin_name, key)
|
|
|
|
end
|
|
|
|
|
2018-08-02 00:42:40 +08:00
|
|
|
def get_all(keys)
|
|
|
|
self.class.get_all(plugin_name, keys)
|
|
|
|
end
|
|
|
|
|
2017-11-15 23:10:20 +08:00
|
|
|
def set(key, value)
|
|
|
|
self.class.set(plugin_name, key, value)
|
|
|
|
end
|
|
|
|
|
|
|
|
def remove(key)
|
|
|
|
self.class.remove(plugin_name, key)
|
|
|
|
end
|
|
|
|
|
2013-08-26 10:52:36 +08:00
|
|
|
def self.get(plugin_name, key)
|
2014-05-06 21:41:59 +08:00
|
|
|
if row = PluginStoreRow.find_by(plugin_name: plugin_name, key: key)
|
2013-08-26 10:52:36 +08:00
|
|
|
cast_value(row.type_name, row.value)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2018-08-02 00:42:40 +08:00
|
|
|
def self.get_all(plugin_name, keys)
|
|
|
|
rows = PluginStoreRow.where('plugin_name = ? AND key IN (?)', plugin_name, keys).to_a
|
|
|
|
|
|
|
|
Hash[rows.map { |row| [row.key, cast_value(row.type_name, row.value)] }]
|
|
|
|
end
|
|
|
|
|
2013-08-26 10:52:36 +08:00
|
|
|
def self.set(plugin_name, key, value)
|
2017-07-28 09:20:09 +08:00
|
|
|
hash = { plugin_name: plugin_name, key: key }
|
2014-08-19 20:40:23 +08:00
|
|
|
row = PluginStoreRow.find_by(hash) || PluginStoreRow.new(hash)
|
2013-08-26 10:52:36 +08:00
|
|
|
|
|
|
|
row.type_name = determine_type(value)
|
|
|
|
# nil are stored as nil
|
|
|
|
row.value =
|
|
|
|
if row.type_name == "JSON"
|
|
|
|
value.to_json
|
|
|
|
elsif value
|
|
|
|
value.to_s
|
|
|
|
end
|
|
|
|
|
|
|
|
row.save
|
|
|
|
end
|
|
|
|
|
2014-02-25 08:11:31 +08:00
|
|
|
def self.remove(plugin_name, key)
|
2014-02-26 00:26:35 +08:00
|
|
|
PluginStoreRow.where(plugin_name: plugin_name, key: key).destroy_all
|
2014-02-25 08:11:31 +08:00
|
|
|
end
|
|
|
|
|
2013-08-26 10:52:36 +08:00
|
|
|
def self.determine_type(value)
|
2014-03-10 17:22:59 +08:00
|
|
|
value.is_a?(Hash) || value.is_a?(Array) ? "JSON" : value.class.to_s
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.map_json(item)
|
|
|
|
if item.is_a? Hash
|
|
|
|
ActiveSupport::HashWithIndifferentAccess.new item
|
|
|
|
elsif item.is_a? Array
|
2017-07-28 09:20:09 +08:00
|
|
|
item.map { |subitem| map_json subitem }
|
2014-03-10 17:22:59 +08:00
|
|
|
else
|
|
|
|
item
|
|
|
|
end
|
2013-08-26 10:52:36 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def self.cast_value(type, value)
|
|
|
|
case type
|
2017-04-15 12:11:02 +08:00
|
|
|
when "Integer", "Fixnum" then value.to_i
|
2013-08-26 10:52:36 +08:00
|
|
|
when "TrueClass", "FalseClass" then value == "true"
|
2014-03-10 17:22:59 +08:00
|
|
|
when "JSON" then map_json(::JSON.parse(value))
|
2013-08-26 10:52:36 +08:00
|
|
|
else value
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|