liberty 0.1.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 0bbb2fc0351069beaffe253c8a6e49b16384b229e4560b3bbe1bc3975569b525
4
+ data.tar.gz: 615d3af3c92b65eb50ff6d073698392f5cd20b24319df1ec517b5ac0c2665ded
5
+ SHA512:
6
+ metadata.gz: 05133b60173a69591ca063f75c5ea7773510441f8124da02abf57f7f8fe1903ecaffbead071849ff473c559bbf2f6485448d76009d747cb3bd425a1302e38e4d
7
+ data.tar.gz: baeeea27ca2953b3709e71c694265bbba1e395a279eea22fa2e78b990bbfe3609973c85310ad45358a69796f0d27121a9d5c3c466a78bfef7ba1e6211dd7ae37
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --color
2
+ --require spec_helper
data/.standard.yml ADDED
@@ -0,0 +1,3 @@
1
+ # For available configuration options, see:
2
+ # https://github.com/testdouble/standard
3
+ ruby_version: 3.1
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2022-04-22
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders 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, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at alan@ridlehoover.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
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 liberty.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+
12
+ gem "standard", "~> 1.3"
data/Gemfile.lock ADDED
@@ -0,0 +1,92 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ liberty (0.1.0)
5
+ json (~> 2.3)
6
+ mustermann (~> 1.1)
7
+ mustermann-contrib (~> 1.1)
8
+ rack (~> 2.2)
9
+ rack-abstract-format (~> 0.9.9)
10
+ rack-accept-media-types (~> 0.9)
11
+
12
+ GEM
13
+ remote: https://rubygems.org/
14
+ specs:
15
+ ast (2.4.2)
16
+ diff-lcs (1.5.0)
17
+ docile (1.4.0)
18
+ hansi (0.2.0)
19
+ json (2.6.1)
20
+ mustermann (1.1.1)
21
+ ruby2_keywords (~> 0.0.1)
22
+ mustermann-contrib (1.1.1)
23
+ hansi (~> 0.2.0)
24
+ mustermann (= 1.1.1)
25
+ parallel (1.22.1)
26
+ parser (3.1.2.0)
27
+ ast (~> 2.4.1)
28
+ rack (2.2.3)
29
+ rack-abstract-format (0.9.9)
30
+ rack-accept-media-types (0.9)
31
+ rainbow (3.1.1)
32
+ rake (13.0.6)
33
+ regexp_parser (2.3.0)
34
+ rexml (3.2.5)
35
+ rspec (3.11.0)
36
+ rspec-core (~> 3.11.0)
37
+ rspec-expectations (~> 3.11.0)
38
+ rspec-mocks (~> 3.11.0)
39
+ rspec-core (3.11.0)
40
+ rspec-support (~> 3.11.0)
41
+ rspec-expectations (3.11.0)
42
+ diff-lcs (>= 1.2.0, < 2.0)
43
+ rspec-support (~> 3.11.0)
44
+ rspec-mocks (3.11.1)
45
+ diff-lcs (>= 1.2.0, < 2.0)
46
+ rspec-support (~> 3.11.0)
47
+ rspec-support (3.11.0)
48
+ rspec_junit_formatter (0.5.1)
49
+ rspec-core (>= 2, < 4, != 2.12.0)
50
+ rubocop (1.27.0)
51
+ parallel (~> 1.10)
52
+ parser (>= 3.1.0.0)
53
+ rainbow (>= 2.2.2, < 4.0)
54
+ regexp_parser (>= 1.8, < 3.0)
55
+ rexml
56
+ rubocop-ast (>= 1.16.0, < 2.0)
57
+ ruby-progressbar (~> 1.7)
58
+ unicode-display_width (>= 1.4.0, < 3.0)
59
+ rubocop-ast (1.17.0)
60
+ parser (>= 3.1.1.0)
61
+ rubocop-performance (1.13.3)
62
+ rubocop (>= 1.7.0, < 2.0)
63
+ rubocop-ast (>= 0.4.0)
64
+ ruby-progressbar (1.11.0)
65
+ ruby2_keywords (0.0.5)
66
+ simplecov (0.21.2)
67
+ docile (~> 1.1)
68
+ simplecov-html (~> 0.11)
69
+ simplecov_json_formatter (~> 0.1)
70
+ simplecov-html (0.12.3)
71
+ simplecov_json_formatter (0.1.4)
72
+ standard (1.10.0)
73
+ rubocop (= 1.27.0)
74
+ rubocop-performance (= 1.13.3)
75
+ unicode-display_width (2.1.0)
76
+
77
+ PLATFORMS
78
+ x86_64-darwin-21
79
+ x86_64-linux
80
+
81
+ DEPENDENCIES
82
+ bundler (~> 2.0)
83
+ liberty!
84
+ rack (~> 2.2)
85
+ rake (~> 13.0)
86
+ rspec (~> 3.0)
87
+ rspec_junit_formatter (~> 0.4)
88
+ simplecov (~> 0.21)
89
+ standard (~> 1.3)
90
+
91
+ BUNDLED WITH
92
+ 2.3.11
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Alan Ridlehoover and Fito von Zastrow
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.
data/README.md ADDED
@@ -0,0 +1,89 @@
1
+ <img src="assets/liberty.png"/>
2
+
3
+ # Liberty
4
+
5
+ [![Ruby](https://github.com/first-try-software/liberty/actions/workflows/main.yml/badge.svg?branch=main)](https://github.com/first-try-software/liberty/actions/workflows/main.yml)
6
+
7
+ Liberty is the state of being free from oppressive restrictions imposed by authority.
8
+
9
+ Liberty is also a minimalist web-framework for Ruby that seeks to get out of your way
10
+ so that you can focus on your most valuable asset: your business logic. It is structured
11
+ in a way that encourages you to separate your business logic from the framework code.
12
+ It provides the web adapter for a Hexagonal Architecture and it works well with Domain
13
+ Driven Design.
14
+
15
+ ## Installation
16
+
17
+ Install the gem and add to the application's Gemfile by executing:
18
+
19
+ $ bundle add liberty
20
+
21
+ If bundler is not being used to manage dependencies, install the gem by executing:
22
+
23
+ $ gem install liberty
24
+
25
+ ## Usage
26
+
27
+ Liberty consists of four top level classes:
28
+ * Endpoint
29
+ * CORS
30
+ * Application (private)
31
+ * Router (private)
32
+
33
+ Inherit from the `Endpoint` class to create class that responds to a single type of request.
34
+ Here's an example for an HTTP get to the `/hello` route, which returns a hello world JSON payload.
35
+
36
+ ```ruby
37
+ class MyEndpoint < Liberty::Endpoint
38
+ responds_to :get, '/hello'
39
+
40
+ def status
41
+ 200
42
+ end
43
+
44
+ def json
45
+ { hello: :world }
46
+ end
47
+ end
48
+ ```
49
+
50
+ Using `responds_to` as in the example above registers a class to receive traffic on that route
51
+ with our incredibly fast `Router`. You shouldn't ever need to use the `Router` directly. Just
52
+ use `responds_to` to register your route.
53
+
54
+ The `Application` class is another private class that turns each `Endpoint` class into a
55
+ Rack application. This is also a class you won't use directly.
56
+
57
+ Finally, the `CORS` class allows you to configure CORS headers for your application, like this:
58
+
59
+ ```ruby
60
+ Liberty::CORS.config do |config|
61
+ config.headers = {
62
+ 'Access-Control-Allow-Origin' => '*',
63
+ 'Access-Control-Allow-Methods' => 'POST, GET, PUT, PATCH, DELETE, OPTIONS',
64
+ 'Access-Control-Allow-Headers' => 'Origin, Content-Type, Accept, Authorization, X-Your-Own-Custom-Headers',
65
+ 'Access-Control-Max-Age' => '1728000'
66
+ }
67
+ end
68
+ ```
69
+
70
+ If you configure your CORS headers before you launch your application, `Endpoints` will
71
+ automatically respond with the right headers.
72
+
73
+ ## Development
74
+
75
+ 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.
76
+
77
+ 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 the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
78
+
79
+ ## Contributing
80
+
81
+ Bug reports and pull requests are welcome on GitHub at https://github.com/first-try-software/liberty. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/first-try-software/liberty/blob/main/CODE_OF_CONDUCT.md).
82
+
83
+ ## License
84
+
85
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
86
+
87
+ ## Code of Conduct
88
+
89
+ Everyone interacting in the Liberty project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/first-try-software/liberty/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,10 @@
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
+ require "standard/rake"
9
+
10
+ task default: %i[spec standard]
Binary file
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "json"
4
+ require_relative "null"
5
+
6
+ module Liberty
7
+ module Adapters
8
+ module Parsers
9
+ class Factory
10
+ def self.build(media_type:)
11
+ case media_type
12
+ when /application\/json/
13
+ Parsers::JSON
14
+ else
15
+ Parsers::Null
16
+ end
17
+ end
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Liberty
4
+ module Adapters
5
+ module Parsers
6
+ class JSON
7
+ def self.parse(text)
8
+ text ? ::JSON.parse(text) : {}
9
+ rescue ::JSON::ParserError
10
+ {}
11
+ end
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Liberty
4
+ module Adapters
5
+ module Parsers
6
+ class Null
7
+ def self.parse(*args)
8
+ end
9
+ end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "parsers/factory"
4
+
5
+ module Liberty
6
+ module Adapters
7
+ class Request
8
+ PARSED_BODY = "parsed_body"
9
+ ROUTER_PARAMS = "router.params"
10
+
11
+ attr_reader :env
12
+
13
+ def initialize(env = nil)
14
+ @env = env
15
+ end
16
+
17
+ def headers
18
+ @headers ||= env ? {
19
+ accept_media_types: accept_media_types,
20
+ preferred_media_type: preferred_media_type
21
+ } : {}
22
+ end
23
+
24
+ def params
25
+ @params ||= env ? all_params : {}
26
+ end
27
+
28
+ private
29
+
30
+ def all_params
31
+ form_params.merge!(body_params).merge!(url_params)
32
+ end
33
+
34
+ def accept_media_types
35
+ @accept_media_types ||= rack_request.accept_media_types
36
+ end
37
+
38
+ def preferred_media_type
39
+ accept_media_types.first
40
+ end
41
+
42
+ def form_params
43
+ symbolize_keys(rack_request.params || {})
44
+ end
45
+
46
+ def body_params
47
+ symbolize_keys(parsed_body || {})
48
+ end
49
+
50
+ def parsed_body
51
+ Parsers::Factory.build(media_type: media_type).parse(body)
52
+ end
53
+
54
+ def body
55
+ read_body = rack_request.body.read
56
+ rack_request.body.rewind
57
+ read_body
58
+ end
59
+
60
+ def media_type
61
+ rack_request.media_type
62
+ end
63
+
64
+ def url_params
65
+ env[ROUTER_PARAMS] || {}
66
+ end
67
+
68
+ def symbolize_keys(hash)
69
+ hash.each_with_object({}) { |(key, value), obj| obj[key.to_sym] = value }
70
+ end
71
+
72
+ def rack_request
73
+ @rack_request ||= Rack::Request.new(env)
74
+ end
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Liberty
4
+ module Adapters
5
+ class Response
6
+ CONTENT_TYPE = "Content-Type"
7
+ CONTENT_LENGTH = "Content-Length"
8
+ MIME_TYPE_JSON = "application/json"
9
+ MIME_TYPE_HTML = "text/html"
10
+ MIME_TYPE_TEXT = "text/plain"
11
+ EMPTY_CONTENT = ""
12
+
13
+ attr_reader :endpoint
14
+
15
+ def initialize(endpoint)
16
+ @endpoint = endpoint
17
+ end
18
+
19
+ def to_rack_response
20
+ [status, headers, [content]]
21
+ end
22
+
23
+ private
24
+
25
+ def status
26
+ endpoint.status
27
+ end
28
+
29
+ def headers
30
+ headers = {CONTENT_LENGTH => content_length}
31
+ headers[CONTENT_TYPE] = content_type if content_type
32
+ headers.merge!(response_headers)
33
+ headers
34
+ end
35
+
36
+ def response_headers
37
+ @response_headers ||= Hash(endpoint.headers)
38
+ end
39
+
40
+ def content_type
41
+ return MIME_TYPE_JSON if json
42
+ return MIME_TYPE_HTML if html
43
+ return MIME_TYPE_TEXT if text
44
+ end
45
+
46
+ def content_length
47
+ content.bytesize.to_s
48
+ end
49
+
50
+ def content
51
+ json || html || text || body || EMPTY_CONTENT
52
+ end
53
+
54
+ def json
55
+ return unless response_json
56
+ return stringified_json if valid_json?
57
+
58
+ response_json.to_json
59
+ end
60
+
61
+ def response_json
62
+ @response_json ||= endpoint.json
63
+ end
64
+
65
+ def html
66
+ @html ||= endpoint.html
67
+ end
68
+
69
+ def text
70
+ @text ||= endpoint.text
71
+ end
72
+
73
+ def body
74
+ @body ||= endpoint.body
75
+ end
76
+
77
+ def valid_json?
78
+ JSON.parse(stringified_json)
79
+ true
80
+ rescue JSON::ParserError
81
+ false
82
+ end
83
+
84
+ def stringified_json
85
+ @stringified_json ||= endpoint.json.to_s
86
+ end
87
+ end
88
+ end
89
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "adapters/request"
4
+ require_relative "adapters/response"
5
+
6
+ module Liberty
7
+ class Application
8
+ attr_reader :endpoint_class
9
+
10
+ def initialize(endpoint_class:)
11
+ @endpoint_class = endpoint_class
12
+ end
13
+
14
+ def call(env)
15
+ response(env).to_rack_response
16
+ end
17
+
18
+ private
19
+
20
+ def response(env)
21
+ Adapters::Response.new(endpoint(request(env)))
22
+ end
23
+
24
+ def request(env)
25
+ Adapters::Request.new(env)
26
+ end
27
+
28
+ def endpoint(request)
29
+ endpoint_class.new.tap { |endpoint| endpoint.inject(request: request) }
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Liberty
4
+ class CORS
5
+ class Middleware
6
+ def initialize(app)
7
+ @app = app
8
+ end
9
+
10
+ def call(env)
11
+ return @app.call(env) unless cors_configured?
12
+ return cors_response if cors_request?(env)
13
+
14
+ with_cors_header(@app.call(env))
15
+ end
16
+
17
+ private
18
+
19
+ def with_cors_header(response)
20
+ status, headers, body = response
21
+
22
+ [status, headers.merge(access_control_header), body]
23
+ end
24
+
25
+ def access_control_header
26
+ Liberty::CORS.headers.slice("Access-Control-Allow-Origin")
27
+ end
28
+
29
+ def cors_configured?
30
+ !Liberty::CORS.headers.empty?
31
+ end
32
+
33
+ def cors_request?(env)
34
+ env["REQUEST_METHOD"] == "OPTIONS"
35
+ end
36
+
37
+ def cors_response
38
+ [200, default_headers.merge(Liberty::CORS.headers), []]
39
+ end
40
+
41
+ def default_headers
42
+ {
43
+ "Content-Type" => "text/plain",
44
+ "Content-Length" => "0"
45
+ }
46
+ end
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "cors/middleware"
4
+
5
+ module Liberty
6
+ class CORS
7
+ class << self
8
+ def config
9
+ yield(self)
10
+ end
11
+
12
+ def headers
13
+ @headers ||= {}
14
+ end
15
+
16
+ def headers=(headers)
17
+ raise ArgumentError.new("Expected headers to be a Hash, received a #{headers.class} instead") unless headers.is_a?(Hash)
18
+
19
+ @headers = headers
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Liberty
4
+ class Endpoint
5
+ DEFAULT_STATUS = 200
6
+
7
+ def self.responds_to(verb, path)
8
+ Liberty.add_endpoint(verb: verb, path: path, endpoint_class: self)
9
+ end
10
+
11
+ attr_reader :request
12
+
13
+ def inject(request:)
14
+ @request = request
15
+ end
16
+
17
+ def params
18
+ request.params
19
+ end
20
+
21
+ def preferred_media_type
22
+ request.headers[:preferred_media_type]
23
+ end
24
+
25
+ def status
26
+ DEFAULT_STATUS
27
+ end
28
+
29
+ def headers
30
+ end
31
+
32
+ def json
33
+ end
34
+
35
+ def html
36
+ end
37
+
38
+ def text
39
+ end
40
+
41
+ def body
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Liberty
4
+ class Router
5
+ class Node
6
+ MUSTERMANN_VERSION = "5.0"
7
+ DYNAMIC_PREFIX = /:/
8
+
9
+ attr_reader :endpoint
10
+
11
+ def initialize
12
+ @endpoint = nil
13
+ @static = nil
14
+ @dynamic = nil
15
+ end
16
+
17
+ def add(segment)
18
+ dynamic?(segment) ? add_dynamic(segment) : add_static(segment)
19
+ end
20
+
21
+ def find(segment)
22
+ find_node(segment) { |params| yield(symbolize_keys(params)) if params && block_given? }
23
+ end
24
+
25
+ def attach(endpoint)
26
+ @endpoint = endpoint
27
+ end
28
+
29
+ def print(verb, routes, prefix = "")
30
+ print_segments(@static, routes, verb, prefix)
31
+ print_segments(@dynamic, routes, verb, prefix)
32
+ end
33
+
34
+ private
35
+
36
+ def add_static(segment)
37
+ @static ||= {}
38
+ @static[segment] ||= self.class.new
39
+ end
40
+
41
+ def add_dynamic(segment)
42
+ @dynamic ||= {}
43
+ @dynamic[dynamic_segment(segment)] ||= self.class.new
44
+ end
45
+
46
+ def find_node(segment, &block)
47
+ return if empty?
48
+
49
+ find_static(segment, &block) || find_dynamic(segment, &block)
50
+ end
51
+
52
+ def find_static(segment, &block)
53
+ @static ||= {}
54
+ @static[segment].tap { |node| node && block.call({}) }
55
+ end
56
+
57
+ def find_dynamic(segment, &block)
58
+ @dynamic ||= {}
59
+ matcher = @dynamic.keys.find { |matcher| block.call(matcher.match(segment)&.named_captures) }
60
+ matcher && @dynamic[matcher]
61
+ end
62
+
63
+ def empty?
64
+ !@static && !@dynamic
65
+ end
66
+
67
+ def dynamic?(segment)
68
+ DYNAMIC_PREFIX.match?(segment)
69
+ end
70
+
71
+ def dynamic_segment(segment)
72
+ Mustermann.new(segment, type: :rails, version: MUSTERMANN_VERSION)
73
+ end
74
+
75
+ def symbolize_keys(hash)
76
+ hash.each_with_object({}) { |(key, value), obj| obj[key.to_sym] = value }
77
+ end
78
+
79
+ def print_segments(segments, routes, verb, prefix)
80
+ segments&.each do |segment, node|
81
+ routes << {verb: verb, path: "#{prefix}/#{segment}", endpoint: node.endpoint} if node.endpoint
82
+ node.print(verb, routes, "#{prefix}/#{segment}")
83
+ end
84
+ end
85
+ end
86
+ end
87
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Liberty
4
+ class Router
5
+ class Printer
6
+ VERBS = %w[GET HEAD POST PUT PATCH DELETE].freeze
7
+
8
+ attr_reader :static, :dynamic, :memo, :stdout
9
+
10
+ def initialize(static, dynamic, stdout = $stdout)
11
+ @static, @dynamic = static, dynamic
12
+ @stdout = stdout
13
+ @memo = []
14
+ end
15
+
16
+ def print
17
+ gather_static_routes
18
+ gather_dynamic_routes
19
+ print_routes
20
+ end
21
+
22
+ private
23
+
24
+ def gather_static_routes
25
+ static.each do |verb, routes|
26
+ routes.each do |path, endpoint|
27
+ memo << {verb: verb, path: path, endpoint: endpoint}
28
+ end
29
+ end
30
+ end
31
+
32
+ def gather_dynamic_routes
33
+ dynamic.each do |verb, trie|
34
+ trie.print(verb, memo)
35
+ end
36
+ end
37
+
38
+ def print_routes
39
+ sorted_routes.each { |route| print_route(**route) }
40
+ end
41
+
42
+ def sorted_routes
43
+ memo.sort_by { |route| "#{route[:path]}-#{VERBS.find_index(route[:verb])}" }
44
+ end
45
+
46
+ def print_route(verb:, path:, endpoint:)
47
+ stdout.puts "#{pad(verb, 8)} #{pad(path, -50)} => #{endpoint}"
48
+ end
49
+
50
+ def pad(str, length)
51
+ "%#{length}s" % str
52
+ end
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "node"
4
+
5
+ module Liberty
6
+ class Router
7
+ class Trie
8
+ PATH_SEPARATOR = "/"
9
+
10
+ def initialize
11
+ @root = Node.new
12
+ end
13
+
14
+ def add_route(path, endpoint)
15
+ traverse(path) { |segment, node| node.add(segment) }.attach(endpoint)
16
+ end
17
+
18
+ def find_route(path)
19
+ route_params = {}
20
+ node = traverse(path) do |segment, node|
21
+ node.find(segment) { |params| route_params.merge!(params) }
22
+ end
23
+
24
+ yield(route_params) if node && block_given?
25
+
26
+ node&.endpoint
27
+ end
28
+
29
+ def print(verb, routes)
30
+ @root.print(verb, routes)
31
+ end
32
+
33
+ private
34
+
35
+ def traverse(path)
36
+ _, *segments = path.split(PATH_SEPARATOR)
37
+ segments.reduce(@root) do |node, segment|
38
+ break unless node
39
+ yield(segment, node)
40
+ end
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,91 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "router/trie"
4
+ require_relative "router/printer"
5
+
6
+ module Liberty
7
+ class Router
8
+ GET = "GET"
9
+ HEAD = "HEAD"
10
+ POST = "POST"
11
+ PUT = "PUT"
12
+ PATCH = "PATCH"
13
+ DELETE = "DELETE"
14
+ REQUEST_METHOD = "REQUEST_METHOD"
15
+ PATH_INFO = "PATH_INFO"
16
+ ROUTER_PARAMS = "router.params"
17
+ DYNAMIC_PREFIX = /:/
18
+ NOT_FOUND_RESPONSE = [404, {"Content-Length" => "9"}, ["Not Found"]].freeze
19
+
20
+ def initialize
21
+ @apps = {}
22
+ @static = Hash.new { |h, k| h[k] = {} }
23
+ @dynamic = {}
24
+ end
25
+
26
+ def get(path, to:)
27
+ register_route(GET, path, to)
28
+ register_route(HEAD, path, to)
29
+ end
30
+
31
+ def post(path, to:)
32
+ register_route(POST, path, to)
33
+ end
34
+
35
+ def put(path, to:)
36
+ register_route(PUT, path, to)
37
+ end
38
+
39
+ def patch(path, to:)
40
+ register_route(PATCH, path, to)
41
+ end
42
+
43
+ def delete(path, to:)
44
+ register_route(DELETE, path, to)
45
+ end
46
+
47
+ def call(env)
48
+ endpoint = find_endpoint(env[REQUEST_METHOD], env[PATH_INFO]) { |params| env[ROUTER_PARAMS] = params }
49
+ endpoint ? endpoint.call(env) : NOT_FOUND_RESPONSE
50
+ end
51
+
52
+ def print(stdout = $stdout)
53
+ Printer.new(@static, @dynamic, stdout).print
54
+ end
55
+
56
+ private
57
+
58
+ def register_route(verb, path, to)
59
+ dynamic?(path) ? register_dynamic_route(verb, path, to) : register_static_route(verb, path, to)
60
+ end
61
+
62
+ def find_endpoint(verb, path, &block)
63
+ find_static(verb, path, &block) || find_dynamic(verb, path, &block)
64
+ end
65
+
66
+ def find_static(verb, path, &block)
67
+ @static[verb][path].tap { |endpoint| endpoint && block.call({}) }
68
+ end
69
+
70
+ def find_dynamic(verb, path, &block)
71
+ dynamic(verb).find_route(path, &block)
72
+ end
73
+
74
+ def dynamic?(path)
75
+ DYNAMIC_PREFIX.match?(path)
76
+ end
77
+
78
+ def dynamic(verb)
79
+ @dynamic[verb] ||= Trie.new
80
+ end
81
+
82
+ def register_dynamic_route(verb, path, to)
83
+ @dynamic[verb] ||= Trie.new
84
+ @dynamic[verb].add_route(path, to)
85
+ end
86
+
87
+ def register_static_route(verb, path, to)
88
+ @static[verb][path] = to
89
+ end
90
+ end
91
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Liberty
4
+ VERSION = "0.1.0"
5
+ end
data/lib/liberty.rb ADDED
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "mustermann"
5
+ require "rack"
6
+ require "rack/accept_media_types"
7
+ require "rack/abstract_format"
8
+
9
+ require_relative "liberty/version"
10
+ require_relative "liberty/endpoint"
11
+ require_relative "liberty/router"
12
+ require_relative "liberty/application"
13
+ require_relative "liberty/cors"
14
+
15
+ module Liberty
16
+ def self.rack_app
17
+ @server ||= Rack::Builder.new(Liberty.router) do
18
+ use Liberty::CORS::Middleware
19
+ use Rack::AbstractFormat
20
+ end
21
+ end
22
+
23
+ def self.add_endpoint(verb:, path:, endpoint_class:)
24
+ app = Application.new(endpoint_class: endpoint_class)
25
+ router.public_send(verb, path, to: app)
26
+ end
27
+
28
+ def self.router
29
+ @router ||= Liberty::Router.new
30
+ end
31
+ end
data/liberty.gemspec ADDED
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/liberty/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "liberty"
7
+ spec.version = Liberty::VERSION
8
+ spec.authors = ["Alan Ridlehoover", "Fito von Zastrow"]
9
+ spec.email = ["liberty@firsttry.software"]
10
+
11
+ spec.summary = "A framework for Ruby web applications"
12
+ spec.description = "Liberty is the state of being free from oppressive restrictions imposed by authority."
13
+ spec.homepage = "https://github.com/first-try-software/liberty"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 3.1.0"
16
+
17
+ spec.metadata["homepage_uri"] = spec.homepage
18
+ spec.metadata["source_code_uri"] = spec.homepage
19
+ spec.metadata["changelog_uri"] = "https://github.com/first-try-software/liberty/CHANGELOG.md"
20
+
21
+ spec.files = Dir.chdir(__dir__) do
22
+ `git ls-files -z`.split("\x0").reject do |f|
23
+ (f == __FILE__) || f.match(%r{\A(?:(?:bin|test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
24
+ end
25
+ end
26
+ spec.bindir = "exe"
27
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
28
+ spec.require_paths = ["lib"]
29
+
30
+ spec.add_dependency "mustermann", "~> 1.1"
31
+ spec.add_dependency "mustermann-contrib", "~> 1.1"
32
+ spec.add_dependency "json", "~> 2.3"
33
+ spec.add_dependency "rack", "~> 2.2"
34
+ spec.add_dependency "rack-abstract-format", "~> 0.9.9"
35
+ spec.add_dependency "rack-accept-media-types", "~> 0.9"
36
+
37
+ spec.add_development_dependency "rack", "~> 2.2"
38
+ spec.add_development_dependency "bundler", "~> 2.0"
39
+ spec.add_development_dependency "rake", "~> 12.0"
40
+ spec.add_development_dependency "rspec", "~> 3.0"
41
+ spec.add_development_dependency "rspec_junit_formatter", "~> 0.4"
42
+ spec.add_development_dependency "simplecov", "~> 0.21"
43
+ end
metadata ADDED
@@ -0,0 +1,242 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: liberty
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Alan Ridlehoover
8
+ - Fito von Zastrow
9
+ autorequire:
10
+ bindir: exe
11
+ cert_chain: []
12
+ date: 2022-04-24 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: mustermann
16
+ requirement: !ruby/object:Gem::Requirement
17
+ requirements:
18
+ - - "~>"
19
+ - !ruby/object:Gem::Version
20
+ version: '1.1'
21
+ type: :runtime
22
+ prerelease: false
23
+ version_requirements: !ruby/object:Gem::Requirement
24
+ requirements:
25
+ - - "~>"
26
+ - !ruby/object:Gem::Version
27
+ version: '1.1'
28
+ - !ruby/object:Gem::Dependency
29
+ name: mustermann-contrib
30
+ requirement: !ruby/object:Gem::Requirement
31
+ requirements:
32
+ - - "~>"
33
+ - !ruby/object:Gem::Version
34
+ version: '1.1'
35
+ type: :runtime
36
+ prerelease: false
37
+ version_requirements: !ruby/object:Gem::Requirement
38
+ requirements:
39
+ - - "~>"
40
+ - !ruby/object:Gem::Version
41
+ version: '1.1'
42
+ - !ruby/object:Gem::Dependency
43
+ name: json
44
+ requirement: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - "~>"
47
+ - !ruby/object:Gem::Version
48
+ version: '2.3'
49
+ type: :runtime
50
+ prerelease: false
51
+ version_requirements: !ruby/object:Gem::Requirement
52
+ requirements:
53
+ - - "~>"
54
+ - !ruby/object:Gem::Version
55
+ version: '2.3'
56
+ - !ruby/object:Gem::Dependency
57
+ name: rack
58
+ requirement: !ruby/object:Gem::Requirement
59
+ requirements:
60
+ - - "~>"
61
+ - !ruby/object:Gem::Version
62
+ version: '2.2'
63
+ type: :runtime
64
+ prerelease: false
65
+ version_requirements: !ruby/object:Gem::Requirement
66
+ requirements:
67
+ - - "~>"
68
+ - !ruby/object:Gem::Version
69
+ version: '2.2'
70
+ - !ruby/object:Gem::Dependency
71
+ name: rack-abstract-format
72
+ requirement: !ruby/object:Gem::Requirement
73
+ requirements:
74
+ - - "~>"
75
+ - !ruby/object:Gem::Version
76
+ version: 0.9.9
77
+ type: :runtime
78
+ prerelease: false
79
+ version_requirements: !ruby/object:Gem::Requirement
80
+ requirements:
81
+ - - "~>"
82
+ - !ruby/object:Gem::Version
83
+ version: 0.9.9
84
+ - !ruby/object:Gem::Dependency
85
+ name: rack-accept-media-types
86
+ requirement: !ruby/object:Gem::Requirement
87
+ requirements:
88
+ - - "~>"
89
+ - !ruby/object:Gem::Version
90
+ version: '0.9'
91
+ type: :runtime
92
+ prerelease: false
93
+ version_requirements: !ruby/object:Gem::Requirement
94
+ requirements:
95
+ - - "~>"
96
+ - !ruby/object:Gem::Version
97
+ version: '0.9'
98
+ - !ruby/object:Gem::Dependency
99
+ name: rack
100
+ requirement: !ruby/object:Gem::Requirement
101
+ requirements:
102
+ - - "~>"
103
+ - !ruby/object:Gem::Version
104
+ version: '2.2'
105
+ type: :development
106
+ prerelease: false
107
+ version_requirements: !ruby/object:Gem::Requirement
108
+ requirements:
109
+ - - "~>"
110
+ - !ruby/object:Gem::Version
111
+ version: '2.2'
112
+ - !ruby/object:Gem::Dependency
113
+ name: bundler
114
+ requirement: !ruby/object:Gem::Requirement
115
+ requirements:
116
+ - - "~>"
117
+ - !ruby/object:Gem::Version
118
+ version: '2.0'
119
+ type: :development
120
+ prerelease: false
121
+ version_requirements: !ruby/object:Gem::Requirement
122
+ requirements:
123
+ - - "~>"
124
+ - !ruby/object:Gem::Version
125
+ version: '2.0'
126
+ - !ruby/object:Gem::Dependency
127
+ name: rake
128
+ requirement: !ruby/object:Gem::Requirement
129
+ requirements:
130
+ - - "~>"
131
+ - !ruby/object:Gem::Version
132
+ version: '12.0'
133
+ type: :development
134
+ prerelease: false
135
+ version_requirements: !ruby/object:Gem::Requirement
136
+ requirements:
137
+ - - "~>"
138
+ - !ruby/object:Gem::Version
139
+ version: '12.0'
140
+ - !ruby/object:Gem::Dependency
141
+ name: rspec
142
+ requirement: !ruby/object:Gem::Requirement
143
+ requirements:
144
+ - - "~>"
145
+ - !ruby/object:Gem::Version
146
+ version: '3.0'
147
+ type: :development
148
+ prerelease: false
149
+ version_requirements: !ruby/object:Gem::Requirement
150
+ requirements:
151
+ - - "~>"
152
+ - !ruby/object:Gem::Version
153
+ version: '3.0'
154
+ - !ruby/object:Gem::Dependency
155
+ name: rspec_junit_formatter
156
+ requirement: !ruby/object:Gem::Requirement
157
+ requirements:
158
+ - - "~>"
159
+ - !ruby/object:Gem::Version
160
+ version: '0.4'
161
+ type: :development
162
+ prerelease: false
163
+ version_requirements: !ruby/object:Gem::Requirement
164
+ requirements:
165
+ - - "~>"
166
+ - !ruby/object:Gem::Version
167
+ version: '0.4'
168
+ - !ruby/object:Gem::Dependency
169
+ name: simplecov
170
+ requirement: !ruby/object:Gem::Requirement
171
+ requirements:
172
+ - - "~>"
173
+ - !ruby/object:Gem::Version
174
+ version: '0.21'
175
+ type: :development
176
+ prerelease: false
177
+ version_requirements: !ruby/object:Gem::Requirement
178
+ requirements:
179
+ - - "~>"
180
+ - !ruby/object:Gem::Version
181
+ version: '0.21'
182
+ description: Liberty is the state of being free from oppressive restrictions imposed
183
+ by authority.
184
+ email:
185
+ - liberty@firsttry.software
186
+ executables: []
187
+ extensions: []
188
+ extra_rdoc_files: []
189
+ files:
190
+ - ".rspec"
191
+ - ".standard.yml"
192
+ - CHANGELOG.md
193
+ - CODE_OF_CONDUCT.md
194
+ - Gemfile
195
+ - Gemfile.lock
196
+ - LICENSE.txt
197
+ - README.md
198
+ - Rakefile
199
+ - assets/liberty.png
200
+ - lib/liberty.rb
201
+ - lib/liberty/adapters/parsers/factory.rb
202
+ - lib/liberty/adapters/parsers/json.rb
203
+ - lib/liberty/adapters/parsers/null.rb
204
+ - lib/liberty/adapters/request.rb
205
+ - lib/liberty/adapters/response.rb
206
+ - lib/liberty/application.rb
207
+ - lib/liberty/cors.rb
208
+ - lib/liberty/cors/middleware.rb
209
+ - lib/liberty/endpoint.rb
210
+ - lib/liberty/router.rb
211
+ - lib/liberty/router/node.rb
212
+ - lib/liberty/router/printer.rb
213
+ - lib/liberty/router/trie.rb
214
+ - lib/liberty/version.rb
215
+ - liberty.gemspec
216
+ homepage: https://github.com/first-try-software/liberty
217
+ licenses:
218
+ - MIT
219
+ metadata:
220
+ homepage_uri: https://github.com/first-try-software/liberty
221
+ source_code_uri: https://github.com/first-try-software/liberty
222
+ changelog_uri: https://github.com/first-try-software/liberty/CHANGELOG.md
223
+ post_install_message:
224
+ rdoc_options: []
225
+ require_paths:
226
+ - lib
227
+ required_ruby_version: !ruby/object:Gem::Requirement
228
+ requirements:
229
+ - - ">="
230
+ - !ruby/object:Gem::Version
231
+ version: 3.1.0
232
+ required_rubygems_version: !ruby/object:Gem::Requirement
233
+ requirements:
234
+ - - ">="
235
+ - !ruby/object:Gem::Version
236
+ version: '0'
237
+ requirements: []
238
+ rubygems_version: 3.3.11
239
+ signing_key:
240
+ specification_version: 4
241
+ summary: A framework for Ruby web applications
242
+ test_files: []