dry-mutations 0.8.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: cb0b6c10516160d2950e96ba5983f671b6b944fc
4
+ data.tar.gz: 174d99350fa4138262c39e47bd9280ca7f43a766
5
+ SHA512:
6
+ metadata.gz: 0fb7e0849cfe37acb7134a60a0c8669e1a5e3fa730d5324f50c292d3d4c43c4c1056d4c48cece10a3477a9b8b2c688fe87b5c5516b91468c32dc9a0fba14560b
7
+ data.tar.gz: dd2e77496437e448325e90283c03f48800d20ad6162c34df17c4f6ec2cbe2728d559d6238551ee9784b4fdc4777ab979a198b58a5289848e497c2837fb1a132f
@@ -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
+ ratings:
13
+ paths:
14
+ - "**.rb"
15
+ exclude_paths:
16
+ - features/
17
+ - spec/
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
@@ -0,0 +1,92 @@
1
+ inherit_from: .rubocop_todo.yml
2
+
3
+ # METRICS
4
+ Metrics/ClassLength:
5
+ Max: 200
6
+
7
+ Metrics/CyclomaticComplexity:
8
+ Max: 21
9
+
10
+ Metrics/LineLength:
11
+ Max: 180
12
+
13
+ Metrics/MethodLength:
14
+ Max: 42
15
+
16
+ Metrics/PerceivedComplexity:
17
+ Max: 21
18
+
19
+ Metrics/AbcSize:
20
+ Max: 42
21
+
22
+ ################################################################################
23
+
24
+ Style/SignalException:
25
+ EnforcedStyle: semantic
26
+
27
+ Style/MethodName:
28
+ Exclude:
29
+ - 'lib/dry/mutations/utils.rb'
30
+
31
+ ################################################################################
32
+
33
+ Style/Alias:
34
+ Exclude:
35
+ - 'lib/**/*'
36
+ - 'spec/**/*'
37
+
38
+ Style/LambdaCall:
39
+ Exclude:
40
+ - 'lib/**/*'
41
+
42
+ Style/ParallelAssignment:
43
+ Exclude:
44
+ - 'lib/**/*'
45
+
46
+ Style/FormatString:
47
+ Exclude:
48
+ - 'lib/**/*'
49
+
50
+ Style/MethodDefParentheses:
51
+ Exclude:
52
+ - 'lib/**/*'
53
+ - 'spec/**/*'
54
+
55
+ Style/AsciiIdentifiers:
56
+ Exclude:
57
+ - 'lib/**/*'
58
+ - 'spec/**/*'
59
+
60
+ Style/AsciiComments:
61
+ Exclude:
62
+ - 'lib/**/*'
63
+ - 'spec/**/*'
64
+
65
+ Style/RescueModifier:
66
+ Exclude:
67
+ - 'lib/**/*'
68
+
69
+ Style/EmptyCaseCondition:
70
+ Exclude:
71
+ - 'lib/**/*'
72
+ - 'spec/**/*'
73
+
74
+ Style/RaiseArgs:
75
+ Exclude:
76
+ - 'lib/**/*'
77
+ - 'spec/**/*'
78
+
79
+ Style/SpecialGlobalVars:
80
+ Exclude:
81
+ - 'lib/**/*'
82
+ - 'spec/**/*'
83
+
84
+ Style/MultilineBlockChain:
85
+ Exclude:
86
+ - 'lib/**/*'
87
+ - 'spec/**/*'
88
+
89
+ Style/CaseEquality:
90
+ Exclude:
91
+ - 'lib/**/*'
92
+ - 'spec/**/*'
@@ -0,0 +1,14 @@
1
+ # This configuration was generated by
2
+ # `rubocop --auto-gen-config`
3
+ # on 2016-07-08 09:24:30 +0200 using RuboCop version 0.40.0.
4
+ # The point is for the user to remove these configuration records
5
+ # one by one as the offenses are removed from the code base.
6
+ # Note that changes in the inspected code, or installation of new
7
+ # versions of RuboCop, may require this file to be generated again.
8
+
9
+ # Offense count: 1
10
+ Style/Documentation:
11
+ Exclude:
12
+ - 'spec/**/*'
13
+ - 'test/**/*'
14
+ - 'lib/dry/mutations.rb'
@@ -0,0 +1,9 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.1.1
4
+ - 2.1.8
5
+ - 2.2.0
6
+ before_install: gem install bundler -v 1.10.6
7
+ addons:
8
+ code_climate:
9
+ repo_token: ebdc539bad445dc9ca96c4b01e2aa414624456bc47b3bf8b77c726c49b3158ba
@@ -0,0 +1,13 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
4
+
5
+ We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion.
6
+
7
+ Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
8
+
9
+ Project maintainers 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. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
10
+
11
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
12
+
13
+ This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
data/Gemfile ADDED
@@ -0,0 +1,8 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in dry-mutations.gemspec
4
+ gemspec
5
+
6
+ gem 'dry-validation', github: 'dry-rb/dry-validation'
7
+
8
+ gem 'codeclimate-test-reporter', group: :test, require: nil
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 Aleksei Matiushkin
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,118 @@
1
+ # Dry::Mutations
2
+
3
+ [![Build Status](https://travis-ci.org/am-kantox/dry-mutations.svg?branch=master)](https://travis-ci.org/am-kantox/dry-mutations)
4
+ [![Code Climate](https://codeclimate.com/github/am-kantox/dry-mutations/badges/gpa.svg)](https://codeclimate.com/github/am-kantox/dry-mutations)
5
+
6
+ ---
7
+
8
+ A link between [`dry-validation`](http://dry-rb.org/gems/dry-validation) and
9
+ [`mutations`](http://github.com/cypriss/mutations) gems. This gem enables
10
+ support for `dry-validation` schemas to be used within legacy `mutations`-based
11
+ syntax.
12
+
13
+ ## Installation
14
+
15
+ Add this line to your application's Gemfile:
16
+
17
+ ```ruby
18
+ gem 'dry-mutations'
19
+ ```
20
+
21
+ And then execute:
22
+
23
+ $ bundle
24
+
25
+ Or install it yourself as:
26
+
27
+ $ gem install dry-mutations
28
+
29
+ ## Usage
30
+
31
+ ### Enable extensions for the specific mutation’s command
32
+
33
+ Prepend a `::Dry::Mutations::Command` module to your `Mutation::Command` instance:
34
+
35
+ ```ruby
36
+ class MyMutation < Mutations::Command
37
+ prepend ::Dry::Mutations::Command
38
+
39
+ required do
40
+ model :company, class: 'Profile'
41
+ model :user
42
+ hash :maturity_set do
43
+ string :maturity_choice, in: %w(spot forward_days fixed_date)
44
+ optional do
45
+ hash :maturity_days_set do
46
+ integer :days # For spot or forward_days options
47
+ end
48
+ hash :maturity_date_set do
49
+ date :date # When passing a fixed date
50
+ end
51
+ end
52
+ end
53
+ ...
54
+ ```
55
+
56
+ ### `dry-validation` syntax
57
+
58
+ It is possible to mix standard mutations’ syntax with `dry-rb` schemas:
59
+
60
+ ```ruby
61
+ class MyMutation < Mutations::Command
62
+ prepend ::Dry::Mutations::Command
63
+
64
+ required do
65
+ model :company, class: 'Profile'
66
+ end
67
+
68
+ schema do
69
+ required(:maturity_choice).filled(:str?, included_in?: %w(spot forward_days fixed_date))
70
+ end
71
+ ```
72
+
73
+ ### Reusing schema
74
+
75
+ Basically, everything [written here](http://dry-rb.org/gems/dry-validation/reusing-schemas/)
76
+ is applicable. Syntax to include the nested schema is as simple as:
77
+
78
+ ```ruby
79
+ UserSchema = Dry::Validation.Schema do
80
+ required(:email).filled(:str?)
81
+ required(:name).filled(:str?)
82
+ required(:address).schema(AddressSchema)
83
+ end
84
+ ```
85
+
86
+ or, in legacy `mutations` syntax (**NB! This is not yet implemented!**):
87
+
88
+ ```ruby
89
+ required do
90
+ string :email
91
+ string :name
92
+ schema :address, AddressSchema
93
+ end
94
+ ```
95
+
96
+ ### Turn On Globally (use with caution!)
97
+
98
+ ENV['GLOBAL_DRY_MUTATIONS'] = 'true' && rake
99
+
100
+ That way _all_ mutations all over the system will be patched/injected with
101
+ new functionality. This is untested in all possible environments.
102
+
103
+ Bug reports are very welcome!
104
+
105
+ ## Development
106
+
107
+ 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.
108
+
109
+ 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).
110
+
111
+ ## Contributing
112
+
113
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/dry-mutations. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct.
114
+
115
+
116
+ ## License
117
+
118
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
@@ -0,0 +1,25 @@
1
+ # encoding: UTF-8
2
+ require 'rubygems'
3
+
4
+ require 'bundler'
5
+ require 'bundler/setup'
6
+ require 'bundler/gem_tasks'
7
+
8
+ require 'rspec/core/rake_task'
9
+
10
+ begin
11
+ Bundler.setup(:default, :development, :test)
12
+ rescue Bundler::BundlerError => e
13
+ $stderr.puts e.message
14
+ $stderr.puts 'Run `bundle install` to install missing gems'
15
+ exit e.status_code
16
+ end
17
+
18
+ desc 'Tests'
19
+ RSpec::Core::RakeTask.new(:spec) do |spec|
20
+ # ENV['GLOBAL_DRY_MUTATIONS'] = 'true'
21
+ spec.rspec_opts = '-Ispec'
22
+ # spec.rcov = true
23
+ end
24
+
25
+ task default: [:spec]
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'bundler/setup'
4
+ require 'dry/mutations'
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
@@ -0,0 +1,7 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+
5
+ bundle install
6
+
7
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,4 @@
1
+ en:
2
+ errors:
3
+ duck?: 'must respond to %{expected}'
4
+ model?: 'must be a model (instance of %{expected})'
@@ -0,0 +1,39 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'dry/mutations/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'dry-mutations'
8
+ spec.version = Dry::Mutations::VERSION
9
+ spec.authors = ['Aleksei Matiushkin']
10
+ spec.email = ['aleksei.matiushkin@kantox.com']
11
+
12
+ spec.summary = 'Mutations gem interface implemented with `dry-rb`’s validation schemas.'
13
+ spec.description = <<-DESC
14
+ Mutations gem interface implemented with `dry-rb`’s validation schemas.
15
+ DESC
16
+ spec.homepage = 'http://github.com/am-kantox/dry-mutations'
17
+ spec.license = 'MIT'
18
+
19
+ # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
20
+ # delete this section to allow pushing this gem to any host.
21
+ fail 'RubyGems 2.0 or newer is required to protect against public gem pushes.' unless spec.respond_to?(:metadata)
22
+ # spec.metadata['allowed_push_host'] = 'https://gemfury.com'
23
+
24
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
25
+ spec.bindir = 'bin'
26
+ spec.executables = spec.files.grep(%r{^bin/}, &File.method(:basename))
27
+ spec.require_paths = ['lib']
28
+
29
+ spec.add_development_dependency 'bundler', '~> 1.10'
30
+ spec.add_development_dependency 'rake', '~> 10.0'
31
+ spec.add_development_dependency 'rspec', '~> 3'
32
+ spec.add_development_dependency 'pry', '~> 0.10'
33
+ spec.add_development_dependency 'awesome_print'
34
+
35
+ spec.add_dependency 'activesupport', '~> 3.2' # prevent mutations to require activesupport 5
36
+ spec.add_dependency 'mutations', '~> 0.8'
37
+ spec.add_dependency 'dry-validation', '~> 0.8'
38
+ spec.add_dependency 'hashie', '~> 3'
39
+ end
@@ -0,0 +1,30 @@
1
+ require 'mutations'
2
+ require 'dry-validation'
3
+
4
+ require 'dry/mutations/version'
5
+ require 'dry/mutations/utils'
6
+ require 'dry/mutations/monkeypatches'
7
+ require 'dry/mutations/predicates'
8
+ require 'dry/mutations/errors'
9
+ require 'dry/mutations/dsl'
10
+ require 'dry/mutations/command'
11
+
12
+ module Dry
13
+ # A dry implementation of mutations interface introduced by
14
+ # [Jonathan Novak](mailto:jnovak@gmail.com) in
15
+ # [`mutations` gem](http://github.com/cypriss/mutations).
16
+ #
17
+ # Basically, all the old mutations syntax is supported, plus
18
+ # native [`dry-validation`](http://github.com/dry-rb/dry-validation)
19
+ # schemas moight be used to describe validation rules.
20
+ module Mutations
21
+ def self.inject target
22
+ %i(Schema Blocks Types Weirdo).each do |mod|
23
+ target.singleton_class.prepend ::Dry::Mutations::DSL.const_get(mod)
24
+ end
25
+ end
26
+
27
+ DSL::Types::Nested.extend DSL::Module
28
+ ::Mutations::Command.prepend Command if Utils.Truthy?(ENV['GLOBAL_DRY_MUTATIONS'])
29
+ end
30
+ end
@@ -0,0 +1,49 @@
1
+ module Dry
2
+ module Mutations
3
+ module Command # :nodoc:
4
+ def self.prepended base
5
+ fail ArgumentError, "Can not prepend #{self.class} to #{base.class}: base class must be a ::Mutations::Command descendant." unless base < ::Mutations::Command
6
+ base.extend(DSL::Module) unless base.ancestors.include?(DSL::Module)
7
+ end
8
+
9
+ attr_reader :validation
10
+
11
+ def initialize(*args)
12
+ @raw_inputs = args.inject(Utils.Hash({})) do |h, arg|
13
+ fail ArgumentError.new('All arguments must be hashes') unless arg.is_a?(Hash)
14
+ h.merge!(arg)
15
+ end
16
+
17
+ @validation_result = schema.(@raw_inputs)
18
+
19
+ @inputs = Utils.Hash @validation_result.output
20
+
21
+ # dry: {:name=>["size cannot be greater than 10"],
22
+ # :properties=>{:first_arg=>["must be a string", "is in invalid format"]},
23
+ # :second_arg=>{:second_sub_arg=>["must be one of: 42"]},
24
+ # :amount=>["must be one of: 42"]}}
25
+ # mut: {:name=>#<Mutations::ErrorAtom:0x00000009534e50 @key=:name, @symbol=:max_length, @message=nil, @index=nil>,
26
+ # :properties=>{
27
+ # :second_arg=>{:second_sub_arg=>#<Mutations::ErrorAtom:0x000000095344a0 @key=:second_sub_arg, @symbol=:in, @message=nil, @index=nil>}
28
+ # :amount=>#<Mutations::ErrorAtom:0x00000009534068 @key=:amount, @symbol=:in, @message=nil, @index=nil>}
29
+
30
+ @errors = Errors::ErrorAtom.patch_message_set(
31
+ Errors::ErrorCompiler.new(schema).(@validation_result.to_ast.last)
32
+ )
33
+
34
+ # Run a custom validation method if supplied:
35
+ validate unless has_errors?
36
+ end
37
+
38
+ def messages
39
+ @messages ||= @errors && @errors.values.map(&:dry_message)
40
+ end
41
+
42
+ private
43
+
44
+ def schema
45
+ @schema ||= self.class.schema
46
+ end
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,5 @@
1
+ require 'dry/mutations/dsl/schema'
2
+ require 'dry/mutations/dsl/weirdo'
3
+ require 'dry/mutations/dsl/types'
4
+ require 'dry/mutations/dsl/blocks'
5
+ require 'dry/mutations/dsl/module'
@@ -0,0 +1,28 @@
1
+ module Dry
2
+ module Mutations
3
+ module DSL
4
+ module Blocks # :nodoc:
5
+ def optionality
6
+ @current = __callee__
7
+ instance_eval(&Proc.new) if block_given?
8
+ @current = nil
9
+ end
10
+
11
+ alias_method :optional, :optionality
12
+ alias_method :required, :optionality
13
+
14
+ private :optionality
15
+
16
+ # with_options empty: true do |empty|
17
+ # empty.string :bank_reference, nils: true
18
+ # empty.array :invoice_files, nils: true
19
+ # end
20
+ def with_options **params
21
+ @environs = params
22
+ yield self if block_given?
23
+ @environs = nil
24
+ end
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,21 @@
1
+ module Dry
2
+ module Mutations
3
+ module DSL
4
+ BRICKS = %i(Schema Blocks Types Weirdo).freeze.each
5
+
6
+ module Module # :nodoc:
7
+ def self.extended base
8
+ BRICKS.each do |mod|
9
+ base.singleton_class.prepend ::Dry::Mutations::DSL.const_get(mod)
10
+ end
11
+ end
12
+
13
+ def self.included base
14
+ BRICKS.each do |mod|
15
+ base.prepend ::Dry::Mutations::DSL.const_get(mod)
16
+ end
17
+ end
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,39 @@
1
+ module Dry
2
+ module Mutations
3
+ module DSL
4
+ module Schema # :nodoc:
5
+ def schema
6
+ @schema ||= derived_schema
7
+ return @schema unless block_given?
8
+
9
+ @schema = Validation.Schema(@schema, **@schema.options, &Proc.new)
10
+ end
11
+
12
+ private
13
+
14
+ def derived_schema
15
+ this = is_a?(Class) ? self : self.class
16
+
17
+ parent_with_schema = this.ancestors.drop(1).detect do |klazz|
18
+ next if [this, ::Mutations::Command, ::Dry::Mutations::Command].include?(klazz)
19
+ klazz.respond_to?(:schema) && klazz.schema.is_a?(Validation::Schema)
20
+ end
21
+ parent_with_schema ? Class.new(parent_with_schema.schema.class).new : empty_schema
22
+ end
23
+
24
+ def empty_schema
25
+ Validation.Schema do
26
+ configure do
27
+ # config.messages = :i18n
28
+ config.messages_file = ::File.join __dir__, '..', '..', '..', '..', 'config', 'messages.yml'
29
+ config.hash_type = :symbolized
30
+ config.input_processor = :sanitizer
31
+
32
+ predicates(Mutations::Predicates)
33
+ end
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,113 @@
1
+ module Dry
2
+ module Mutations
3
+ module DSL
4
+ module Types # :nodoc:
5
+ class Nested # :nodoc:
6
+ def self.init current
7
+ @current = current
8
+ instance_eval(&Proc.new) if block_given?
9
+ schema
10
+ end
11
+
12
+ def self.! current, &cb
13
+ Class.new(Nested).init current, &cb
14
+ end
15
+ end
16
+ # private_constant :Nested
17
+
18
+ ########################################################################
19
+ ### enumerables
20
+ ########################################################################
21
+
22
+ # FIXME: errors in double+ nested hashes are not nested! dry-rb glitch?
23
+ def hash name, **_params, &cb
24
+ current = @current # closure scope
25
+
26
+ schema { __send__(current, name).schema(Nested.!(current, &cb)) }
27
+
28
+ define_method(name) { Utils::Hash(@inputs[name]) } unless Nested === self
29
+ end
30
+
31
+ # FIXME: array of anonymous objects
32
+ def array name, **_params, &cb
33
+ current = @current # closure scope
34
+
35
+ nested = begin
36
+ Nested.!(current, &cb)
37
+ rescue Errors::AnonymousTypeDetected => err
38
+ Utils.Type err.type
39
+ end
40
+
41
+ name.nil? ? schema { each(nested) } : schema { __send__(current, name).each(nested) }
42
+
43
+ define_method(name) { @inputs[name] } unless Nested === self
44
+ end
45
+
46
+ ########################################################################
47
+ ### custom types
48
+ ########################################################################
49
+
50
+ def duck name, **params
51
+ current = @current # closure scope
52
+ filled_or_maybe = optionality(params)
53
+
54
+ schema do
55
+ __send__(current, name).__send__(filled_or_maybe, duck?: [*params[:methods]])
56
+ end
57
+ end
58
+
59
+ # possible params: `class: nil, builder: nil, new_records: false`
60
+ def model name, **params
61
+ current = @current # closure scope
62
+ filled_or_maybe = optionality(params)
63
+ params[:class] ||= name.to_s.gsub(/(?:\A|_)./) { |m| m[-1].upcase }
64
+
65
+ schema do
66
+ __send__(current, name).__send__(filled_or_maybe, model?: params[:class])
67
+ end
68
+ end
69
+
70
+ ########################################################################
71
+ ### generic types
72
+ ########################################################################
73
+
74
+ def generic_type name = nil, **params
75
+ fail Errors::AnonymousTypeDetected.new(__callee__) if name.nil?
76
+
77
+ params = @environs.merge params if @environs
78
+
79
+ # FIXME: :strip => true and siblings should be handled with procs?
80
+ current = @current # closure scope
81
+
82
+ opts = Utils.Guards(params)
83
+
84
+ type = [optionality(params), Utils.Type(__callee__)]
85
+
86
+ schema do
87
+ Utils.smart_send(__send__(current, name), *type, **opts)
88
+ end
89
+
90
+ unless Nested === self
91
+ define_method(name) { @inputs[name] }
92
+ define_method(:"#{name}_present?") { @inputs.key?(name) }
93
+ define_method(:"#{name}=") { |value| @inputs[name] = value }
94
+ end
95
+ end
96
+
97
+ %i(string integer float date time boolean).each do |m|
98
+ alias_method m, :generic_type
99
+ end
100
+
101
+ private :generic_type
102
+
103
+ private
104
+
105
+ def optionality nils
106
+ # rubocop:disable Style/NestedTernaryOperator
107
+ (nils.is_a?(Hash) ? nils[:nils] || nils[:empty] : nils) ? :maybe : :filled
108
+ # rubocop:enable Style/NestedTernaryOperator
109
+ end
110
+ end
111
+ end
112
+ end
113
+ end
@@ -0,0 +1,22 @@
1
+ module Dry
2
+ module Mutations
3
+ module DSL
4
+ module Weirdo # :nodoc:
5
+ # FIXME: try-catch and call super in rescue clause
6
+ def method_missing m, *args, &_cb
7
+ puts "==> [MM] “#{m}” called with args: “#{args.inspect}”"
8
+ name, current = args.shift, @current
9
+ schema do
10
+ configure do
11
+ define_method(:"#{name}?") do |_value|
12
+ false # FIXME
13
+ end
14
+ end
15
+
16
+ __send__(current, name) { __send__ :"#{name}?" }
17
+ end
18
+ end
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,19 @@
1
+ module Dry
2
+ module Mutations
3
+ module Errors
4
+ class AnonymousTypeDetected < StandardError # :nodoc:
5
+ attr_reader :type, :cause
6
+ def initialize type, cause = nil
7
+ @type = type
8
+ @cause = cause
9
+ end
10
+ end
11
+
12
+ class TypeError < StandardError # :nodoc:
13
+ end
14
+ end
15
+ end
16
+ end
17
+
18
+ require 'dry/mutations/errors/error_atom'
19
+ require 'dry/mutations/errors/error_compiler'
@@ -0,0 +1,30 @@
1
+ module Dry
2
+ module Mutations
3
+ module Errors
4
+ class ErrorAtom < ::Mutations::ErrorAtom # :nodoc:
5
+ %i(predicate path text rule args options).each do |mm|
6
+ define_method(mm) do |*args, &cb|
7
+ @dry_message.send mm, *args, &cb
8
+ end
9
+ end
10
+
11
+ attr_reader :dry_message
12
+
13
+ def initialize(key, error_symbol, dry_message, options = {})
14
+ super key, Utils::DRY_TO_MUTATIONS[error_symbol] || error_symbol, options
15
+ @dry_message = dry_message
16
+ end
17
+
18
+ def self.patch_message_set(set)
19
+ return nil if set.empty?
20
+
21
+ fail TypeError, "Expected: ::Dry::Validation::MessageSet; got: #{set.class}" unless set.is_a?(::Dry::Validation::MessageSet)
22
+ set.map.with_index.with_object(::Mutations::ErrorHash.new) do |(msg, idx), memo|
23
+ key = msg.path.join('.')
24
+ memo[key] = new(key, msg.predicate, msg, message: msg.text, index: idx)
25
+ end
26
+ end
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,31 @@
1
+ module Dry
2
+ module Mutations
3
+ module Errors
4
+ class ErrorCompiler < ::Dry::Validation::ErrorCompiler # :nodoc:
5
+ def initialize schema = nil
6
+ super (schema && schema.error_compiler || ::Dry::Validation::Schema).messages
7
+ end
8
+
9
+ def visit_error(node, opts = ::Dry::Validation::EMPTY_HASH)
10
+ rule, error = node
11
+ node_path = Array(opts.fetch(:path, rule))
12
+ path = (rule.is_a?(Array) && rule.size > node_path.size ? rule : node_path).compact
13
+ text = messages[rule]
14
+
15
+ if text
16
+ ErrorAtom.new(
17
+ [*node.first].join('.'),
18
+ predicate,
19
+ ::Dry::Validation::Message.new(node, path, text, rule: rule),
20
+ message: text
21
+ )
22
+ else
23
+ visit(error, opts.merge(path: path))
24
+ end
25
+ end
26
+ end
27
+ end
28
+ end
29
+ end
30
+
31
+ ::Dry::Validation::Schema.instance_variable_set(:@error_compiler, ::Dry::Mutations::Errors::ErrorCompiler.new)
@@ -0,0 +1,11 @@
1
+ # Well, I expect tons of questions about this.
2
+ # Just let it stay, unless I understand the cause of exception thrown
3
+ # in this particular case.
4
+
5
+ # rubocop:disable Style/ClassAndModuleChildren
6
+ class Dry::Logic::Rule::Value < Dry::Logic::Rule
7
+ def input
8
+ predicate.args.last rescue nil
9
+ end
10
+ end
11
+ # rubocop:enable Style/ClassAndModuleChildren
@@ -0,0 +1,24 @@
1
+ module Dry
2
+ module Mutations
3
+ module Predicates # :nodoc:
4
+ include ::Dry::Logic::Predicates
5
+
6
+ predicate(:duck?) do |expected, current|
7
+ expected.empty? || expected.all?(&current.method(:respond_to?))
8
+ end
9
+
10
+ # FIXME: at the moment this is an exact equivalent of :type? => User
11
+ predicate(:model?) do |expected, current|
12
+ return true if expected.nil?
13
+ expected = begin
14
+ ::Kernel.const_get(expected)
15
+ rescue TypeError => e
16
+ raise Errors::TypeError, "Bad “model” type. Error: [#{e.message}]"
17
+ rescue NameError => e
18
+ raise Errors::TypeError, "Bad “model” class. Error: [#{e.message}]"
19
+ end unless expected.is_a? Module
20
+ current.is_a?(expected)
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,92 @@
1
+ module Dry
2
+ module Mutations
3
+ module Utils # :nodoc:
4
+ FALSEY = /\A#{Regexp.union(%w(0 false falsey no n)).source}\z/i
5
+ TRUTHY = /\A#{Regexp.union(%w(1 true truthy yes y)).source}\z/i
6
+
7
+ def self.Falsey? input, explicit: true
8
+ explicit ? input.to_s =~ FALSEY : input.to_s !~ TRUTHY
9
+ end
10
+
11
+ def self.Truthy? input, explicit: true
12
+ explicit ? input.to_s =~ TRUTHY : input.to_s !~ FALSEY
13
+ end
14
+
15
+ # Lazy detector for Hashie::Mash
16
+ # TODO: Make it possible to choose friendly hash implementation
17
+ USE_HASHIE_MASH = Falsey?(ENV['PLAIN_HASHES'], explicit: false) && begin
18
+ require 'hashie/mash'
19
+ true
20
+ rescue LoadError => e
21
+ $stderr.puts [
22
+ '[DRY] Could not find Hashie::Mash.',
23
+ 'You probably want to install it / add it to your Gemfile.',
24
+ "Error: [#{e.message}]."
25
+ ].join($/)
26
+ end
27
+
28
+ # Converts a hash to a best available hash implementation
29
+ # with stringified keys, since `Mutations` expect hash
30
+ # keys to be strings.
31
+ def self.Hash hash
32
+ case
33
+ when USE_HASHIE_MASH
34
+ Kernel.const_get('::Hashie::Mash').new(hash)
35
+ when hash.respond_to?(:with_indifferent_access)
36
+ hash.with_indifferent_access
37
+ else
38
+ hash.map { |k, v| [k.to_s, v] }.to_h
39
+ end
40
+ end
41
+
42
+ DRY_TO_MUTATIONS = {
43
+ min_size?: :min_length,
44
+ max_size?: :max_length,
45
+ format?: :matches,
46
+ inclusion?: :in, # deprecated in Dry
47
+ included_in?: :in,
48
+ gteq?: :min,
49
+ lteq?: :max
50
+ }.freeze
51
+ MUTATIONS_TO_DRY = DRY_TO_MUTATIONS.invert.freeze
52
+
53
+ # Fuzzy converts params between different implementaions
54
+ def self.Guards *keys, **params
55
+ return {} if params.empty? || params[:empty] # Mutations `empty?` guard takes precedence on all others
56
+
57
+ keys = params.keys if keys.empty?
58
+ keys.flatten! # allow array to be passed as the only parameter
59
+
60
+ map = [DRY_TO_MUTATIONS, MUTATIONS_TO_DRY].detect do |h|
61
+ (h.keys & keys).any?
62
+ end
63
+
64
+ map.values_at(*keys).zip(keys.map(&params.method(:[])))
65
+ .to_h
66
+ .tap { |h| h.delete(nil) }
67
+ end
68
+
69
+ def self.Type type, **params
70
+ case type.to_s
71
+ when 'string'
72
+ if Falsey?(params[:strip])
73
+ :str?
74
+ else
75
+ # TODO: this silently coerces everything to be a string
76
+ # when `param[:strip]` is specified. This is likely OK, though.
77
+ ::Dry::Types::Constructor.new(
78
+ ::Dry::Types['strict.string'], fn: ->(v) { v.to_s.strip }
79
+ )
80
+ end
81
+ when 'integer' then :int?
82
+ when 'boolean' then :bool?
83
+ else :"#{type}?"
84
+ end
85
+ end
86
+
87
+ def self.smart_send receiver, *args, **params
88
+ params.empty? ? receiver.__send__(*args) : receiver.__send__(*args, **params)
89
+ end
90
+ end
91
+ end
92
+ end
@@ -0,0 +1,5 @@
1
+ module Dry
2
+ module Mutations
3
+ VERSION = '0.8.1'.freeze
4
+ end
5
+ end
metadata ADDED
@@ -0,0 +1,203 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: dry-mutations
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.8.1
5
+ platform: ruby
6
+ authors:
7
+ - Aleksei Matiushkin
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2016-07-11 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.10'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.10'
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'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3'
55
+ - !ruby/object:Gem::Dependency
56
+ name: pry
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '0.10'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '0.10'
69
+ - !ruby/object:Gem::Dependency
70
+ name: awesome_print
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: activesupport
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '3.2'
90
+ type: :runtime
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '3.2'
97
+ - !ruby/object:Gem::Dependency
98
+ name: mutations
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: '0.8'
104
+ type: :runtime
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: '0.8'
111
+ - !ruby/object:Gem::Dependency
112
+ name: dry-validation
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - "~>"
116
+ - !ruby/object:Gem::Version
117
+ version: '0.8'
118
+ type: :runtime
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - "~>"
123
+ - !ruby/object:Gem::Version
124
+ version: '0.8'
125
+ - !ruby/object:Gem::Dependency
126
+ name: hashie
127
+ requirement: !ruby/object:Gem::Requirement
128
+ requirements:
129
+ - - "~>"
130
+ - !ruby/object:Gem::Version
131
+ version: '3'
132
+ type: :runtime
133
+ prerelease: false
134
+ version_requirements: !ruby/object:Gem::Requirement
135
+ requirements:
136
+ - - "~>"
137
+ - !ruby/object:Gem::Version
138
+ version: '3'
139
+ description: |2
140
+ Mutations gem interface implemented with `dry-rb`’s validation schemas.
141
+ email:
142
+ - aleksei.matiushkin@kantox.com
143
+ executables:
144
+ - console
145
+ - setup
146
+ extensions: []
147
+ extra_rdoc_files: []
148
+ files:
149
+ - ".codeclimate.yml"
150
+ - ".gitignore"
151
+ - ".rspec"
152
+ - ".rubocop.yml"
153
+ - ".rubocop_todo.yml"
154
+ - ".travis.yml"
155
+ - CODE_OF_CONDUCT.md
156
+ - Gemfile
157
+ - LICENSE.txt
158
+ - README.md
159
+ - Rakefile
160
+ - bin/console
161
+ - bin/setup
162
+ - config/messages.yml
163
+ - dry-mutations.gemspec
164
+ - lib/dry/mutations.rb
165
+ - lib/dry/mutations/command.rb
166
+ - lib/dry/mutations/dsl.rb
167
+ - lib/dry/mutations/dsl/blocks.rb
168
+ - lib/dry/mutations/dsl/module.rb
169
+ - lib/dry/mutations/dsl/schema.rb
170
+ - lib/dry/mutations/dsl/types.rb
171
+ - lib/dry/mutations/dsl/weirdo.rb
172
+ - lib/dry/mutations/errors.rb
173
+ - lib/dry/mutations/errors/error_atom.rb
174
+ - lib/dry/mutations/errors/error_compiler.rb
175
+ - lib/dry/mutations/monkeypatches.rb
176
+ - lib/dry/mutations/predicates.rb
177
+ - lib/dry/mutations/utils.rb
178
+ - lib/dry/mutations/version.rb
179
+ homepage: http://github.com/am-kantox/dry-mutations
180
+ licenses:
181
+ - MIT
182
+ metadata: {}
183
+ post_install_message:
184
+ rdoc_options: []
185
+ require_paths:
186
+ - lib
187
+ required_ruby_version: !ruby/object:Gem::Requirement
188
+ requirements:
189
+ - - ">="
190
+ - !ruby/object:Gem::Version
191
+ version: '0'
192
+ required_rubygems_version: !ruby/object:Gem::Requirement
193
+ requirements:
194
+ - - ">="
195
+ - !ruby/object:Gem::Version
196
+ version: '0'
197
+ requirements: []
198
+ rubyforge_project:
199
+ rubygems_version: 2.4.8
200
+ signing_key:
201
+ specification_version: 4
202
+ summary: Mutations gem interface implemented with `dry-rb`’s validation schemas.
203
+ test_files: []