interfaceable 0.1.1

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: 54f19bb6bdcdc83dcf60a80e84e4dcbda3cf8a45cc3873213f1e57b40bbe4096
4
+ data.tar.gz: d2a192cddb7d1b166005d333eec6c88e7e605b41c788de1c123a50467c3122c8
5
+ SHA512:
6
+ metadata.gz: 75cacdc1919e4ef26a2b51ec875dc21a5b4ebe1ad982ff755fc3a60152cc1627eac2a0d720e2c7e8422aff42d384d0f7d7b21d40c526ad6d73f65dca90ef86b2
7
+ data.tar.gz: 246b9251c3943540a64308c56e1921d7bab4eea044a3ca185659e96f223144dc3c099837f00d14c9a3833e1a65d634ec5badde3c5b1e20157598c255820db0e5
@@ -0,0 +1,11 @@
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
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,10 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.6.6
6
+ before_install: gem install bundler -v 2.1.4
7
+ install: bundle
8
+ script:
9
+ - bundle exec rubocop
10
+ - COVERAGE=1 bundle exec rspec
data/Gemfile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ # Specify your gem's dependencies in interfacable.gemspec
6
+ gemspec
7
+
8
+ gem 'awesome_print'
9
+ gem 'rake'
10
+ gem 'rspec'
11
+ gem 'rubocop'
12
+ gem 'simplecov'
@@ -0,0 +1,63 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ interfaceable (0.1.1)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ ast (2.4.1)
10
+ awesome_print (1.8.0)
11
+ diff-lcs (1.4.4)
12
+ docile (1.3.2)
13
+ parallel (1.19.2)
14
+ parser (2.7.1.5)
15
+ ast (~> 2.4.1)
16
+ rainbow (3.0.0)
17
+ rake (13.0.1)
18
+ regexp_parser (1.8.1)
19
+ rexml (3.2.4)
20
+ rspec (3.9.0)
21
+ rspec-core (~> 3.9.0)
22
+ rspec-expectations (~> 3.9.0)
23
+ rspec-mocks (~> 3.9.0)
24
+ rspec-core (3.9.2)
25
+ rspec-support (~> 3.9.3)
26
+ rspec-expectations (3.9.2)
27
+ diff-lcs (>= 1.2.0, < 2.0)
28
+ rspec-support (~> 3.9.0)
29
+ rspec-mocks (3.9.1)
30
+ diff-lcs (>= 1.2.0, < 2.0)
31
+ rspec-support (~> 3.9.0)
32
+ rspec-support (3.9.3)
33
+ rubocop (0.92.0)
34
+ parallel (~> 1.10)
35
+ parser (>= 2.7.1.5)
36
+ rainbow (>= 2.2.2, < 4.0)
37
+ regexp_parser (>= 1.7)
38
+ rexml
39
+ rubocop-ast (>= 0.5.0)
40
+ ruby-progressbar (~> 1.7)
41
+ unicode-display_width (>= 1.4.0, < 2.0)
42
+ rubocop-ast (0.7.1)
43
+ parser (>= 2.7.1.5)
44
+ ruby-progressbar (1.10.1)
45
+ simplecov (0.19.0)
46
+ docile (~> 1.1)
47
+ simplecov-html (~> 0.11)
48
+ simplecov-html (0.12.3)
49
+ unicode-display_width (1.7.0)
50
+
51
+ PLATFORMS
52
+ ruby
53
+
54
+ DEPENDENCIES
55
+ awesome_print
56
+ interfaceable!
57
+ rake
58
+ rspec
59
+ rubocop
60
+ simplecov
61
+
62
+ BUNDLED WITH
63
+ 2.1.4
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020 artemave
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,73 @@
1
+ # Interfaceable [![Build Status](https://travis-ci.org/featurist/interfaceable.svg?branch=master)](https://travis-ci.org/featurist/interfaceable) [![Gem Version](https://badge.fury.io/rb/interfaceable.svg)](https://badge.fury.io/rb/interfaceable)
2
+
3
+ Impose interfaces on classes and let this gem automatically check that the interface constraints are met.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'interfaceable'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle install
16
+
17
+ ## Usage
18
+
19
+ In this example:
20
+
21
+ ```ruby
22
+ module Carrier
23
+ def call(number); end
24
+
25
+ def text(number, text); end
26
+ end
27
+
28
+ class Giffgaff
29
+ extend Interfaceable
30
+
31
+ implements Carrier
32
+ end
33
+ ```
34
+
35
+ An attempt to _load_ this code will result in the following error:
36
+
37
+ Giffgaff must implement: (Interfaceable::Error)
38
+ - Carrier#text
39
+ - Carrier#call
40
+
41
+ It will keep failing until `Giffgaff` defines those methods.
42
+
43
+ Correctly! E.g.:
44
+
45
+ ```ruby
46
+ class Giffgaff
47
+ def call(number); end
48
+
49
+ def text(number); end
50
+ end
51
+ ```
52
+
53
+ Will fail because of method signature mismatch:
54
+
55
+ Giffgaff must implement correctly: (Interfaceable::Error)
56
+ - Carrier#text:
57
+ - expected arguments: (req, req)
58
+ - actual arguments: (req)
59
+
60
+ ### Rails
61
+
62
+ Mix in `Interfaceable` before any of the application code is loaded. For example, in the initializer. For extra peace of mind, you can noop interface checking in production:
63
+
64
+ ```ruby
65
+ # config/initializers/interfaceable.rb
66
+ class Class
67
+ if Rails.env.production?
68
+ def implements(*args); end
69
+ else
70
+ include Interfaceable
71
+ end
72
+ end
73
+ ```
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'interfacable'
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,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/interfaceable/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'interfaceable'
7
+ spec.version = Interfaceable::VERSION
8
+ spec.authors = ['artemave']
9
+ spec.email = ['artemave@gmail.com']
10
+
11
+ spec.summary = 'Strict interfaces in Ruby'
12
+ # spec.description = %q{TODO: Write a longer description or delete this line.}
13
+ spec.homepage = 'https://github.com/featurist/interfaceable'
14
+ spec.license = 'MIT'
15
+ spec.required_ruby_version = Gem::Requirement.new('>= 2.3.0')
16
+
17
+ spec.metadata['homepage_uri'] = spec.homepage
18
+ spec.metadata['source_code_uri'] = 'https://github.com/artemave/interfaceable.git'
19
+
20
+ # Specify which files should be added to the gem when it is released.
21
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
22
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
23
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
24
+ end
25
+ spec.bindir = 'exe'
26
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
27
+ spec.require_paths = ['lib']
28
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'interfaceable/implementation_check'
4
+ require_relative 'interfaceable/error_formatter'
5
+
6
+ # Ruby interfaces yeah
7
+ module Interfaceable
8
+ # Subclassing exceptions because other errors don't raise from within `TracePoint.trace`.
9
+ # rubocop:disable Lint/InheritException
10
+ class Error < Exception; end
11
+ # rubocop:enable Lint/InheritException
12
+
13
+ def implements(*interfaces)
14
+ (@interfaces ||= []).push(*interfaces)
15
+
16
+ # rubocop:disable Naming/MemoizedInstanceVariableName
17
+ @interfaceable_trace ||= TracePoint.trace(:end) do |t|
18
+ # simplecov does not see inside this block
19
+ # :nocov:
20
+ # rubocop:enable Naming/MemoizedInstanceVariableName
21
+ if self == t.self
22
+ unless (errors = ImplementationCheck.new(self).perform(@interfaces)).empty?
23
+ error_message = ErrorFormatter.new(self).format_errors(errors)
24
+ raise(Error, error_message)
25
+ end
26
+
27
+ t.disable
28
+ end
29
+ # :nocov:
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Interfaceable
4
+ # Formats errors
5
+ class ErrorFormatter
6
+ def initialize(class_name)
7
+ @class_name = class_name
8
+ end
9
+
10
+ def format_errors(errors)
11
+ error_lines = []
12
+
13
+ if (missing_method_errors = all_missing_methods_errors(errors)).any?
14
+ error_lines << "#{@class_name} must implement:"
15
+ error_lines << missing_method_errors.map { |error| " - #{error}" }
16
+ end
17
+
18
+ if (signature_errors = all_signature_errors(errors)).any?
19
+ error_lines << "#{@class_name} must implement correctly:"
20
+ error_lines << signature_errors.map(&method(:format_signature_error))
21
+ end
22
+
23
+ error_lines.flatten.join("\n")
24
+ end
25
+
26
+ private
27
+
28
+ def format_signature_error(args)
29
+ meth, check = args
30
+ [
31
+ " - #{meth}:",
32
+ " - expected arguments: (#{check[:expected].map(&method(:format_arg)).join(', ')})",
33
+ " - actual arguments: (#{check[:actual].map(&method(:format_arg)).join(', ')})"
34
+ ]
35
+ end
36
+
37
+ def all_missing_methods_errors(errors)
38
+ errors.map do |interface, methods|
39
+ methods[:missing_class_methods].map { |meth| "#{interface}.#{meth}" } +
40
+ methods[:missing_instance_methods].map { |meth| "#{interface}##{meth}" }
41
+ end.flatten
42
+ end
43
+
44
+ def all_signature_errors(errors)
45
+ errors.map do |interface, methods|
46
+ methods[:class_method_signature_errors].map { |meth, check| ["#{interface}.#{meth}", check] } +
47
+ methods[:instance_method_signature_errors].map { |meth, check| ["#{interface}##{meth}", check] }
48
+ end.flatten(1)
49
+ end
50
+
51
+ def format_arg(arg)
52
+ {
53
+ 'req' => 'req',
54
+ 'opt' => 'opt=',
55
+ 'rest' => '*rest',
56
+ 'keyrest' => '**keyrest'
57
+ }.fetch(arg, "#{arg}:")
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,116 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Interfaceable
4
+ # Checks if class implements interfaces correctly
5
+ class ImplementationCheck
6
+ def initialize(klass)
7
+ @klass = klass
8
+ end
9
+
10
+ def perform(interfaces)
11
+ results = validate(interfaces)
12
+
13
+ results.reject do |_, checks|
14
+ checks.values.all?(&:empty?)
15
+ end
16
+ end
17
+
18
+ private
19
+
20
+ # rubocop:disable Metrics/MethodLength
21
+ def validate(interfaces)
22
+ interfaces.each_with_object({}) do |interface, acc|
23
+ missing_class_methods = find_missing_class_methods(interface)
24
+ missing_instance_methods = find_missing_instance_methods(interface)
25
+ instance_method_signature_errors = find_signature_errors(
26
+ interface,
27
+ :instance_method,
28
+ interface.instance_methods - missing_instance_methods
29
+ )
30
+ class_method_signature_errors = find_signature_errors(
31
+ interface,
32
+ :method,
33
+ own_methods(interface.methods) - missing_class_methods
34
+ )
35
+
36
+ acc[interface] = {
37
+ missing_instance_methods: missing_instance_methods,
38
+ missing_class_methods: missing_class_methods,
39
+ instance_method_signature_errors: instance_method_signature_errors,
40
+ class_method_signature_errors: class_method_signature_errors
41
+ }
42
+ end
43
+ end
44
+ # rubocop:enable Metrics/MethodLength
45
+
46
+ def find_missing_class_methods(interface)
47
+ own_methods(interface.methods).reject do |meth|
48
+ own_methods(@klass.methods).include?(meth)
49
+ end
50
+ end
51
+
52
+ def find_missing_instance_methods(interface)
53
+ interface.instance_methods.reject do |meth|
54
+ @klass.instance_methods.include?(meth)
55
+ end
56
+ end
57
+
58
+ def find_signature_errors(interface, method_type, implemented_methods)
59
+ implemented_methods.each_with_object({}) do |meth, acc|
60
+ expected_parameters = interface.send(method_type, meth).parameters
61
+ actual_parameters = @klass.send(method_type, meth).parameters
62
+
63
+ next unless (errors = check_method_signature(expected_parameters, actual_parameters))
64
+
65
+ acc[meth] = {
66
+ expected: errors[:expected_positional_parameters] + errors[:expected_keyword_parameters],
67
+ actual: errors[:actual_positional_parameters] + errors[:actual_keyword_parameters]
68
+ }
69
+ end
70
+ end
71
+
72
+ def own_methods(methods)
73
+ methods - Object.methods
74
+ end
75
+
76
+ # rubocop:disable Metrics/MethodLength
77
+ def check_method_signature(expected_parameters, actual_parameters)
78
+ expected_keyword_parameters, expected_positional_parameters = simplify_parameters(
79
+ *split_parameters_by_type(expected_parameters)
80
+ )
81
+ actual_keyword_parameters, actual_positional_parameters = simplify_parameters(
82
+ *split_parameters_by_type(actual_parameters)
83
+ )
84
+
85
+ return if expected_positional_parameters == actual_positional_parameters &&
86
+ expected_keyword_parameters == actual_keyword_parameters
87
+
88
+ {
89
+ expected_positional_parameters: expected_positional_parameters,
90
+ expected_keyword_parameters: expected_keyword_parameters,
91
+ actual_positional_parameters: actual_positional_parameters,
92
+ actual_keyword_parameters: actual_keyword_parameters
93
+ }
94
+ end
95
+ # rubocop:enable Metrics/MethodLength
96
+
97
+ def simplify_parameters(keyword_parameters, positional_parameters)
98
+ keyrest = pop_keyrest(keyword_parameters)
99
+
100
+ [
101
+ keyword_parameters.map(&:last).sort + (keyrest ? ['keyrest'] : []),
102
+ positional_parameters.map(&:first).reject { |p| p == :block }.map(&:to_s)
103
+ ]
104
+ end
105
+
106
+ def pop_keyrest(keyword_parameters)
107
+ return unless keyword_parameters.last && keyword_parameters.last.first == :keyrest
108
+
109
+ keyword_parameters.pop
110
+ end
111
+
112
+ def split_parameters_by_type(parameters)
113
+ parameters.partition { |(arg_type)| arg_type.to_s =~ /^key/ }
114
+ end
115
+ end
116
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Interfaceable
4
+ VERSION = '0.1.1'
5
+ end
metadata ADDED
@@ -0,0 +1,60 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: interfaceable
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - artemave
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-10-13 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description:
14
+ email:
15
+ - artemave@gmail.com
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - ".gitignore"
21
+ - ".rspec"
22
+ - ".travis.yml"
23
+ - Gemfile
24
+ - Gemfile.lock
25
+ - LICENSE.txt
26
+ - README.md
27
+ - Rakefile
28
+ - bin/console
29
+ - bin/setup
30
+ - interfaceable.gemspec
31
+ - lib/interfaceable.rb
32
+ - lib/interfaceable/error_formatter.rb
33
+ - lib/interfaceable/implementation_check.rb
34
+ - lib/interfaceable/version.rb
35
+ homepage: https://github.com/featurist/interfaceable
36
+ licenses:
37
+ - MIT
38
+ metadata:
39
+ homepage_uri: https://github.com/featurist/interfaceable
40
+ source_code_uri: https://github.com/artemave/interfaceable.git
41
+ post_install_message:
42
+ rdoc_options: []
43
+ require_paths:
44
+ - lib
45
+ required_ruby_version: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: 2.3.0
50
+ required_rubygems_version: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ requirements: []
56
+ rubygems_version: 3.0.3
57
+ signing_key:
58
+ specification_version: 4
59
+ summary: Strict interfaces in Ruby
60
+ test_files: []