configman 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 0b6a12b4c7b56681598b3685bbc6ed62510477f16886a4746ee1b1c262e1ef7d
4
+ data.tar.gz: 863b74da2182c750dced1a5b0e4800f1585e9da050df124051cd882606b234e3
5
+ SHA512:
6
+ metadata.gz: f3e999e4387a21034b7792ad77744d863142a36b796d04a29f7b78aa1894cf2996d3a16f3f96aa482c53889e050ca4364ca5c6a8449f787cd8f9a7812a48cd32
7
+ data.tar.gz: 69e1c3e1ce18108b94cb4d63c00a819502d7ebacfd752850e635ebcd71d416d8b076c18ea053cc4be7b3d33669628fcf847143d46952a48c87782332c7560ecb
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,13 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.6
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at ceo@pixelatedstudios.net. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/LICENSE ADDED
@@ -0,0 +1,71 @@
1
+ PixelRidge Business Exclusive General Public Use License for Software Executables (PixelRidge-BEGPULSE)
2
+
3
+ ## Version 1.3
4
+
5
+ ### Preamble
6
+
7
+ This License governs the terms under which the software ("Software") provided by PixelRidge Softworks ("Licensor") may be used, modified, and distributed.
8
+
9
+ ### 1. Definitions
10
+
11
+ - **Software**: The original software and associated documentation provided under this license.
12
+ - **Business Purposes**: Any activity designed with the main intent to generate revenue or profit.
13
+ - **Modification**: Any change or addition to the Software's source code or executable.
14
+ - **Distribution**: The act of making the Software available to third parties.
15
+ - **Contributor**: Any individual or entity that modifies or distributes the Software.
16
+
17
+ ### 2. License Grant
18
+
19
+ Subject to the terms and conditions of this License, Licensor hereby grants you a worldwide, non-exclusive, non-transferable, non-sublicensable license to use and modify the Software.
20
+
21
+ ### 3. Attribution
22
+
23
+ You must provide attribution to the Licensor by including a plain-view URI (or link) to the Licensor's website. This link must be easily visible to all users and not hidden under any circumstances. It should be noted that this should only apply in the event that it can. In the event a public link is impossible due to the nature of the usage of the Software, it's expected that attribution be given in a way such that the attribution complies with the Open Source Initiative standards for Open Source Attribution.
24
+
25
+ ### 4. Business Use
26
+
27
+ If you wish to use the Software for Business Purposes, you must obtain written permission from PixelRidge Softworks. Failure to obtain such permission will result in a violation of this License.
28
+
29
+ ### 5. Indemnification
30
+
31
+ You agree to indemnify, defend, and hold harmless PixelRidge Softworks and its affiliates from and against any and all claims, damages, losses, liabilities, costs, and expenses arising out of or relating to your use or distribution of the Software.
32
+
33
+ ### 6. No Warranty and Limitation of Liability
34
+
35
+ The Software is provided "AS-IS," without any warranty of any kind, either express or implied. The Software is designed to be highly secure but will only be as secure as the system on which it is deployed. On an insecure system, the Software may exacerbate existing security issues. PixelRidge Softworks shall not be liable for any damages arising from the use of the Software.
36
+
37
+ ### 7. Updates and Versioning
38
+
39
+ PixelRidge Softworks may or may not provide updates to the Software in the future. There is no obligation to provide updates or support for the Software. The latest version of this License shall always be considered the governing terms. PixelRidge Softworks will provide reasonable notice in the event of a license change. Notice shall be provided via email. Due to spam laws, we cannot just email you. You may opt into our specialized mailing list for licensing on our website.
40
+
41
+ ### 8. Source Code Availability
42
+
43
+ Any modifications to the Software must remain open-source and source-available in their entirety unless another agreement with the Licensor is formed.
44
+
45
+ ### 9. Compliance Monitoring
46
+
47
+ Compliance with this License may or may not be monitored by PixelRidge Softworks. You grant PixelRidge Softworks the right to monitor for compliance as it sees fit.
48
+
49
+ ### 10. Data Collection
50
+
51
+ If the Software collects any data, such data will be used in accordance with PixelRidge Softworks' privacy policy.
52
+
53
+ ### 11. Export Control
54
+
55
+ You agree not to use the Software in violation of any export laws or regulations.
56
+
57
+ ### 12. Termination and Revocation
58
+
59
+ This License will automatically terminate if you fail to comply with any of its terms or conditions. Revocation is allowed only in the event of a violation of this License.
60
+
61
+ ### 13. Dispute Resolution
62
+
63
+ Any disputes arising out of this License shall be resolved through arbitration in Alberta, Canada.
64
+
65
+ ### 14. Jurisdiction
66
+
67
+ This License shall be governed by the laws of Alberta, Canada.
68
+
69
+ ### 15. Miscellaneous
70
+
71
+ This License constitutes the entire agreement between you and PixelRidge Softworks concerning the Software.
data/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # ConfigMan
2
+
3
+ A Ruby Gem for automating your Config handling
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require 'rubocop/rake_task'
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/configman.gemspec ADDED
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/configman/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'configman'
7
+ spec.version = ConfigMan::VERSION
8
+ spec.authors = ['PixelRidge Softworks']
9
+ spec.email = ['vetheon@pixelridgesoftworks.com']
10
+
11
+ spec.summary = 'A Ruby Gem for automating your configs!'
12
+ spec.homepage = 'https://git.pixelridgesoftworks.com/PixelRidge-Softworks/ConfigMan'
13
+ spec.license = 'PixelRidge-BEGPULSE'
14
+ spec.required_ruby_version = '>= 3.2.2'
15
+
16
+ spec.metadata['homepage_uri'] = spec.homepage
17
+ spec.metadata['source_code_uri'] = 'https://git.pixelridgesoftworks.com/PixelRidge-Softworks/ConfigMan'
18
+
19
+ # Specify which files should be added to the gem when it is released.
20
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
21
+ spec.files = Dir.chdir(__dir__) do
22
+ `git ls-files -z`.split("\x0").reject do |f|
23
+ (File.expand_path(f) == __FILE__) ||
24
+ f.start_with?(*%w[bin/ test/ spec/ features/ .git .circleci appveyor Gemfile])
25
+ end
26
+ end
27
+ spec.require_paths = ['lib']
28
+
29
+ # Uncomment to register a new dependency of your gem
30
+ # spec.add_dependency "example-gem", "~> 1.0"
31
+ spec.add_dependency 'inifile'
32
+
33
+ # For more information and examples about making a new gem, check out our
34
+ # guide at: https://bundler.io/guides/creating_gem.html
35
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ConfigMan
4
+ module Modules
5
+ module API
6
+ def self.populate_defaults
7
+ {
8
+ 'api_endpoint' => 'https://api.example.com',
9
+ 'api_key' => 'your_api_key_here',
10
+ 'rate_limit' => 1000
11
+ }
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ConfigMan
4
+ module Modules
5
+ module Cache
6
+ def self.populate_defaults
7
+ {
8
+ 'cache_type' => 'Redis',
9
+ 'host' => 'localhost',
10
+ 'port' => 6379
11
+ }
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ConfigMan
4
+ module Modules
5
+ module Database
6
+ def self.populate_defaults
7
+ {
8
+ 'db_host' => 'localhost',
9
+ 'db_port' => 3306,
10
+ 'db_user' => 'root',
11
+ 'db_password' => 'password',
12
+ 'db_name' => 'my_database'
13
+ }
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ConfigMan
4
+ module Modules
5
+ module Email
6
+ def self.populate_defaults
7
+ {
8
+ 'smtp_server' => 'smtp.example.com',
9
+ 'smtp_port' => 587,
10
+ 'smtp_user' => 'user@example.com',
11
+ 'smtp_password' => 'password_here',
12
+ 'smtp_protocol' => 'SSL/TLS'
13
+ }
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ConfigMan
4
+ module Modules
5
+ module FileStorage
6
+ def self.populate_defaults
7
+ {
8
+ 'storage_type' => 'local',
9
+ 'cloud_provider' => 'none',
10
+ 'local_path' => '/path/to/storage'
11
+ }
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ConfigMan
4
+ module Modules
5
+ module Localization
6
+ def self.populate_defaults
7
+ {
8
+ 'language' => 'en',
9
+ 'time_zone' => 'UTC',
10
+ 'encoding' => 'UTF-8'
11
+ }
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ConfigMan
4
+ module Modules
5
+ module Logging
6
+ def self.populate_defaults
7
+ {
8
+ 'log_level' => 'info',
9
+ 'log_file' => 'application.log',
10
+ 'log_rotation' => 'daily'
11
+ }
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ # config_util.rb
4
+
5
+ module ConfigMan
6
+ module Utils
7
+ def self.sort_into_sections(config_hash, expected_keys, loaded_modules)
8
+ # Convert loaded_modules to uppercase for comparison
9
+ loaded_modules_upcase = loaded_modules.map(&:upcase)
10
+
11
+ sorted_config = Hash.new { |hash, key| hash[key] = {} }
12
+
13
+ config_hash.each do |key, value|
14
+ section_found = false
15
+
16
+ expected_keys.each do |section, keys|
17
+ # Skip the section if it's not in the loaded modules
18
+ next unless loaded_modules_upcase.include?(section.upcase)
19
+
20
+ # Skip the key if it's not in the expected keys for this section
21
+ next unless keys.include?(key)
22
+
23
+ sorted_config[section][key] = value
24
+ section_found = true
25
+ break
26
+ end
27
+
28
+ # If the key doesn't match any of the expected keys, put it in the 'General' section
29
+ sorted_config['General'][key] = value unless section_found
30
+ end
31
+
32
+ sorted_config
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'inifile'
4
+ require_relative '../modules/utils'
5
+
6
+ module ConfigMan
7
+ module Parsers
8
+ module INI
9
+ CONFIG_FILE_PATH = File.join(Dir.pwd, '.config').freeze
10
+
11
+ # Parse the .config file and return a hash of the configuration values
12
+ def self.parse(file_path)
13
+ raise ArgumentError, "File not found: #{file_path}" unless File.exist?(file_path)
14
+
15
+ ini = IniFile.load(file_path)
16
+ parsed_config = ini.to_h
17
+
18
+ raise ArgumentError, "Invalid INI format in #{file_path}" unless parsed_config.is_a?(Hash)
19
+
20
+ parsed_config
21
+ end
22
+
23
+ def self.update(key, new_value)
24
+ existing_config = parse(CONFIG_FILE_PATH)
25
+ section, key = key.split('.', 2)
26
+ existing_config[section] ||= {}
27
+ existing_config[section][key] = new_value
28
+
29
+ ini = IniFile.new(content: existing_config)
30
+ ini.write(filename: CONFIG_FILE_PATH)
31
+ end
32
+
33
+ def self.write(config_hash)
34
+ # Access the loaded modules and expected keys from the main class
35
+ loaded_modules = ConfigMan.used_modules
36
+ expected_keys = ConfigMan.expected_keys
37
+ puts "Debug: About to pass these #{expected_keys} to the utils module"
38
+ puts "and these #{loaded_modules}"
39
+ puts "and this #{config_hash}"
40
+
41
+ # Sort the keys into their respective sections
42
+ sorted_config = Utils.sort_into_sections(config_hash, expected_keys, loaded_modules)
43
+
44
+ # Debug statement to output the sorted_config
45
+ #puts 'Debug: About to write the following sorted_config to INI file:'
46
+ #p sorted_config
47
+
48
+ # Write the sorted config to the INI file
49
+ ini = IniFile.new(content: sorted_config)
50
+ ini.write(filename: CONFIG_FILE_PATH)
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require_relative '../modules/utils'
5
+
6
+ module ConfigMan
7
+ module Parsers
8
+ module JSON
9
+ CONFIG_FILE_PATH = File.join(Dir.pwd, '.config').freeze
10
+
11
+ # Parse the .config file and return a hash of the configuration values
12
+ def self.parse(file_path)
13
+ raise ArgumentError, "File not found: #{file_path}" unless File.exist?(file_path)
14
+
15
+ file_content = File.read(file_path)
16
+ parsed_config = ::JSON.parse(file_content)
17
+
18
+ raise ArgumentError, "Invalid JSON format in #{file_path}" unless parsed_config.is_a?(Hash)
19
+
20
+ parsed_config
21
+ end
22
+
23
+ def self.update(key, new_value)
24
+ existing_config = parse(CONFIG_FILE_PATH)
25
+ existing_config[key] = new_value
26
+
27
+ File.open(CONFIG_FILE_PATH, 'w') do |file|
28
+ file.write(::JSON.pretty_generate(existing_config))
29
+ end
30
+ end
31
+
32
+ def self.write(config_hash)
33
+ # Access the loaded modules and expected keys from the main class
34
+ loaded_modules = ConfigMan.used_modules
35
+ expected_keys = ConfigMan.expected_keys
36
+
37
+ # Use the utility method to sort the keys into their respective sections
38
+ sorted_config = Utils.sort_into_sections(config_hash, expected_keys, loaded_modules)
39
+
40
+ File.open(CONFIG_FILE_PATH, 'w') do |file|
41
+ file.write(::JSON.pretty_generate(sorted_config))
42
+ end
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rexml/document'
4
+ require 'rexml/formatters/pretty'
5
+ require_relative '../modules/utils'
6
+
7
+ module ConfigMan
8
+ module Parsers
9
+ module XML
10
+ CONFIG_FILE_PATH = File.join(Dir.pwd, '.config').freeze
11
+
12
+ # Parse the .config file and return a hash of the configuration values
13
+ # Parse the .config file and return a hash of the configuration values
14
+ def self.parse(file_path)
15
+ raise ArgumentError, "File not found: #{file_path}" unless File.exist?(file_path)
16
+
17
+ xml_file = File.new(file_path)
18
+ document = REXML::Document.new(xml_file)
19
+ parsed_config = {}
20
+
21
+ # Recursive lambda to parse nested elements
22
+ parse_element = lambda do |element|
23
+ if element.has_elements?
24
+ element_hash = {}
25
+ element.each_element do |child|
26
+ element_hash[child.name] = parse_element.call(child)
27
+ end
28
+ element_hash
29
+ else
30
+ element.text
31
+ end
32
+ end
33
+
34
+ document.elements.each('config/*') do |element|
35
+ parsed_config[element.name] = parse_element.call(element)
36
+ end
37
+
38
+ raise ArgumentError, "Invalid XML format in #{file_path}" unless parsed_config.is_a?(Hash)
39
+
40
+ parsed_config
41
+ end
42
+
43
+ def self.update(key, new_value)
44
+ existing_config = parse(CONFIG_FILE_PATH)
45
+ existing_config[key] = new_value
46
+
47
+ doc = REXML::Document.new
48
+ doc.add_element('config')
49
+ existing_config.each { |k, v| doc.root.add_element(k).text = v }
50
+
51
+ formatter = REXML::Formatters::Pretty.new
52
+ File.open(CONFIG_FILE_PATH, 'w') do |file|
53
+ formatter.write(doc, file)
54
+ end
55
+ end
56
+
57
+ def self.write(config_hash)
58
+ # Access the loaded modules and expected keys from the main class
59
+ loaded_modules = ConfigMan.used_modules
60
+ expected_keys = ConfigMan.expected_keys
61
+
62
+ # Sort the keys into their respective sections
63
+ sorted_config = Utils.sort_into_sections(config_hash, expected_keys, loaded_modules)
64
+
65
+ doc = REXML::Document.new
66
+ doc.add_element('config')
67
+
68
+ sorted_config.each do |section, section_data|
69
+ section_element = doc.root.add_element(section)
70
+ section_data.each { |k, v| section_element.add_element(k).text = v }
71
+ end
72
+
73
+ formatter = REXML::Formatters::Pretty.new
74
+ File.open(CONFIG_FILE_PATH, 'w') do |file|
75
+ formatter.write(doc, file)
76
+ end
77
+ end
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'yaml'
4
+ require_relative '../modules/utils'
5
+
6
+ module ConfigMan
7
+ module Parsers
8
+ module YAML
9
+ CONFIG_FILE_PATH = File.join(Dir.pwd, '.config').freeze
10
+
11
+ # Parse the .config file and return a hash of the configuration values
12
+ def self.parse(file_path)
13
+ raise ArgumentError, "File not found: #{file_path}" unless File.exist?(file_path)
14
+
15
+ parsed_config = ::YAML.load_file(file_path)
16
+
17
+ raise ArgumentError, "Invalid YAML format in #{file_path}" unless parsed_config.is_a?(Hash)
18
+
19
+ parsed_config
20
+ end
21
+
22
+ def self.update(key, new_value)
23
+ existing_config = parse(CONFIG_FILE_PATH)
24
+ existing_config[key] = new_value
25
+
26
+ File.open(CONFIG_FILE_PATH, 'w') do |file|
27
+ file.write(existing_config.to_yaml)
28
+ end
29
+ end
30
+
31
+ def self.write(config_hash)
32
+ # Access the loaded modules and expected keys from the main class
33
+ loaded_modules = ConfigMan.used_modules
34
+ expected_keys = ConfigMan.expected_keys
35
+
36
+ # Use the utility method to sort the keys into their respective sections
37
+ sorted_config = Utils.sort_into_sections(config_hash, expected_keys, loaded_modules)
38
+
39
+ File.open(CONFIG_FILE_PATH, 'w') do |file|
40
+ file.write(sorted_config.to_yaml)
41
+ end
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ConfigMan
4
+ VERSION = '1.0.0'
5
+ end
data/lib/configman.rb ADDED
@@ -0,0 +1,179 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'configman/version'
4
+ require_relative 'configman/parsers/json'
5
+ require_relative 'configman/parsers/ini'
6
+ require_relative 'configman/parsers/xml'
7
+ require_relative 'configman/parsers/yaml'
8
+
9
+ module ConfigMan # rubocop:disable Metrics/ModuleLength, Style/Documentation
10
+ class Error < StandardError; end
11
+
12
+ @config_values = {}
13
+ @used_modules = []
14
+ @loaded_parser = nil
15
+ @custom_modules = []
16
+
17
+ EXPECTED_KEYS = {
18
+ 'API' => %w[api_endpoint api_key rate_limit],
19
+ 'Cache' => %w[cache_type host port],
20
+ 'Database' => %w[db_host db_port db_user db_password db_name],
21
+ 'Email' => %w[smtp_server smtp_port smtp_user smtp_password smtp_protocol],
22
+ 'FileStorage' => %w[storage_type cloud_provider local_path],
23
+ 'Localization' => %w[language time_zone encoding],
24
+ 'Logging' => %w[log_level log_file log_rotation]
25
+ }.freeze
26
+
27
+ def self.expected_keys
28
+ EXPECTED_KEYS
29
+ end
30
+
31
+ # register any custom modules the user provides
32
+ def self.register_module(file_path)
33
+ raise ArgumentError, "File not found: #{file_path}" unless File.exist?(file_path)
34
+
35
+ require file_path
36
+
37
+ module_name = File.basename(file_path, '.rb').capitalize
38
+ mod_class = Object.const_get(module_name)
39
+
40
+ unless mod_class.respond_to?(:populate_defaults)
41
+ raise ArgumentError, "Custom module must implement a 'populate_defaults' method"
42
+ end
43
+
44
+ @custom_modules ||= []
45
+ @custom_modules << mod_class
46
+ puts "Custom modules: #{@custom_modules.inspect}" # Debug line
47
+ end
48
+
49
+ def self.used_modules
50
+ @used_modules
51
+ end
52
+
53
+ # Setup ConfigMan with presets
54
+ def self.setup(default_modules, custom_options = {})
55
+ # Check if a parser is loaded
56
+ raise 'No parser module loaded. Please load a parser module before calling setup.' if @loaded_parser.nil?
57
+
58
+ final_config = {}
59
+
60
+ # Remove parser names from default_modules
61
+ default_modules = default_modules.reject { |mod| %w[json ini xml yaml].include?(mod.downcase) }
62
+
63
+ # Populate defaults from built-in modules
64
+ default_modules.each do |mod|
65
+ mod_class = Object.const_get("ConfigMan::Modules::#{mod}")
66
+ final_config.merge!(mod_class.populate_defaults)
67
+ end
68
+
69
+ # Populate defaults from custom modules
70
+ @custom_modules.each do |mod_class|
71
+ final_config.merge!(mod_class.populate_defaults)
72
+ end
73
+
74
+ # Add custom options
75
+ final_config.merge!(custom_options) unless custom_options.empty?
76
+
77
+ # Write to the config file using the appropriate parser
78
+ parser_module = Object.const_get("ConfigMan::Parsers::#{@loaded_parser.upcase}")
79
+ parser_module.write(final_config)
80
+ end
81
+
82
+ # Generate a .config file in the working directory
83
+ def self.generate_config_file(final_config)
84
+ File.open('.config', 'w') do |file|
85
+ case @loaded_parser
86
+ when 'json'
87
+ file.write(JSON.pretty_generate(final_config))
88
+ when 'yaml'
89
+ require 'yaml'
90
+ file.write(final_config.to_yaml)
91
+ when 'xml'
92
+ require 'rexml/document'
93
+ xml = REXML::Document.new
94
+ xml.add_element('config', final_config)
95
+ formatter = REXML::Formatters::Pretty.new
96
+ formatter.write(xml, file)
97
+ when 'ini'
98
+ require 'inifile'
99
+ ini = IniFile.new
100
+ ini['default'] = final_config
101
+ file.write(ini.to_s)
102
+ else
103
+ file.write(JSON.pretty_generate(final_config)) # Default to JSON
104
+ end
105
+ end
106
+ end
107
+
108
+ # Lazy loading of modules and parsers
109
+ def self.load_modules(module_names)
110
+ module_names.each do |module_name|
111
+ if %w[json ini xml yaml].include?(module_name.downcase)
112
+ # It's a parser
113
+ require_relative "configman/parsers/#{module_name.downcase}"
114
+ @loaded_parser = module_name.downcase
115
+ else
116
+ # It's a regular module
117
+ require_relative "configman/modules/#{module_name.downcase}"
118
+ end
119
+ @used_modules << module_name.downcase
120
+ end
121
+ end
122
+
123
+ # Cleanup unused modules
124
+ def self.cleanup_unused_modules
125
+ # List of all available modules
126
+ all_modules = %w[database logging api ini yaml]
127
+
128
+ # Calculate modules to remove
129
+ remove_modules = all_modules - @used_modules
130
+
131
+ # Remove unnecessary modules
132
+ remove_modules.each do |mod|
133
+ module_path = File.join(__dir__, 'modules', "#{mod}.rb")
134
+ File.delete(module_path) if File.exist?(module_path)
135
+ end
136
+ end
137
+
138
+ # Load configurations from the .config file
139
+ def self.load
140
+ config_file_path = File.join(Dir.pwd, '.config')
141
+ parsed_config = send_to_parser(config_file_path)
142
+
143
+ parsed_config.each do |module_name, config|
144
+ define_singleton_method(module_name) do
145
+ config
146
+ end
147
+ end
148
+ end
149
+
150
+ # Delegate to the appropriate parser to parse the file
151
+ def self.send_to_parser(file_path)
152
+ raise ArgumentError, 'No parser loaded' unless @loaded_parser
153
+
154
+ parser_module = Object.const_get("ConfigMan::Parsers::#{@loaded_parser.upcase}")
155
+
156
+ raise ArgumentError, "Invalid parser: #{@loaded_parser}" unless parser_module.respond_to?(:parse)
157
+
158
+ parsed_config = parser_module.parse(file_path)
159
+ @config_values.merge!(parsed_config)
160
+ end
161
+
162
+ def self.fetch(key)
163
+ @config_values[key] || raise(%(Configuration key "#{key}" not found.))
164
+ end
165
+
166
+ # Handle undefined methods to fetch config values
167
+ def self.method_missing(method_name, *args, &block)
168
+ if @config_values.key?(method_name)
169
+ @config_values[method_name]
170
+ else
171
+ super
172
+ end
173
+ end
174
+
175
+ # Respond to missing methods
176
+ def self.respond_to_missing?(method_name, include_private = false)
177
+ @config_values.key?(method_name) || super
178
+ end
179
+ end
data/sig/configman.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module ConfigMan
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,81 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: configman
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - PixelRidge Softworks
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2023-10-27 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: inifile
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ description:
28
+ email:
29
+ - vetheon@pixelridgesoftworks.com
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - ".rspec"
35
+ - ".rubocop.yml"
36
+ - CODE_OF_CONDUCT.md
37
+ - LICENSE
38
+ - README.md
39
+ - Rakefile
40
+ - configman.gemspec
41
+ - lib/configman.rb
42
+ - lib/configman/modules/api.rb
43
+ - lib/configman/modules/cache.rb
44
+ - lib/configman/modules/database.rb
45
+ - lib/configman/modules/email.rb
46
+ - lib/configman/modules/filestorage.rb
47
+ - lib/configman/modules/localization.rb
48
+ - lib/configman/modules/logging.rb
49
+ - lib/configman/modules/utils.rb
50
+ - lib/configman/parsers/ini.rb
51
+ - lib/configman/parsers/json.rb
52
+ - lib/configman/parsers/xml.rb
53
+ - lib/configman/parsers/yaml.rb
54
+ - lib/configman/version.rb
55
+ - sig/configman.rbs
56
+ homepage: https://git.pixelridgesoftworks.com/PixelRidge-Softworks/ConfigMan
57
+ licenses:
58
+ - PixelRidge-BEGPULSE
59
+ metadata:
60
+ homepage_uri: https://git.pixelridgesoftworks.com/PixelRidge-Softworks/ConfigMan
61
+ source_code_uri: https://git.pixelridgesoftworks.com/PixelRidge-Softworks/ConfigMan
62
+ post_install_message:
63
+ rdoc_options: []
64
+ require_paths:
65
+ - lib
66
+ required_ruby_version: !ruby/object:Gem::Requirement
67
+ requirements:
68
+ - - ">="
69
+ - !ruby/object:Gem::Version
70
+ version: 3.2.2
71
+ required_rubygems_version: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ requirements: []
77
+ rubygems_version: 3.4.20
78
+ signing_key:
79
+ specification_version: 4
80
+ summary: A Ruby Gem for automating your configs!
81
+ test_files: []