Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

config.rb 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. require 'yaml'
  2. require 'fileutils'
  3. class CrossPost
  4. class Config
  5. DEFAULT_CONFIG_FOLDER = File.join Dir.home, '.config/cross-post'
  6. DEFAULT_CONFIG_FILE = 'config.yml'
  7. class SubConfig
  8. def initialize(config = {})
  9. @config = config
  10. end
  11. def each(&block)
  12. @config.each &block
  13. end
  14. def [](key)
  15. case key
  16. when String
  17. current = @config
  18. key.split(/\./).each do |k|
  19. current = current[k]
  20. return nil if current.nil?
  21. end
  22. current
  23. else
  24. @config[key]
  25. end
  26. end
  27. def fetch(key, default = nil)
  28. self[key] || default
  29. end
  30. def []=(key, value)
  31. case key
  32. when String
  33. *key, last = key.to_s.split(/\./)
  34. current = @config
  35. key.each do |k|
  36. next_ = current[k]
  37. case next_
  38. when nil
  39. next_ = current[k] = {}
  40. when Hash
  41. else
  42. raise "Invalid entry, Hash expected, had #{next_.class} (#{next_})"
  43. end
  44. current = next_
  45. end
  46. current[last] = value
  47. else
  48. @config[key] = value
  49. end
  50. end
  51. end
  52. class FifoSubConfig < SubConfig
  53. def initialize(size = 100)
  54. @size = size
  55. @keys = []
  56. super({})
  57. end
  58. def []=(key, value)
  59. @keys.delete key
  60. value = super key, value
  61. @keys << key
  62. while @keys.size > @size
  63. key = @keys.delete_at 0
  64. @config.delete key
  65. end
  66. value
  67. end
  68. end
  69. class FileSubConfig < SubConfig
  70. def initialize(file)
  71. @file = file
  72. super YAML.load_file @file
  73. end
  74. def put(key, value, save: false)
  75. self[key] = value
  76. self.save if save
  77. end
  78. def save
  79. LOGGER.debug "Saving #{@file}"
  80. yaml = YAML.dump @config
  81. File.write @file, yaml
  82. end
  83. end
  84. def initialize
  85. @configs = {}
  86. @dir = ENV.fetch 'CONFIG_FOLDER', DEFAULT_CONFIG_FOLDER
  87. file = ENV.fetch 'CONFIG_FILE', DEFAULT_CONFIG_FILE
  88. self.load :settings, file
  89. self.load :users
  90. self[:posts] = FifoSubConfig.new
  91. end
  92. def [](name)
  93. @configs[name]
  94. end
  95. def []=(name, value)
  96. @configs[name] = value
  97. end
  98. def load(name, file = nil)
  99. file ||= "#{name}.yml"
  100. file = File.join @dir, file
  101. FileUtils.touch file unless File.exist? file
  102. self[name] = FileSubConfig.new file
  103. end
  104. end
  105. end