harmoni 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: ce2973b7c51e052b1a35f925f561d79a499dd8b017db4019913db2e35c277c00
4
+ data.tar.gz: 697d4acd0d1b0959a16864205916c1c1dd5ed3dac39bc38a3c87ae10b5979fee
5
+ SHA512:
6
+ metadata.gz: ffd3136eb77a5714759ef9c226b8bd65a26349e570952d7c29764ea744eef4546e7929578d71d5c6da5b0361edf9676dad3f114cc5b728ff84ddfe3150e736c4
7
+ data.tar.gz: 2c7a45cdfe30e04e54bcd83b562205b9511cf0354d705387952dbf5d484d0e4576db2e572ceecabcf508415b59e8aa51dcd996221c7bc43022efbd90ab0a491d
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
12
+ *.gem
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.4.3
5
+ before_install: gem install bundler -v 1.16.2
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at d2sm10@hotmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in harmoni.gemspec
6
+ gemspec
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 Brandon Black
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,174 @@
1
+ # Harmoni
2
+
3
+ Harmoni is a very simple library made for keeping configuration files on disk in sync with configuration loaded into memory. This provides capabilities to more easily support hot loading of configuration or settings for running applications. It also adds several goodies to make interacting with your configurations easier, whether they are synchronized to a file or not.
4
+
5
+ Harmoni currently supports YAML and JSON files but may grow to include other formats in the future (as necessary).
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'harmoni'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install harmoni
22
+
23
+ ## Usage
24
+ First `require 'harmoni'`
25
+
26
+ Using Harmoni is very simple. To create or track a new configuration, you can do any of the following:
27
+
28
+ ```
29
+ # The simplest way to spin up a new config. This is not synchronized
30
+ # with a file on disk unless you pass sync: true
31
+ Harmoni.build('my-config.json')
32
+
33
+ # Same as :build but automatically sets sync: true so that the file on disk
34
+ # will be in sync with the settings in memory
35
+ Harmoni.sync('your-config.yml')
36
+
37
+ # Create a new instace of config. Specifying type: yaml will return and instance
38
+ # of Harmoni::Config::YAML instead of the barebones Harmoni::Config
39
+ Harmoni::Config.new(path: 'settings.yml', type: :yaml)
40
+
41
+ # Same as the example above but is called specifically on the YAML class
42
+ Harmoni::YAML.new(path: 'settings.yml')
43
+ ```
44
+
45
+ Both Harmoni.build and Harmoni.sync will automatically detect the appropriate adapter to use based on the path provided. If the path already exists, the adapters will ensure the content fits their parsing. So a file named bad-idea.json that is actually YAML will appropriately be detected as YAML, despite the extension mismatch.
46
+
47
+ If the file does not already exist, the adapter will be determined based off of the extension. So passing a path of "config.json" will create an instance of Harmoni::JSON. The file will then automatically be created the first time :save is invoked.
48
+
49
+ If for any reason the auto detection fails or you do not want to rely on it, you can also specify the adapter to use by passing the keyword :type to the constructor. The current adapters available can be specified as type: :yaml or type: :json.
50
+
51
+ ### Setting and Getting Values
52
+
53
+ Harmoni heavily uses BBLib::HashPath under the hood to manage your configuration. This means you can use the hash path notation to set and get nested values (even recursively!). For an example, look at the code below.
54
+
55
+ #### Get
56
+ ```
57
+ conf = Harmoni.sync('/tmp/settings.yml', configuration: { settings: { general: { user: 'bblack16' } } })
58
+
59
+ p conf.get('settings.general.user')
60
+ # => "bblack16"
61
+
62
+ # You could also do this:
63
+ conf['settings.general.user']
64
+
65
+ # Recursively
66
+ conf.get('settings..user')
67
+ ```
68
+ Note that :get will return the first matching value, but when using recursive paths it is possible to have multiple results. If you wish to see all matches use :get_all instead.
69
+
70
+ Additionally, you can retrieve values for root level keys by simply calling them on the configuration object.
71
+
72
+ ```
73
+ conf = Harmoni.build('config.yml', default: { active: true })
74
+
75
+ puts conf.active
76
+ # => true
77
+ ```
78
+
79
+ #### Set
80
+ You can also set values deeply using the set or [] method.
81
+ ```
82
+ conf.set('my.nested.value', 99)
83
+
84
+ p conf.configuration
85
+ # => { my: { nested: { value: 99 } } }
86
+
87
+ # set also takes hashes
88
+ conf.set(active: true, count: 100)
89
+ ```
90
+
91
+ ### Synchronization
92
+
93
+ A config object does not have sync enabled upstream (from file) or downstream (to file) by default. There are several ways to enable this behavior:
94
+
95
+ ```
96
+ conf = Harmoni.build('database.json')
97
+
98
+ # Turn on sync from file to memory
99
+ conf.sync_up = true
100
+
101
+ # Turn on sync from memory to file
102
+ conf.sync_down = true
103
+
104
+ # Or turn both up and down on at once
105
+ conf.sync = true
106
+
107
+ # Or specify sync options during instantiation
108
+ # NOTE: There is no need to combine :sync with :sync_up and/or :sync down,
109
+ # it is shown below for illustrative purposes only
110
+ conf = Harmoni.build('database.json', sync_up: true, sync: true, sync_down: true)
111
+ ```
112
+
113
+ NOTE: Using Harmoni.sync() to create your config will automatically enable sync.
114
+
115
+ #### Sync Up
116
+
117
+ When sync up is enabled a file watcher thread is spun up within the instance of the config class. This thread will monitor the related file for changes and reload it and merge in changes whenever the mtime is changed. There are several behaviors you can tweak based on preference or use case. NOTE: All settings below can be passed to the :build, :sync or :new methods on instantiation.
118
+
119
+ - __interval__ [default: 1]: How often (in seconds) to check the file on disk for changes. The higher this is the more CPU it will require (especially when dealing with larger files).
120
+ - __prefer_memory__ [default: false]: When set to false changes on disk have precedence over changes in memory. That is to say, changes on disk are merged over top of configuration held in memory. When set to true the opposite occurs.
121
+ - __persist_memory__ [default: false]: When set to false any changes made in memory are overwritten or wiped out when reloading configuration from disk. When set to true changes are merged in to memory instead. This is useful when you want the file on disk to be the sole source-of-truth for your config.
122
+
123
+ #### Sync Down
124
+
125
+ When sync down is enabled any changes made using commands like :set or :[]= will force the configuration to save itself to disk. This keeps changes in memory in sync with those in the configuration file on disk.
126
+
127
+ ### Event Hooks
128
+
129
+ There are currently two events that can be hooked. Details for each can be found in the following sub sections. Both hooks can be set by calling their respective setter or by passing them in as named arguments to :build, :sync or :new.
130
+
131
+ #### on_reload
132
+
133
+ on_reload can be passed a Proc or lambda to be executed any time the configuration is reloaded from disk. Reloads occur whenever the file's mtime is changed or if :reload is called manually. The configuration is passed in to the block as the only argument.
134
+
135
+
136
+ ```
137
+ conf = Harmoni.sync('example.json', on_change: proc { |config| puts 'Config reloaded!' })
138
+ ```
139
+
140
+ #### on_change
141
+
142
+ on_change also takes a Proc or lambda but is called any time a reload is called that contains differences from the current configuration. Two arguments are passed to the block. The first is the full configuration, just like in on_reload but the second is a hash containing only the values that have changed (including nested changes). If a reload occurs that does not come with any changes, this hook will not be called.
143
+
144
+ ```
145
+ conf = Harmoni.sync('test.yml', on_change: proc { |config, changes| puts "Got changes: #{changes}" })
146
+ ```
147
+
148
+ ### Defaults and Overlays
149
+
150
+ Harmoni also provides a mechanism to specify layers of configuration. You can specify a default configuration that the provided configuration (from disk or memory) will be merged over. This gives you an easy way to ensure certain keys exist and have a default value if they are not otherwise specified. You can also provide an overlay configuration that will be applied over the top of the configuration read in or set during run time. This allows you to prevent users from changing certain settings on disk or in memory.
151
+
152
+ The full precedence for merging each of the configs is as follows:
153
+
154
+ default_configuration -> configuration -> overlay_configuration
155
+
156
+ Both :overlay_configuration and :default_configuration can be provided as named arguments on instantiation of via their respective setters. They are also aliased to the short methods :defaults and :overlay,
157
+
158
+ ## Development
159
+
160
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
161
+
162
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
163
+
164
+ ## Contributing
165
+
166
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/harmoni. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
167
+
168
+ ## License
169
+
170
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
171
+
172
+ ## Code of Conduct
173
+
174
+ Everyone interacting in the Harmoni project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/harmoni/blob/master/CODE_OF_CONDUCT.md).
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "harmoni"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,40 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "harmoni/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "harmoni"
8
+ spec.version = Harmoni::VERSION
9
+ spec.authors = ["Brandon Black"]
10
+ spec.email = ["d2sm10@hotmail.com"]
11
+
12
+ spec.summary = %q{Keep configuration on disk is sync with memory.}
13
+ spec.description = %q{Harmoni keeps configuration files in sync between memory and on disk for hot loading and other tasks.}
14
+ spec.homepage = "https://github.com/bblack16/harmoni"
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
18
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
19
+ # if spec.respond_to?(:metadata)
20
+ # spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
21
+ # else
22
+ # raise "RubyGems 2.0 or newer is required to protect against " \
23
+ # "public gem pushes."
24
+ # end
25
+
26
+ # Specify which files should be added to the gem when it is released.
27
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
28
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
29
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
30
+ end
31
+ spec.bindir = "exe"
32
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
33
+ spec.require_paths = ["lib"]
34
+
35
+ spec.add_development_dependency "bundler", "~> 1.16"
36
+ spec.add_development_dependency "rake", "~> 10.0"
37
+ spec.add_development_dependency "rspec", "~> 3.0"
38
+
39
+ spec.add_runtime_dependency 'bblib', '~> 2.0'
40
+ end
@@ -0,0 +1,18 @@
1
+ require 'bblib' unless defined?(BBLib::VERSION)
2
+ require 'json'
3
+ require 'yaml'
4
+
5
+ require_relative 'harmoni/version'
6
+ require_relative 'harmoni/config'
7
+ require_relative 'harmoni/types'
8
+
9
+ module Harmoni
10
+ def self.build(path, *args, **opts)
11
+ type = opts[:type] || Config.detect_type(path)
12
+ Config.new(*args, opts.merge(type: type, path: path))
13
+ end
14
+
15
+ def self.sync(file, *args, **opts)
16
+ build(file, *args, opts.merge(sync: true))
17
+ end
18
+ end
@@ -0,0 +1,182 @@
1
+ module Harmoni
2
+ class Config
3
+ include BBLib::Effortless
4
+ include BBLib::TypeInit
5
+ include BBLib::Delegator
6
+
7
+ # The path to the file this will be stored in
8
+ attr_str :path
9
+ # If true changes made to the file will be automatically loaded via a watcher thread
10
+ attr_bool :sync_up, default: false
11
+ # If true changes made in memory (via set/delete) will be made to the file on disk
12
+ attr_bool :sync_down, default: false
13
+ # The configuration loaded from disk and from commands like set
14
+ attr_hash :configuration, pre_proc: :process_config
15
+ # Default configurations. @configuration gets precedence and merges over these.
16
+ attr_hash :default_configuration, aliases: [:default, :defaults]
17
+ # Overlayed configuration. Has precedence and gets overlayed over configuration.
18
+ attr_hash :overlay_configuration, aliases: [:overlay]
19
+ # If true, changes made in memory have precedence over changes made on disk when merging
20
+ attr_bool :prefer_memory, default: false
21
+ # If false changes made in memory are wiped out when reloading from disk.
22
+ attr_bool :persist_memory, default: false
23
+ # If true all keys in configuration (included nested ones) are converted to symbols when loaded
24
+ attr_bool :keys_to_sym, default: true
25
+ # Records the last time the file on disk was refreshed
26
+ attr_time :last_refresh, serialize: false
27
+ # How long to sleep after checking if the file has been modified
28
+ attr_float_between 0.01, nil, :interval, default: 1
29
+ # Hook that is called every time reload is invoked (due to changes to file)
30
+ attr_of Proc, :on_reload, default: nil, allow_nil: true
31
+ # Hook that is called any time reload is called and makes actual changes
32
+ attr_of Proc, :on_change, default: nil, allow_nil: true
33
+
34
+ after :sync_up, :watch_file
35
+ before :configuration=, :detect_changes, send_args: true
36
+
37
+ delegate_to :configuration
38
+
39
+ # Determines what type of config file should be used for a given file/path
40
+ def self.detect_type(file)
41
+ Config.descendants.find { |desc| desc.match?(file) }&.type || type
42
+ end
43
+
44
+ # Should be overriden in subclasses. This is used to determine whether
45
+ # the file is the correct format for the class. For example, the yaml
46
+ # class should use this to determine if the config file is yaml (if it exists)
47
+ # or should be yaml (based on extension if it does not exist)
48
+ def self.match?(file)
49
+ false
50
+ end
51
+
52
+ # Set a single key value pair or merge in a hash. Keys can use hash path notation
53
+ def set(key = nil, value = nil, **opts)
54
+ if key
55
+ configuration.hpath_set(key => value)
56
+ else
57
+ opts.each do |k, v|
58
+ configuration.hpath_set(k => v)
59
+ end
60
+ end
61
+ save if sync_down
62
+ true
63
+ end
64
+
65
+ alias []= set
66
+
67
+ # Returns true if the sync thread is actively running and watching the file
68
+ def watching?
69
+ @watcher && @watcher.alive? ? true : false
70
+ end
71
+
72
+ # Get the first matching value for the key or path
73
+ def get(key)
74
+ get_all(key).first
75
+ end
76
+
77
+ alias [] get
78
+
79
+ # Get all matching instancesof the key or path
80
+ def get_all(key)
81
+ configuration.hpath(key)
82
+ end
83
+
84
+ # Delete a key or nested path from the configuration
85
+ def delete(key)
86
+ configuration.hpath_delete.tap do |result|
87
+ save if sync_down
88
+ end
89
+ end
90
+
91
+ # Delete the entire config file (if one exists)
92
+ def delete!
93
+ return true unless File.exist?(path)
94
+ FileUtils.rm(path)
95
+ end
96
+
97
+ # Clear our the configuration
98
+ def clear
99
+ self.configuration = {}
100
+ end
101
+
102
+ # Turn on sync up and down in one call for convenience
103
+ def sync(toggle)
104
+ self.sync_up = toggle
105
+ self.sync_down = toggle
106
+ end
107
+
108
+ alias sync= sync
109
+
110
+ # Should persist the configuration to disk. This is adapter dependent
111
+ def save
112
+ # Nothing in base class. This should be used to persist settings in
113
+ # subclasses that use files.
114
+ end
115
+
116
+ # Loads configuration from disk during synchronization
117
+ def load_config
118
+ # Nothing in base class. This should be used to load the configuration from
119
+ # disk if saved to a file.
120
+ {}
121
+ end
122
+
123
+ # Reload the configuration from disk and merge it in
124
+ def reload
125
+ if !persist_memory?
126
+ self.configuration = load_config
127
+ elsif prefer_memory
128
+ self.configuration = load_config.deep_merge(configuration)
129
+ else
130
+ self.configuration = configuration.deep_merge(load_config)
131
+ end
132
+ self.last_refresh = Time.now
133
+ on_reload.call(configuration) if on_reload
134
+ true
135
+ end
136
+
137
+ protected
138
+
139
+ def simple_postinit(*args)
140
+ named = BBLib.named_args(*args)
141
+ sync(true) if named[:sync]
142
+ reload
143
+ watch_file if sync_up?
144
+ end
145
+
146
+ # Spin up a thread to monitor the file for changes
147
+ def watch_file
148
+ if sync_up? && (@watcher.nil? || !@watcher.alive?)
149
+ BBLib.logger.debug("Spinning up a configuration watcher for #{path}")
150
+ @watcher = Thread.new do
151
+ loop do
152
+ break unless sync_up?
153
+ if path && File.exist?(path) && File.mtime(path) > last_refresh
154
+ reload
155
+ end
156
+ sleep(interval)
157
+ end
158
+ end
159
+ end
160
+ end
161
+
162
+ # Determine what has changed after performing a reload to trigger the on_change hook.
163
+ def detect_changes(hash)
164
+ return unless on_change && @configuration
165
+ changes = configuration.squish.to_a.diff(hash.squish.to_a).to_h.expand
166
+ return if changes.empty?
167
+ on_change.call(hash, changes)
168
+ end
169
+
170
+ # Processes configuration and converts it to a HashStruct internally
171
+ def process_config(hash)
172
+ return _compile(hash).to_hash_struct unless keys_to_sym?
173
+ _compile(hash).keys_to_sym.to_hash_struct
174
+ end
175
+
176
+ # Applies defaults config, specified/loaded config and then overlay config
177
+ def _compile(config)
178
+ default_configuration.deep_merge(config).deep_merge(overlay_configuration)
179
+ end
180
+
181
+ end
182
+ end
@@ -0,0 +1,2 @@
1
+ require_relative 'types/yaml'
2
+ require_relative 'types/json'
@@ -0,0 +1,34 @@
1
+ module Harmoni
2
+ class JSON < Config
3
+ include BBLib::Effortless
4
+
5
+ def self.match?(file)
6
+ if File.exist?(file)
7
+ begin
8
+ ::JSON.parse(File.read(file))
9
+ true
10
+ rescue => _e
11
+ false
12
+ end
13
+ else
14
+ file.file_name =~ /\.json$/i
15
+ end
16
+ end
17
+
18
+ def save
19
+ configuration.to_json.to_file(path, mode: 'w')
20
+ end
21
+
22
+ def load_config
23
+ if File.exist?(path)
24
+ ::JSON.parse(File.read(path))
25
+ else
26
+ {}
27
+ end
28
+ rescue => e
29
+ BBLib.logger.warn("Failed to load file as json @ #{path}: #{e}")
30
+ {}
31
+ end
32
+
33
+ end
34
+ end
@@ -0,0 +1,34 @@
1
+ module Harmoni
2
+ class YAML < Config
3
+ include BBLib::Effortless
4
+
5
+ def self.match?(file)
6
+ if File.exist?(file)
7
+ begin
8
+ ::YAML.load_file(file)
9
+ true
10
+ rescue => _e
11
+ false
12
+ end
13
+ else
14
+ file.file_name =~ /\.(yml|yaml)$/i
15
+ end
16
+ end
17
+
18
+ def save
19
+ configuration.to_h.to_yaml.to_file(path, mode: 'w')
20
+ end
21
+
22
+ def load_config
23
+ if File.exist?(path)
24
+ ::YAML.load_file(path)
25
+ else
26
+ {}
27
+ end
28
+ rescue => e
29
+ BBLib.logger.warn("Failed to load file as yaml @ #{path}: #{e}")
30
+ {}
31
+ end
32
+
33
+ end
34
+ end
@@ -0,0 +1,3 @@
1
+ module Harmoni
2
+ VERSION = '0.1.0'.freeze
3
+ end
metadata ADDED
@@ -0,0 +1,118 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: harmoni
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Brandon Black
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2018-09-21 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.16'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.16'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: bblib
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '2.0'
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '2.0'
69
+ description: Harmoni keeps configuration files in sync between memory and on disk
70
+ for hot loading and other tasks.
71
+ email:
72
+ - d2sm10@hotmail.com
73
+ executables: []
74
+ extensions: []
75
+ extra_rdoc_files: []
76
+ files:
77
+ - ".gitignore"
78
+ - ".rspec"
79
+ - ".travis.yml"
80
+ - CODE_OF_CONDUCT.md
81
+ - Gemfile
82
+ - LICENSE.txt
83
+ - README.md
84
+ - Rakefile
85
+ - bin/console
86
+ - bin/setup
87
+ - harmoni.gemspec
88
+ - lib/harmoni.rb
89
+ - lib/harmoni/config.rb
90
+ - lib/harmoni/types.rb
91
+ - lib/harmoni/types/json.rb
92
+ - lib/harmoni/types/yaml.rb
93
+ - lib/harmoni/version.rb
94
+ homepage: https://github.com/bblack16/harmoni
95
+ licenses:
96
+ - MIT
97
+ metadata: {}
98
+ post_install_message:
99
+ rdoc_options: []
100
+ require_paths:
101
+ - lib
102
+ required_ruby_version: !ruby/object:Gem::Requirement
103
+ requirements:
104
+ - - ">="
105
+ - !ruby/object:Gem::Version
106
+ version: '0'
107
+ required_rubygems_version: !ruby/object:Gem::Requirement
108
+ requirements:
109
+ - - ">="
110
+ - !ruby/object:Gem::Version
111
+ version: '0'
112
+ requirements: []
113
+ rubyforge_project:
114
+ rubygems_version: 2.7.4
115
+ signing_key:
116
+ specification_version: 4
117
+ summary: Keep configuration on disk is sync with memory.
118
+ test_files: []