Sha256: 47a13e4e64049988b1e6ba797f9df9043aaae93de2e34ef3f6fdb07fa2119d69

Contents?: true

Size: 1.12 KB

Versions: 3

Compression:

Stored size: 1.12 KB

Contents

require 'yaml'

class Config
  CONFIG_FILE_PATH = "#{ENV['HOME']}/.local/share/fuck-facebook/config.yaml".freeze

  def self.option(*path, default: nil, type: nil)
    env_var = "FF_#{path.join('_').upcase}"
    path_strings = path.map(&:to_s)

    value = config.dig(*path_strings)
    value = ENV[env_var] if ENV[env_var]
    value = default if value.nil?

    cast_value_to_type(value, type)
  end

  def self.config
    create_config_file_if_not_exists!

    YAML.load_file(CONFIG_FILE_PATH)
  end

  private_class_method def self.create_config_file_if_not_exists!
    dirname = File.dirname(CONFIG_FILE_PATH)
    FileUtils.mkdir_p(dirname) unless File.directory?(dirname)
    File.write(CONFIG_FILE_PATH, '{}') unless File.exist?(CONFIG_FILE_PATH)
  end

  private_class_method def self.cast_value_to_type(value, type)
    case type
    when nil
      value
    when :boolean
      cast_value_to_boolean(value)
    when :float
      value.to_f
    end
  end

  private_class_method def self.cast_value_to_boolean(value)
    if [true, false].include?(value)
      value
    elsif value.is_a?(String)
      value == 'true'
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
fuck_facebook-0.5.4 src/config.rb
fuck_facebook-0.5.3 src/config.rb
fuck_facebook-0.5.2 src/config.rb