servicer 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
+ SHA1:
3
+ metadata.gz: 99a9950f7c88104948e676570b5eb3092e144fda
4
+ data.tar.gz: 073f9d1730486057c1a1db2883a6cac5e4badfab
5
+ SHA512:
6
+ metadata.gz: 9be3adc87ffdd8224b376ee1edfe87ac6440c04e2d2ab9f3f2d85baca03c3e1b250b04d37dc760fc1ee4de2472c78551cf23f96e399e5a6117015b08ac6ee2c5
7
+ data.tar.gz: 6fd89c2f3c1127acf4464cd9a1073c9d1bd3288d1dca554f45eab63fdff41d634757ca7f70fee5d34570e6ad042cf8fe328e6e290eae34fb1739c6b78b6a4d54
data/.codeclimate.yml ADDED
@@ -0,0 +1,17 @@
1
+ ---
2
+ engines:
3
+ duplication:
4
+ enabled: true
5
+ config:
6
+ languages:
7
+ - ruby
8
+ fixme:
9
+ enabled: true
10
+ rubocop:
11
+ enabled: true
12
+ channel: rubocop-0-52
13
+ ratings:
14
+ paths:
15
+ - "**.rb"
16
+ exclude_paths:
17
+ - spec/
data/.gitignore ADDED
@@ -0,0 +1,2 @@
1
+ Gemfile.lock
2
+ pkg/*.gem
data/.rubocop.yml ADDED
@@ -0,0 +1,8 @@
1
+ require: rubocop-rspec
2
+
3
+ AllCops:
4
+ DisplayCopNames: true
5
+ TargetRubyVersion: 2.3
6
+
7
+ Metrics/LineLength:
8
+ Max: 120
data/.travis.yml ADDED
@@ -0,0 +1,18 @@
1
+ dist: trusty
2
+ language: ruby
3
+ script: "bundle exec rake"
4
+ rvm:
5
+ - 2.3
6
+ - 2.4
7
+ - 2.5
8
+ - ruby-head
9
+ - jruby-9.1.9.0 # https://github.com/travis-ci/travis-ci/issues/8446
10
+ - jruby-head
11
+ - rbx-3
12
+
13
+ matrix:
14
+ allow_failures:
15
+ - rvm: 2.5
16
+ - rvm: ruby-head
17
+ - rvm: jruby-head
18
+ - rvm: rbx-3
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0
4
+
5
+ - initial release
data/Gemfile ADDED
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'http://rubygems.org'
4
+
5
+ group :development do
6
+ gem 'rake'
7
+ gem 'rspec', '~> 3.7'
8
+
9
+ # Use same version as Code Climate for consistency with CI
10
+ # https://github.com/codeclimate/codeclimate-rubocop/blob/master/Gemfile.lock
11
+ gem 'rubocop', '0.52.1', require: false
12
+ gem 'rubocop-rspec', '1.21.0', require: false
13
+ end
14
+
15
+ gemspec
data/README.md ADDED
@@ -0,0 +1,166 @@
1
+ # Servicer
2
+
3
+ Simple Service Object builder.
4
+
5
+ ## Installation
6
+
7
+ ```
8
+ gem install servicer
9
+ ```
10
+
11
+ ## Basic usage
12
+
13
+ Servicer provides base class for building services, and set of additional layers for changing behaviour.
14
+
15
+ Simplest use case is building Command Object for API:
16
+
17
+ ```
18
+ class CreateUser < ::Servicer::Base
19
+ def call(current_user, params)
20
+ User.create(params)
21
+ end
22
+ end
23
+
24
+ CreateUser.call(current_user, params) #=> new User
25
+ ```
26
+
27
+ In that form no layers are applied, so input will not be changed in any way. Servicer is proxying class `call` method,
28
+ building new instance and calling `call` with the same params as provided (unless modified by layers).
29
+
30
+ ## Layers
31
+
32
+ Layers are modifying how given service object behave. They can validate input, change params, and raise errors.
33
+ Simplest call would look like this:
34
+
35
+ ```
36
+ class CreateUser < ::Servicer::Base
37
+ layer :require_user
38
+
39
+ def call(current_user, params)
40
+ User.create(params)
41
+ end
42
+ end
43
+ ```
44
+
45
+ Multiple layers can be applied and they will be executed in order of mentioning them. Some of them will require
46
+ additional parameters, documentation can be found below.
47
+
48
+ ### RequireUser
49
+
50
+ This layer is raising `Servicer::AuthorizationError` is current user is not provided. This layer is not accepting
51
+ any options.
52
+
53
+ ```
54
+ class CreateUser < ::Servicer::Base
55
+ layer :require_user
56
+
57
+ def call(current_user, params)
58
+ User.create(params)
59
+ end
60
+ end
61
+
62
+ CreateUser.call(nil, params) #=> raises Servicer::AuthorizationError
63
+ ```
64
+
65
+ ### SetDefaultParams
66
+
67
+ This layer is merging received params with default values provided using deep merge (nested hash values will be merged).
68
+ Values from provided params always take precedence over default values.
69
+
70
+ ```
71
+ class CreateUser < ::Servicer::Base
72
+ layer :set_default_values, {
73
+ role: 'user'
74
+ }
75
+
76
+ def call(current_user, params)
77
+ User.create(params)
78
+ end
79
+ end
80
+
81
+ CreateUser.call(nil, {}) #=> user.role == 'user'
82
+ CreateUser.call(nil, { role: 'admin' }) #=> user.role == 'admin'
83
+ ```
84
+
85
+ ### ValidateParams
86
+
87
+ This layer is validating params provided, raising `Servicer::ParamsError` if validation fails, and filtering any param
88
+ that was not validated. It's using [dry-validation](http://dry-rb.org/gems/dry-validation/) under the hood, and you need
89
+ to include it in your Gemfile.
90
+
91
+ Please bear in mind that it's used for validating input, and not for checking user permissions.
92
+
93
+ ```
94
+ class CreateUser < ::Servicer::Base
95
+ layer :validate_params do
96
+ required(:role).filled(:str?)
97
+ optional(:age).filled(:int?, gt?: 17)
98
+ end
99
+
100
+ def call(current_user, params)
101
+ User.create(params)
102
+ end
103
+ end
104
+
105
+ CreateUser.call(nil, {}) #=> raises Servicer::ParamsError
106
+ CreateUser.call(nil, { role: 1 }) #=> raises Servicer::ParamsError
107
+ CreateUser.call(nil, { role: 'admin' }) #=> user.role == 'admin'
108
+ CreateUser.call(nil, { role: 'admin', age: 17 }) #=> raises Servicer::ParamsError
109
+ CreateUser.call(nil, { role: 'admin', age: 18 }) #=> user.role == 'admin', user.age == 18
110
+ ```
111
+
112
+ ## Combining layers
113
+
114
+ Multiple layers can be used together in order to provide final service:
115
+
116
+ ```
117
+ class CreateUser < ::Servicer::Base
118
+ layer :require_user
119
+
120
+ layer :validate_params do
121
+ optional(:role).filled(:str?)
122
+ required(:age).filled(:int?, gt?: 17)
123
+ end
124
+
125
+ layer :set_default_values, {
126
+ role: 'user'
127
+ }
128
+
129
+ def call(current_user, params)
130
+ User.create(params)
131
+ end
132
+ end
133
+ ```
134
+
135
+ ```
136
+ class ListUsers < ::Servicer::Base
137
+ layer :validate_params do
138
+ optional(:role).filled(:str?)
139
+ optional(:limit).filled(:int?, gt?: 0, lt?: 1000)
140
+ optional(:offset).filled(:int?)
141
+ end
142
+
143
+ layer :set_default_values, {
144
+ limit: 10,
145
+ offset: 0
146
+ }
147
+
148
+ def call(current_user, params)
149
+ limit = params.delete(:limit)
150
+ offset = params.delete(:offset)
151
+ User.where(params).limit(limit).offset(offset)
152
+ end
153
+ end
154
+ ```
155
+
156
+ ## License
157
+
158
+ (The MIT License)
159
+
160
+ Copyright © 2018 Bernard Potocki
161
+
162
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ‘Software’), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
163
+
164
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
165
+
166
+ THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Rakefile ADDED
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler'
4
+ require 'rspec/core/rake_task'
5
+ require 'rubocop/rake_task'
6
+
7
+ Bundler::GemHelper.install_tasks
8
+
9
+ RSpec::Core::RakeTask.new do |t|
10
+ t.rspec_opts = ['-c', '-f progress']
11
+ t.pattern = 'spec/**/*_spec.rb'
12
+ end
13
+
14
+ RuboCop::RakeTask.new
15
+
16
+ task default: %i[spec rubocop]
data/lib/servicer.rb ADDED
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Simple Service Object builder.
4
+ # See ::Servicer::Base for how to use it.
5
+ module Servicer
6
+ class Error < StandardError; end
7
+ class AuthorizationError < Error; end
8
+ class ParamsError < Error; end
9
+
10
+ require_relative 'servicer/base'
11
+ require_relative 'servicer/layers'
12
+ require_relative 'servicer/version'
13
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Servicer
4
+ # This is base class for subclassing your services.
5
+ # Example:
6
+ # class MyClass < ::Servicer::Base
7
+ # layer :require_user
8
+ #
9
+ # def call(current_user, params)
10
+ # true
11
+ # end
12
+ # end
13
+ #
14
+ # MyClass.call(current_user, params)
15
+ class Base
16
+ class AuthorizationError < ::Servicer::AuthorizationError; end
17
+ class ParamsError < ::Servicer::ParamsError; end
18
+
19
+ attr_reader :current_user, :params
20
+
21
+ class << self
22
+ def layers
23
+ @layers ||= []
24
+ end
25
+
26
+ # Apply layer. Layer class can be any class based on ::Servicer::Layers::Base or symbolized name of layer.
27
+ def layer(layer_class, options = {}, &block)
28
+ layer_class = ::Servicer::Layers.const_get(layer_class.to_s.camelcase) if layer_class.is_a?(Symbol)
29
+ layers << layer_class.new(options, &block)
30
+ end
31
+
32
+ # Main call. Will create instance and run `call` on it. In most cases instance method should be overwritten.
33
+ def call(current_user, params)
34
+ current_user, params = layers.inject([current_user, params]) { |arr, layer| layer.call(arr[0], arr[1]) }
35
+ new(current_user, params).call
36
+ end
37
+ end
38
+
39
+ # Main call. Overwrite this.
40
+ def call; end
41
+
42
+ private
43
+
44
+ def initialize(current_user, params)
45
+ @current_user = current_user
46
+ @params = params
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Servicer
4
+ # Module for Layers base.
5
+ module Layers
6
+ autoload :Base, File.join(__dir__, 'layers', 'base')
7
+ autoload :RequireUser, File.join(__dir__, 'layers', 'require_user')
8
+ autoload :SetDefaultParams, File.join(__dir__, 'layers', 'set_default_params')
9
+ autoload :ValidateParams, File.join(__dir__, 'layers', 'validate_params')
10
+ end
11
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Servicer
4
+ module Layers
5
+ # Base class for creating Layers.
6
+ class Base
7
+ def call(current_user, params)
8
+ [current_user, params]
9
+ end
10
+
11
+ private
12
+
13
+ def initialize(options, &block)
14
+ @options = options
15
+ @block = block
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Servicer
4
+ module Layers
5
+ # Layer verifying if current user exists, and raises ::Servicer::AAuthorizationError otherwise.
6
+ # Example:
7
+ # layer :require_user
8
+ class RequireUser < ::Servicer::Layers::Base
9
+ def call(current_user, params)
10
+ raise AuthorizationError if current_user.nil?
11
+ [current_user, params]
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Servicer
4
+ module Layers
5
+ # Layer setting default params using deep_merge.
6
+ # Example:
7
+ # layer :set_default_params, {
8
+ # limit: 10
9
+ # offset: 0
10
+ # }
11
+ class SetDefaultParams < ::Servicer::Layers::Base
12
+ def call(current_user, params)
13
+ # TODO: Remove hidden dependency on ActiveSupport
14
+ [current_user, @options.deep_merge(params)]
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Servicer
4
+ module Layers
5
+ # Layer validating provided params and raising ::Servicer::ParamsError if validation was unsuccessful.
6
+ # It uses `dry-validation` gem schema to build validation options. Please note that you need to add
7
+ # `dry-validations` to your Gemfile, as Servicer is not requiring it automatically.
8
+ # Please consult http://dry-rb.org/gems/dry-validation/ for details of how to build it.
9
+ # Example:
10
+ # layer :validate_params do
11
+ # optional(:limit).maybe(:int?, gt?: 0, lt?: 1_000)
12
+ # optional(:offset).maybe(:int?)
13
+ # end
14
+ class ValidateParams < ::Servicer::Layers::Base
15
+ def initialize(options, &block)
16
+ super
17
+ @schema = ::Dry::Validation.Schema do
18
+ configure do
19
+ config.input_processor = :sanitizer
20
+ end
21
+
22
+ instance_eval(&block)
23
+ end
24
+ end
25
+
26
+ def call(current_user, params)
27
+ validation = @schema.call(params)
28
+ raise ParamsError, validation.errors unless validation.success?
29
+
30
+ [current_user, validation.output]
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Servicer
4
+ VERSION = '1.0.0'
5
+ end
data/servicer.gemspec ADDED
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ $LOAD_PATH.push File.expand_path('../lib', __FILE__)
4
+ require 'servicer/version'
5
+
6
+ Gem::Specification.new do |s|
7
+ s.name = 'servicer'
8
+ s.version = Servicer::VERSION
9
+ s.platform = Gem::Platform::RUBY
10
+ s.authors = ['Bernard Potocki']
11
+ s.email = ['bernard.potocki@imanel.org']
12
+ s.homepage = 'http://github.com/imanel/servicer'
13
+ s.summary = 'Simple Service Object builder.'
14
+ s.description = 'Simple Service Object builder.'
15
+ s.license = 'MIT'
16
+
17
+ s.files = `git ls-files`.split("\n")
18
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
19
+ s.executables = `git ls-files -- bin/*`.split("\n").map { |f| File.basename(f) }
20
+ s.require_paths = ['lib']
21
+
22
+ s.required_ruby_version = '>= 2.3'
23
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'servicer'
4
+ Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
5
+
6
+ RSpec.configure do |config|
7
+ config.expect_with :rspec do |expectations|
8
+ expectations.include_chain_clauses_in_custom_matcher_descriptions = true # Default in RSpec 4
9
+ end
10
+
11
+ config.mock_with :rspec do |mocks|
12
+ mocks.verify_partial_doubles = true # Default in RSpec 4
13
+ end
14
+
15
+ config.shared_context_metadata_behavior = :apply_to_host_groups # Default in RSpec 4
16
+ end
metadata ADDED
@@ -0,0 +1,63 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: servicer
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Bernard Potocki
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2018-01-27 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Simple Service Object builder.
14
+ email:
15
+ - bernard.potocki@imanel.org
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - ".codeclimate.yml"
21
+ - ".gitignore"
22
+ - ".rubocop.yml"
23
+ - ".travis.yml"
24
+ - CHANGELOG.md
25
+ - Gemfile
26
+ - README.md
27
+ - Rakefile
28
+ - lib/servicer.rb
29
+ - lib/servicer/base.rb
30
+ - lib/servicer/layers.rb
31
+ - lib/servicer/layers/base.rb
32
+ - lib/servicer/layers/require_user.rb
33
+ - lib/servicer/layers/set_default_params.rb
34
+ - lib/servicer/layers/validate_params.rb
35
+ - lib/servicer/version.rb
36
+ - servicer.gemspec
37
+ - spec/spec_helper.rb
38
+ homepage: http://github.com/imanel/servicer
39
+ licenses:
40
+ - MIT
41
+ metadata: {}
42
+ post_install_message:
43
+ rdoc_options: []
44
+ require_paths:
45
+ - lib
46
+ required_ruby_version: !ruby/object:Gem::Requirement
47
+ requirements:
48
+ - - ">="
49
+ - !ruby/object:Gem::Version
50
+ version: '2.3'
51
+ required_rubygems_version: !ruby/object:Gem::Requirement
52
+ requirements:
53
+ - - ">="
54
+ - !ruby/object:Gem::Version
55
+ version: '0'
56
+ requirements: []
57
+ rubyforge_project:
58
+ rubygems_version: 2.6.14
59
+ signing_key:
60
+ specification_version: 4
61
+ summary: Simple Service Object builder.
62
+ test_files:
63
+ - spec/spec_helper.rb