attr-gather 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. checksums.yaml +7 -0
  2. data/.github/workflows/deploy.yml +15 -0
  3. data/.github/workflows/doc.yml +25 -0
  4. data/.github/workflows/ruby.yml +20 -0
  5. data/.gitignore +12 -0
  6. data/.ignore +1 -0
  7. data/.rspec +3 -0
  8. data/.rubocop.yml +38 -0
  9. data/.ruby-version +1 -0
  10. data/.travis.yml +7 -0
  11. data/.vim/coc-settings.json +12 -0
  12. data/.vim/install.sh +38 -0
  13. data/.yardopts +4 -0
  14. data/CODE_OF_CONDUCT.md +74 -0
  15. data/Gemfile +19 -0
  16. data/Gemfile.lock +147 -0
  17. data/LICENSE.txt +21 -0
  18. data/README.md +63 -0
  19. data/Rakefile +21 -0
  20. data/attr-gather.gemspec +38 -0
  21. data/bin/console +15 -0
  22. data/bin/setup +8 -0
  23. data/bin/solargraph +29 -0
  24. data/examples/post_enhancer.rb +119 -0
  25. data/examples/post_enhancer.svg +55 -0
  26. data/lib/attr-gather.rb +3 -0
  27. data/lib/attr/gather.rb +16 -0
  28. data/lib/attr/gather/aggregators.rb +31 -0
  29. data/lib/attr/gather/aggregators/base.rb +38 -0
  30. data/lib/attr/gather/aggregators/deep_merge.rb +50 -0
  31. data/lib/attr/gather/aggregators/shallow_merge.rb +40 -0
  32. data/lib/attr/gather/concerns/identifiable.rb +24 -0
  33. data/lib/attr/gather/concerns/registrable.rb +50 -0
  34. data/lib/attr/gather/filters.rb +34 -0
  35. data/lib/attr/gather/filters/base.rb +20 -0
  36. data/lib/attr/gather/filters/contract.rb +60 -0
  37. data/lib/attr/gather/filters/filtering.rb +27 -0
  38. data/lib/attr/gather/filters/noop.rb +14 -0
  39. data/lib/attr/gather/filters/result.rb +23 -0
  40. data/lib/attr/gather/version.rb +7 -0
  41. data/lib/attr/gather/workflow.rb +29 -0
  42. data/lib/attr/gather/workflow/async_task_executor.rb +17 -0
  43. data/lib/attr/gather/workflow/callable.rb +84 -0
  44. data/lib/attr/gather/workflow/dot_serializer.rb +46 -0
  45. data/lib/attr/gather/workflow/dsl.rb +184 -0
  46. data/lib/attr/gather/workflow/graphable.rb +50 -0
  47. data/lib/attr/gather/workflow/task.rb +29 -0
  48. data/lib/attr/gather/workflow/task_execution_result.rb +58 -0
  49. data/lib/attr/gather/workflow/task_executor.rb +31 -0
  50. data/lib/attr/gather/workflow/task_graph.rb +107 -0
  51. metadata +150 -0
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Ian Ker-Seymer
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,63 @@
1
+ # attr-gather
2
+
3
+ [![Actions Status](https://github.com/ianks/attr-gather/workflows/.github/workflows/ruby.yml/badge.svg)](https://github.com/ianks/attr-gather/actions)
4
+
5
+ A gem for creating simple workflows to enhance entities with extra attributes.
6
+ At a high level, `attr-gather` provides a process to sync attributes from many
7
+ sources (third party APIs, legacy databases, etc).
8
+
9
+ ## Links
10
+
11
+ - [API Documentation](https://www.rubydoc.info/gems/attr-gather)
12
+
13
+ ## Examples
14
+
15
+ | [![SVG of Workflow](./examples/post_enhancer.svg)](./examples/post_enhancer.rb) |
16
+ | :-----------------------------------------------------------------------------: |
17
+ | [Example of workflow that enhances a blog post](./examples/post_enhancer.rb) |
18
+
19
+ ## Installation
20
+
21
+ Add this line to your application's Gemfile:
22
+
23
+ ```ruby
24
+ gem 'attr-gather'
25
+ ```
26
+
27
+ And then execute:
28
+
29
+ $ bundle
30
+
31
+ Or install it yourself as:
32
+
33
+ $ gem install attr-gather
34
+
35
+ ## Development
36
+
37
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run
38
+ `rake spec` to run the tests. You can also run `bin/console` for an interactive
39
+ prompt that will allow you to experiment.
40
+
41
+ To install this gem onto your local machine, run `bundle exec rake install`. To
42
+ release a new version, update the version number in `version.rb`, and then run
43
+ `bundle exec rake release`, which will create a git tag for the version, push
44
+ git commits and tags, and push the `.gem` file to
45
+ [rubygems.org](https://rubygems.org).
46
+
47
+ ## Contributing
48
+
49
+ Bug reports and pull requests are welcome on GitHub at
50
+ https://github.com/ianks/attr-gather. This project is intended to be a safe,
51
+ welcoming space for collaboration, and contributors are expected to adhere to
52
+ the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
53
+
54
+ ## License
55
+
56
+ The gem is available as open source under the terms of the [MIT
57
+ License](https://opensource.org/licenses/MIT).
58
+
59
+ ## Code of Conduct
60
+
61
+ Everyone interacting in the Attr::Gather project’s codebases, issue trackers,
62
+ chat rooms and mailing lists is expected to follow the [code of
63
+ conduct](https://github.com/ianks/attr-gather/blob/master/CODE_OF_CONDUCT.md).
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+ require 'rubocop/rake_task'
6
+ require 'yard'
7
+
8
+ RSpec::Core::RakeTask.new(:spec)
9
+ RuboCop::RakeTask.new(:lint)
10
+ YARD::Rake::YardocTask.new(:doc)
11
+
12
+ task default: %i[spec lint]
13
+
14
+ namespace :examples do
15
+ desc 'Run all examples'
16
+ task :run do
17
+ Dir['examples/*.rb'].each do |filename|
18
+ system "ruby #{filename}"
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ lib = File.expand_path('lib', __dir__)
4
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5
+ require 'attr/gather/version'
6
+
7
+ Gem::Specification.new do |spec|
8
+ spec.name = 'attr-gather'
9
+ spec.version = Attr::Gather::VERSION
10
+ spec.authors = ['Ian Ker-Seymer']
11
+ spec.email = ['i.kerseymer@gmail.com']
12
+
13
+ spec.summary = 'Write a short summary, because RubyGems requires one.'
14
+ spec.description = 'Write a longer description or delete this line.'
15
+ spec.homepage = 'https://github.com/ianks/attr-gather'
16
+ spec.license = 'MIT'
17
+
18
+ # spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
19
+
20
+ spec.metadata['homepage_uri'] = spec.homepage
21
+ spec.metadata['source_code_uri'] = 'https://github.com/ianks/attr-gather'
22
+ # spec.metadata["changelog_uri"] = "Put your gem's CHANGELOG.md URL here."
23
+
24
+ # Specify which files should be added to the gem when it is released.
25
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
26
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
27
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
28
+ end
29
+ spec.bindir = 'exe'
30
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
31
+ spec.require_paths = ['lib']
32
+
33
+ spec.add_development_dependency 'bundler', '~> 2.0'
34
+ spec.add_development_dependency 'rake', '~> 10.0'
35
+ spec.add_development_dependency 'rspec', '~> 3.0'
36
+
37
+ spec.add_dependency 'dry-container', '~> 0.7'
38
+ end
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'attr/gather'
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require 'irb'
15
+ 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,29 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ #
5
+ # This file was generated by Bundler.
6
+ #
7
+ # The application 'solargraph' is installed as part of a gem, and
8
+ # this file is here to facilitate running it.
9
+ #
10
+
11
+ require 'pathname'
12
+ ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile',
13
+ Pathname.new(__FILE__).realpath)
14
+
15
+ bundle_binstub = File.expand_path('bundle', __dir__)
16
+
17
+ if File.file?(bundle_binstub)
18
+ if /This file was generated by Bundler/.match?(File.read(bundle_binstub, 300))
19
+ load(bundle_binstub)
20
+ else
21
+ abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
22
+ Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
23
+ end
24
+ end
25
+
26
+ require 'rubygems'
27
+ require 'bundler/setup'
28
+
29
+ load Gem.bin_path('solargraph', 'solargraph')
@@ -0,0 +1,119 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'dry-container'
4
+ require 'dry-validation'
5
+ require 'attr-gather'
6
+ require 'http'
7
+
8
+ # create the container
9
+ class MyContainer
10
+ extend Dry::Container::Mixin
11
+
12
+ register :fetch_post do |id:, **_attrs|
13
+ res = HTTP.get("https://jsonplaceholder.typicode.com/posts/#{id}")
14
+ post = JSON.parse(res.to_s, symbolize_names: true)
15
+
16
+ { title: post[:title], user_id: post[:userId], body: post[:body] }
17
+ end
18
+
19
+ register :fetch_user_from_buggy_api do |*|
20
+ { user: { email: 'invalidemail' } }
21
+ end
22
+
23
+ register :fetch_user do |user_id:, **_attrs|
24
+ res = HTTP.get("https://jsonplaceholder.typicode.com/users/#{user_id}")
25
+ user = JSON.parse(res.to_s, symbolize_names: true)
26
+
27
+ { user: { name: user[:name], email: user[:email] } }
28
+ end
29
+
30
+ register :email_info do |user:, **_attrs|
31
+ res = HTTP.timeout(3).get("https://api.trumail.io/v2/lookups/json?email=#{user[:email]}")
32
+ info = JSON.parse(res.to_s, symbolize_names: true)
33
+
34
+ { user: { email_info: { deliverable: info[:deliverable], free: info[:free] } } }
35
+ end
36
+
37
+ register :gravatar_image do |user:, **_attrs|
38
+ require 'digest/md5'
39
+ email_address = user[:email].downcase
40
+ hash = Digest::MD5.hexdigest(email_address)
41
+ image_url = "https://www.gravatar.com/avatar/#{hash}"
42
+
43
+ { user: { gravatar: image_url } }
44
+ end
45
+ end
46
+
47
+ # define a workflow
48
+ class EnhanceUserProfile
49
+ include Attr::Gather::Workflow
50
+
51
+ # contains all the task implementations
52
+ container MyContainer
53
+
54
+ # perform a deep merge of the task outputs for the result
55
+ aggregator :deep_merge
56
+
57
+ # filter out invalid values using a Dry::Validation::Contract
58
+ filter_with_contract do
59
+ params do
60
+ required(:user_id).filled(:integer)
61
+
62
+ optional(:user).hash do
63
+ optional(:name).filled(:string)
64
+ optional(:email).filled(:string)
65
+ optional(:gravatar).filled(:string)
66
+ optional(:email_info).hash do
67
+ optional(:deliverable).filled(:bool?)
68
+ optional(:free).filled(:bool?)
69
+ end
70
+ end
71
+ end
72
+ end
73
+
74
+ task :fetch_post do |t|
75
+ t.depends_on = []
76
+ end
77
+
78
+ task :fetch_user_from_buggy_api do |t|
79
+ t.depends_on = [:fetch_post]
80
+ end
81
+
82
+ task :fetch_user do |t|
83
+ t.depends_on = [:fetch_post]
84
+ end
85
+
86
+ # will run in parallel
87
+ task :email_info do |t|
88
+ t.depends_on = [:fetch_user]
89
+ end
90
+
91
+ # will run in parallel
92
+ task :gravatar_image do |t|
93
+ t.depends_on = [:fetch_user]
94
+ end
95
+ end
96
+
97
+ # run the workflow
98
+ enhancer = EnhanceUserProfile.new
99
+
100
+ puts
101
+ puts 'Runing workflow...'
102
+ puts
103
+ puts 'Result'
104
+ puts '======'
105
+ pp enhancer.call(id: 12).value!
106
+
107
+ # fun fact: you can preview as svg!
108
+ puts
109
+ print 'Would you like to preview the workflow as SVG? (y/n): '
110
+ exit 0 unless gets.strip == 'y'
111
+
112
+ begin
113
+ enhancer.to_dot(preview: true)
114
+ rescue SignalException
115
+ puts 'Done!'
116
+ rescue StandardError
117
+ abort 'Could not render SVG, please make sure you have ' \
118
+ 'graphviz installed (brew install graphviz), then retry'
119
+ end
@@ -0,0 +1,55 @@
1
+ <?xml version="1.0" encoding="UTF-8" standalone="no"?>
2
+ <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
3
+ "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
4
+ <!-- Generated by graphviz version 2.43.20190912.0211 (20190912.0211)
5
+ -->
6
+ <!-- Title: TaskGraph Pages: 1 -->
7
+ <svg width="308pt" height="188pt"
8
+ viewBox="0.00 0.00 308.04 188.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
9
+ <g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 184)">
10
+ <title>TaskGraph</title>
11
+ <polygon fill="white" stroke="transparent" points="-4,4 -4,-184 304.04,-184 304.04,4 -4,4"/>
12
+ <!-- fetch_post -->
13
+ <g id="node1" class="node">
14
+ <title>fetch_post</title>
15
+ <ellipse fill="none" stroke="black" cx="136.84" cy="-162" rx="58.49" ry="18"/>
16
+ <text text-anchor="middle" x="136.84" y="-158.3" font-family="Times,serif" font-size="14.00">fetch_post</text>
17
+ </g>
18
+ <!-- fetch_user -->
19
+ <g id="node2" class="node">
20
+ <title>fetch_user</title>
21
+ <ellipse fill="none" stroke="black" cx="136.84" cy="-90" rx="59.29" ry="18"/>
22
+ <text text-anchor="middle" x="136.84" y="-86.3" font-family="Times,serif" font-size="14.00">fetch_user</text>
23
+ </g>
24
+ <!-- fetch_post&#45;&gt;fetch_user -->
25
+ <g id="edge1" class="edge">
26
+ <title>fetch_post&#45;&gt;fetch_user</title>
27
+ <path fill="none" stroke="black" d="M136.84,-143.7C136.84,-135.98 136.84,-126.71 136.84,-118.11"/>
28
+ <polygon fill="black" stroke="black" points="140.34,-118.1 136.84,-108.1 133.34,-118.1 140.34,-118.1"/>
29
+ </g>
30
+ <!-- email_info -->
31
+ <g id="node3" class="node">
32
+ <title>email_info</title>
33
+ <ellipse fill="none" stroke="black" cx="57.84" cy="-18" rx="57.69" ry="18"/>
34
+ <text text-anchor="middle" x="57.84" y="-14.3" font-family="Times,serif" font-size="14.00">email_info</text>
35
+ </g>
36
+ <!-- fetch_user&#45;&gt;email_info -->
37
+ <g id="edge2" class="edge">
38
+ <title>fetch_user&#45;&gt;email_info</title>
39
+ <path fill="none" stroke="black" d="M118.52,-72.76C108.15,-63.58 95.02,-51.94 83.62,-41.84"/>
40
+ <polygon fill="black" stroke="black" points="85.87,-39.16 76.07,-35.15 81.23,-44.4 85.87,-39.16"/>
41
+ </g>
42
+ <!-- gravatar_image -->
43
+ <g id="node4" class="node">
44
+ <title>gravatar_image</title>
45
+ <ellipse fill="none" stroke="black" cx="216.84" cy="-18" rx="83.39" ry="18"/>
46
+ <text text-anchor="middle" x="216.84" y="-14.3" font-family="Times,serif" font-size="14.00">gravatar_image</text>
47
+ </g>
48
+ <!-- fetch_user&#45;&gt;gravatar_image -->
49
+ <g id="edge3" class="edge">
50
+ <title>fetch_user&#45;&gt;gravatar_image</title>
51
+ <path fill="none" stroke="black" d="M155.4,-72.76C165.75,-63.71 178.82,-52.27 190.24,-42.28"/>
52
+ <polygon fill="black" stroke="black" points="192.61,-44.85 197.84,-35.63 188,-39.58 192.61,-44.85"/>
53
+ </g>
54
+ </g>
55
+ </svg>
@@ -0,0 +1,3 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'attr/gather'
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'attr/gather/version'
4
+
5
+ module Attr
6
+ module Gather
7
+ class Error < StandardError; end
8
+ # Your code goes here...
9
+
10
+ EMPTY_HASH = {}.freeze
11
+ end
12
+ end
13
+
14
+ require 'attr/gather/workflow'
15
+ require 'attr/gather/aggregators'
16
+ require 'attr/gather/filters'
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'attr/gather/concerns/registrable'
4
+
5
+ module Attr
6
+ module Gather
7
+ # Namespace for aggregators
8
+ module Aggregators
9
+ extend Registrable
10
+
11
+ # The default aggregator if none is specified
12
+ #
13
+ # @return [Attr::Gather::Aggregators::DeepMerge]
14
+ def self.default
15
+ @default = resolve(:deep_merge)
16
+ end
17
+
18
+ register(:deep_merge) do |*args|
19
+ require 'attr/gather/aggregators/deep_merge'
20
+
21
+ DeepMerge.new(*args)
22
+ end
23
+
24
+ register(:shallow_merge) do |*args|
25
+ require 'attr/gather/aggregators/shallow_merge'
26
+
27
+ ShallowMerge.new(*args)
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Attr
4
+ module Gather
5
+ module Aggregators
6
+ # @abstract Subclass and override {#call} to implement
7
+ # a custom Aggregator class.
8
+ #
9
+ # @!attribute [r] filter
10
+ # @return [Attr::Gather::Filters::Base] filter for the output data
11
+ class Base
12
+ attr_accessor :filter
13
+
14
+ def initialize(**opts)
15
+ @filter = opts.delete(:filter)
16
+ end
17
+
18
+ def call(_original_input, _results_array)
19
+ raise NotImplementedError
20
+ end
21
+
22
+ private
23
+
24
+ def wrap_result(result)
25
+ Concurrent::Promise.fulfill(result)
26
+ end
27
+
28
+ def unwrap_result(res)
29
+ unvalidated = res.result.value!
30
+
31
+ return unvalidated if filter.nil?
32
+
33
+ filter.call(unvalidated).value
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end