bianchi 0.1.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
+ SHA256:
3
+ metadata.gz: 6fe9c6aabbf8e704a9ea9403896cc71c9aedf9a5f8bf5a5433469dba9e80d40b
4
+ data.tar.gz: 4caa2699c795f348136640d2300e636c8ce2848daf7605a0596749507034286a
5
+ SHA512:
6
+ metadata.gz: 3f56b2bf18384a755a4e6022b457e450c54efeb088926e112fca3b0ba6a7732a3762d83243a30572fd704c0131c816154e7cf4bbb3548fb489af5c0f11bdbec9
7
+ data.tar.gz: f763c36ef9616506fc87223383bb73487f0fc37901e8e14e99078970ad86c618b97f6b4602ef8140f95d182d23f62c23878fe72c68db9b84f3075ed3e5db8419
data/.gitignore ADDED
@@ -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
data/.rubocop.yml ADDED
@@ -0,0 +1,20 @@
1
+ AllCops:
2
+ NewCops: enable
3
+ TargetRubyVersion: 3.0
4
+
5
+ Style/StringLiterals:
6
+ Enabled: true
7
+ EnforcedStyle: double_quotes
8
+
9
+ Layout/LineLength:
10
+ Max: 120
11
+
12
+ Style/Documentation:
13
+ Enabled: false
14
+
15
+ Metrics/MethodLength:
16
+ CountAsOne: ['array', 'heredoc', 'hash']
17
+
18
+
19
+
20
+
@@ -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 51008616+SydDaps@users.noreply.github.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,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in bianchi.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+
12
+ gem "rubocop", "~> 0.80"
13
+
14
+ gem "byebug"
data/Gemfile.lock ADDED
@@ -0,0 +1,92 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ bianchi (0.1.0)
5
+ activesupport
6
+ json
7
+ redis
8
+ thor
9
+
10
+ GEM
11
+ remote: https://rubygems.org/
12
+ specs:
13
+ activesupport (7.1.3)
14
+ base64
15
+ bigdecimal
16
+ concurrent-ruby (~> 1.0, >= 1.0.2)
17
+ connection_pool (>= 2.2.5)
18
+ drb
19
+ i18n (>= 1.6, < 2)
20
+ minitest (>= 5.1)
21
+ mutex_m
22
+ tzinfo (~> 2.0)
23
+ ast (2.4.2)
24
+ base64 (0.2.0)
25
+ bigdecimal (3.1.6)
26
+ byebug (11.1.3)
27
+ concurrent-ruby (1.2.3)
28
+ connection_pool (2.4.1)
29
+ diff-lcs (1.5.0)
30
+ drb (2.2.0)
31
+ ruby2_keywords
32
+ i18n (1.14.1)
33
+ concurrent-ruby (~> 1.0)
34
+ json (2.7.1)
35
+ minitest (5.21.2)
36
+ mutex_m (0.2.0)
37
+ parallel (1.24.0)
38
+ parser (3.3.0.2)
39
+ ast (~> 2.4.1)
40
+ racc
41
+ racc (1.7.3)
42
+ rainbow (3.1.1)
43
+ rake (13.1.0)
44
+ redis (5.0.8)
45
+ redis-client (>= 0.17.0)
46
+ redis-client (0.19.1)
47
+ connection_pool
48
+ regexp_parser (2.9.0)
49
+ rexml (3.2.6)
50
+ rspec (3.12.0)
51
+ rspec-core (~> 3.12.0)
52
+ rspec-expectations (~> 3.12.0)
53
+ rspec-mocks (~> 3.12.0)
54
+ rspec-core (3.12.2)
55
+ rspec-support (~> 3.12.0)
56
+ rspec-expectations (3.12.3)
57
+ diff-lcs (>= 1.2.0, < 2.0)
58
+ rspec-support (~> 3.12.0)
59
+ rspec-mocks (3.12.6)
60
+ diff-lcs (>= 1.2.0, < 2.0)
61
+ rspec-support (~> 3.12.0)
62
+ rspec-support (3.12.1)
63
+ rubocop (0.93.1)
64
+ parallel (~> 1.10)
65
+ parser (>= 2.7.1.5)
66
+ rainbow (>= 2.2.2, < 4.0)
67
+ regexp_parser (>= 1.8)
68
+ rexml
69
+ rubocop-ast (>= 0.6.0)
70
+ ruby-progressbar (~> 1.7)
71
+ unicode-display_width (>= 1.4.0, < 2.0)
72
+ rubocop-ast (1.30.0)
73
+ parser (>= 3.2.1.0)
74
+ ruby-progressbar (1.13.0)
75
+ ruby2_keywords (0.0.5)
76
+ thor (1.3.0)
77
+ tzinfo (2.0.6)
78
+ concurrent-ruby (~> 1.0)
79
+ unicode-display_width (1.8.0)
80
+
81
+ PLATFORMS
82
+ x86_64-darwin-23
83
+
84
+ DEPENDENCIES
85
+ bianchi!
86
+ byebug
87
+ rake (~> 13.0)
88
+ rspec (~> 3.0)
89
+ rubocop (~> 0.80)
90
+
91
+ BUNDLED WITH
92
+ 2.2.3
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Dapilah Sydney
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,43 @@
1
+ # bianchi
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/bianchi`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'bianchi'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install bianchi
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ 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.
30
+
31
+ 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).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/bianchi. 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/[USERNAME]/bianchi/blob/master/CODE_OF_CONDUCT.md).
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
40
+
41
+ ## Code of Conduct
42
+
43
+ Everyone interacting in the bianchi project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/bianchi/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
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 "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/bianchi.gemspec ADDED
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/bianchi/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "bianchi"
7
+ spec.version = Bianchi::VERSION
8
+ spec.authors = ["Dapilah Sydney"]
9
+ spec.email = ['dapilah.sydney@gmail.com']
10
+
11
+ spec.summary = "Write a short summary, because RubyGems requires one."
12
+ spec.homepage = "https://github.com/SydDaps/Bianchi"
13
+ spec.license = "MIT"
14
+ spec.required_ruby_version = Gem::Requirement.new(">= 3.0.0")
15
+
16
+ spec.metadata["allowed_push_host"] = "https://rubygems.org/"
17
+
18
+ spec.metadata["homepage_uri"] = "https://github.com/SydDaps/Bianchi"
19
+ spec.metadata["source_code_uri"] = "https://github.com/SydDaps/Bianchi"
20
+ spec.metadata["changelog_uri"] = "https://rubygems.org/"
21
+
22
+ # Specify which files should be added to the gem when it is released.
23
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
24
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
25
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
26
+ end
27
+
28
+ spec.bindir = "exe"
29
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
30
+ spec.require_paths = ["lib"]
31
+
32
+ # Uncomment to register a new dependency of your gem
33
+ spec.add_dependency "activesupport"
34
+ spec.add_dependency "json"
35
+ spec.add_dependency "redis"
36
+ spec.add_dependency "thor"
37
+ end
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "bianchi"
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__)
data/bin/setup ADDED
@@ -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
data/exe/bianchi ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bianchi"
5
+
6
+ Bianchi::Cli::Main.start
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bianchi
4
+ module Cli
5
+ class Generator < Thor::Group
6
+ include Thor::Actions
7
+ desc "-g {menu_name}_menu_page_{page_number}", "Generates a menu page file in your current directory"
8
+
9
+ argument :menu_name_page_number
10
+
11
+ def version
12
+ say "Bianchi version #{Bianchi::VERSION}"
13
+ end
14
+
15
+ def self.exit_on_failure?
16
+ true
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ # rubocop:disable Metrics/ParameterLists
4
+ module Bianchi
5
+ module Cli
6
+ class Main < Thor
7
+ include Thor::Actions
8
+
9
+ desc "-v", "Show bianchi version number"
10
+ map %w[-v --version] => :version
11
+
12
+ def version
13
+ say "Bianchi version #{Bianchi::VERSION}"
14
+ end
15
+
16
+ def self.source_root
17
+ File.dirname(__FILE__)
18
+ end
19
+
20
+ desc "setup", "sets up a new ussd project"
21
+ long_desc <<-LONG_DESC
22
+ Usage: bianchi setup optional(-p|--provider)
23
+ \x5 Providers: [:africa_is_talking]
24
+ \x5 Example: `bianchi setup`
25
+ \x5 Example: `bianchi setup -p :africa_is_talking`
26
+
27
+ LONG_DESC
28
+ method_option :provider, :aliases => "-p", type: :string, :desc => "Set up ussd project for provider"
29
+ def setup
30
+ @provider = options[:provider]
31
+ unless ["africa_is_talking", "none"].include? @provider
32
+ say("Error: provider #{@provider} is not yet configured.", :yellow)
33
+ exit(1)
34
+ end
35
+
36
+ @provider = ", provider: :#{@provider}" if @provider
37
+
38
+ template("templates/engine.erb", "ussd/engine.rb")
39
+ end
40
+
41
+ desc "g", "Generates a menu page file"
42
+ long_desc <<-LONG_DESC
43
+ Usage: bianchi g|generate menu [name:string] page [number:int]
44
+ \x5 Example: `bianchi generate menu main page 1`
45
+ LONG_DESC
46
+
47
+ map %w[g generate] => :generate
48
+ def generate(entity = nil, entity_name = nil, type = nil, number = nil)
49
+ unless ["menu"].include?(entity) && entity_name.is_a?(String) && type == "page" && number.to_i.to_s == number
50
+ say("Usage: bianchi g|generate menu [name:string] page [number:int]", :yellow)
51
+ say("Example: bianchi generate menu main page 1")
52
+ exit(1)
53
+ end
54
+
55
+ @menu_name = entity_name
56
+ @page_number = number
57
+ template("templates/page.erb", "ussd/#{@menu_name}_menu/page_#{@page_number}.rb")
58
+ end
59
+
60
+ def self.exit_on_failure?
61
+ true
62
+ end
63
+ end
64
+ end
65
+ end
66
+ # rubocop:enable Metrics/ParameterLists
@@ -0,0 +1,10 @@
1
+ module USSD
2
+ class Engine
3
+ def self.start(params)
4
+
5
+ Bianchi::USSD::Engine.start(params<%= @provider %>) do
6
+ # e.g menu :main, options
7
+ end
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,11 @@
1
+ module USSD
2
+ module <%= @menu_name.camelize %>Menu
3
+ class Page<%= @page_number %> < Bianchi::USSD::Page
4
+ def request
5
+ end
6
+
7
+ def response
8
+ end
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,120 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bianchi
4
+ module USSD
5
+ class Engine
6
+ include USSD::ProviderConfigurations
7
+
8
+ attr_accessor :params, :session, :menus, :prompt_data, :provider
9
+
10
+ def initialize(params, options)
11
+ validate_engine_options(options)
12
+
13
+ @provider = options[:provider]&.to_sym || :none
14
+ @params = parse_params(params)
15
+ @session = Session.new @params
16
+ @menus = []
17
+ @prompt_data = nil
18
+ end
19
+
20
+ def self.start(params, options = {}, &block)
21
+ raise ArgumentError, "block required to start the engine" unless block_given?
22
+
23
+ new(params, options).tap do |e|
24
+ validate_params(e.params)
25
+ e.instance_eval(&block)
26
+ e.process_activity_state
27
+ end
28
+ end
29
+
30
+ def validate_engine_options(options)
31
+ raise ArgumentError, "options expected to be a hash to start engine" unless options.is_a? Hash
32
+ return if options.empty?
33
+
34
+ allowed_options = %i[provider]
35
+ return if (options.keys.map(&:to_sym) - allowed_options).empty?
36
+
37
+ raise ArgumentError, "#{allowed_options} are the only valid option keys"
38
+ end
39
+
40
+ def self.validate_params(params)
41
+ raise ArgumentError, "params expected to be a hash to start engine" unless params.is_a? Hash
42
+
43
+ required_params = %w[session_id mobile_number input_body activity_state]
44
+
45
+ left_required_params = required_params - params.keys.map(&:to_s)
46
+ unless left_required_params.empty?
47
+ raise ArgumentError, "#{left_required_params} required in params to start engine"
48
+ end
49
+
50
+ return if %w[initial subsequent].include? params[:activity_state]
51
+
52
+ raise ArgumentError, "activity_state has to either be initial or subsequent"
53
+ end
54
+
55
+ def menu(menu_name, options = {})
56
+ unless [String, Symbol].include? menu_name.class
57
+ raise ArgumentError, "menu_name expected to either be string/symbol to define menus"
58
+ end
59
+
60
+ raise ArgumentError, "menu_options expected to be a hash to start engine" unless options.is_a? Hash
61
+
62
+ @menus << Menu.new(menu_name, options)
63
+ end
64
+
65
+ def ensure_initial_menu
66
+ return if initial_menu
67
+
68
+ raise PageLoadError, "an initial menu is required to proceed"
69
+ end
70
+
71
+ def process_activity_state
72
+ ensure_initial_menu
73
+
74
+ page = case session.activity_state.to_sym
75
+ when :initial
76
+ initial_menu_page
77
+ when :subsequent
78
+ subsequent_menu_page
79
+ end
80
+
81
+ @prompt_data = parser_prompt_data page.session_prompt_data
82
+ end
83
+
84
+ def initial_menu_page
85
+ session.menu = initial_menu
86
+ menu_page("Page1", :request)
87
+ end
88
+
89
+ def initial_menu
90
+ menus.find { |menu| menu.options[:initial] }
91
+ end
92
+
93
+ def subsequent_menu_page
94
+ previous_session = session.store.previous_session
95
+ unless previous_session
96
+ raise PageLoadError, "Previous session not found to load subsequent page restart from initial menu"
97
+ end
98
+
99
+ session.menu = previous_session.menu
100
+
101
+ menu_page(previous_session.page_number, :response)
102
+ end
103
+
104
+ def menu_page(page_number, action)
105
+ constant_name = "USSD::#{session.menu.name.camelize}Menu::#{page_number}"
106
+ page = constant_name.safe_constantize
107
+
108
+ unless page
109
+ raise PageLoadError,
110
+ "#{constant_name} is supposed to be defined to process #{session.menu.name} menu #{page_number}"
111
+ end
112
+
113
+ page.new(session).tap do |p|
114
+ p.ensure_methods_defined(%i[request response])
115
+ p.send(action)
116
+ end
117
+ end
118
+ end
119
+ end
120
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bianchi
4
+ module USSD
5
+ class ArgumentError < StandardError; end
6
+ class PageLoadError < StandardError; end
7
+ class MethodNameError < StandardError; end
8
+ class ProviderError < StandardError; end
9
+ end
10
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bianchi
4
+ module USSD
5
+ class Menu
6
+ attr_reader :name, :options
7
+
8
+ def initialize(name, options = {})
9
+ @name = name.to_s
10
+ @options = options
11
+ end
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bianchi
4
+ module USSD
5
+ class Page
6
+ attr_reader :session
7
+
8
+ include USSD::PageDelegators
9
+
10
+ def initialize(session)
11
+ @session = session
12
+ end
13
+
14
+ def render(body, options = {})
15
+ raise ArgumentError, "render body expected to be a string" unless body.is_a? String
16
+
17
+ session.tap do |s|
18
+ s.prompt_data = s.params.merge(
19
+ { activity_state: options[:state], body: body }
20
+ )
21
+
22
+ s.page_number = self.class.name.split("::").last
23
+ s.store.track_session
24
+ end
25
+ end
26
+
27
+ def load_page(page_number, menu_name)
28
+ constant_name = "USSD::#{menu_name.camelize}Menu::#{page_number}"
29
+ page = constant_name.safe_constantize
30
+
31
+ unless page
32
+ raise PageLoadError,
33
+ "#{constant_name} is supposed to be defined to process #{menu_name} menu #{page_number}"
34
+ end
35
+
36
+ session.menu = Menu.new(menu_name)
37
+ page.new(session).send(:request)
38
+ end
39
+
40
+ def ensure_methods_defined(methods)
41
+ error_messages = methods.each_with_object([]) do |method, messages|
42
+ next if methods_defined? method
43
+
44
+ messages << "#{self.class.name} is supposed to have method #{method} defined"
45
+ end
46
+
47
+ return if error_messages.empty?
48
+
49
+ raise PageLoadError, error_messages.join(", ")
50
+ end
51
+
52
+ def methods_defined?(method)
53
+ respond_to? method
54
+ end
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,102 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bianchi
4
+ module USSD
5
+ module PageDelegators
6
+ def method_missing(method_name, *args)
7
+ name = method_name.to_s
8
+
9
+ allowed_dynamic_methods_prefix_delegator = {
10
+ "redirect_to_" => proc { delegate_redirected_to(name) },
11
+ "render_and_" => proc { delegate_render_and(name, args) },
12
+ "session_" => proc { delegate_session(name) }
13
+ }
14
+
15
+ dynamic_method = allowed_dynamic_methods_prefix_delegator.find do |key, _value|
16
+ name.start_with? key
17
+ end
18
+
19
+ return super unless dynamic_method.present?
20
+
21
+ dynamic_method.second.call
22
+ end
23
+
24
+ # redirect delegators
25
+ def delegate_redirected_to(name)
26
+ name.delete_prefix!("redirect_to_")
27
+ page, menu_name = handle_redirect_to_cases(name)
28
+ load_page(page, menu_name)
29
+ end
30
+
31
+ def handle_redirect_to_cases(name)
32
+ redirect_to_method_names = [
33
+ "next_page",
34
+ "previous_page",
35
+ "(menu_name)_menu_page_(number)"
36
+ ]
37
+
38
+ case name
39
+ when /(next|previous)_page/
40
+ to_next_or_previous_page Regexp.last_match(1)
41
+ when /(.+)_menu_page_(\d+)/
42
+ to_menu_page(Regexp.last_match(1), Regexp.last_match(2).to_i)
43
+ else
44
+ error_message = redirect_to_method_names.map { |method_name| "redirect_to_#{method_name}" }.join(", ")
45
+ raise MethodNameError, "do you mean [#{error_message}]"
46
+ end
47
+ end
48
+
49
+ def to_next_or_previous_page(keyword)
50
+ page = self.class.name.split("::").last
51
+
52
+ next_page_number = keyword == "next" ? (page[-1].to_i + 1) : (page[-1].to_i - 1)
53
+
54
+ raise PageLoadError, "can not redirect to previous page from page 1" if next_page_number < 1
55
+
56
+ [page_number(page, next_page_number), session.menu.name]
57
+ end
58
+
59
+ def page_number(page, next_page_number)
60
+ page.length == 4 ? page << next_page_number.to_s : page[-1] = next_page_number.to_s
61
+
62
+ page
63
+ end
64
+
65
+ def to_menu_page(menu_name, page_number)
66
+ page = "Page#{page_number}"
67
+
68
+ [page, menu_name]
69
+ end
70
+
71
+ # render delegators
72
+ def delegate_render_and(name, args)
73
+ name.delete_prefix!("render_and_")
74
+
75
+ states = {
76
+ "await" => :await,
77
+ "end" => :end
78
+ }
79
+
80
+ unless states.keys.include? name
81
+ raise MethodNameError, "do you mean [#{states.keys.map { |state| "render_and_#{state}" }.join(', ')}]"
82
+ end
83
+
84
+ render args.first, state: states[name]
85
+ end
86
+
87
+ # session_delegators
88
+ def delegate_session(name)
89
+ name.delete_prefix!("session_")
90
+
91
+ allowed_session_instance_names = session.instance_variables.map { |variable| variable.to_s.delete_prefix("@") }
92
+
93
+ unless allowed_session_instance_names.include? name
94
+ error_message = allowed_session_instance_names.map { |method_name| "session_#{method_name}" }.join(", ")
95
+ raise MethodNameError, "do you mean [#{error_message}]"
96
+ end
97
+
98
+ session.send(name)
99
+ end
100
+ end
101
+ end
102
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bianchi
4
+ module USSD
5
+ module ProviderConfigurations
6
+ def parse_params(params)
7
+ provider_parsers = {
8
+ none: proc { params },
9
+ africa_is_talking: proc { africa_is_talking_params_parser(params) }
10
+ }.with_indifferent_access
11
+
12
+ parser = provider_parsers[@provider]
13
+
14
+ raise ProviderError, "Could not find configurations for provider(#{@provider}) specified" unless parser.present?
15
+
16
+ parser.call
17
+ end
18
+
19
+ def africa_is_talking_params_parser(params)
20
+ required_params = %w[sessionId phoneNumber text serviceCode]
21
+ left_required_params = required_params - params.keys.map(&:to_s)
22
+
23
+ unless left_required_params.empty?
24
+ raise ArgumentError, "#{left_required_params} required in params to start engine for provider #{@provider}"
25
+ end
26
+
27
+ {
28
+ session_id: params["sessionId"],
29
+ mobile_number: params["phoneNumber"],
30
+ activity_state: params["text"] && params["text"].empty? ? "initial" : "subsequent",
31
+ input_body: params["text"],
32
+ service_code: params["serviceCode"]
33
+ }
34
+ end
35
+
36
+ def parser_prompt_data(prompt_data)
37
+ provider_parsers = {
38
+ none: proc { prompt_data },
39
+ africa_is_talking: proc { africa_is_talking_prompt_data_parser(prompt_data) }
40
+ }.with_indifferent_access
41
+
42
+ parser = provider_parsers[@provider]
43
+
44
+ raise StandardError, "could not parse response data for the provider specified." unless parser.present?
45
+
46
+ parser.call
47
+ end
48
+
49
+ def africa_is_talking_prompt_data_parser(prompt_data)
50
+ prompt_data["activity_state"] == :await ? "CON #{prompt_data['body']}" : "END #{prompt_data['body']}"
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bianchi
4
+ module USSD
5
+ class Session
6
+ attr_accessor :params, :activity_state, :prompt_data,
7
+ :menu, :page_number, :store,
8
+ :id, :mobile_number, :input_body
9
+
10
+ def initialize(params, menu = nil, page_number = nil)
11
+ @params = params.with_indifferent_access
12
+ @activity_state = params[:activity_state]
13
+ @mobile_number = params[:mobile_number]
14
+ @id = params[:session_id]
15
+ @input_body = params[:input_body]
16
+ @prompt_data = {}
17
+ @menu = menu
18
+ @page_number = page_number
19
+ @store = Store.new(self)
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bianchi
4
+ module USSD
5
+ class Store
6
+ attr_reader :session
7
+
8
+ def initialize(session)
9
+ @redis = Redis.new(url: ENV.fetch("REDIS_URL", nil))
10
+ @session = session
11
+ end
12
+
13
+ def track_session
14
+ data = {
15
+ params: session.params,
16
+ menu: session.menu.name,
17
+ page_number: session.page_number
18
+ }.to_json
19
+
20
+ @redis.hset("#{session.id}-#{session.mobile_number}-activity", data: data)
21
+ end
22
+
23
+ def previous_session
24
+ previous_activity = @redis.hgetall("#{session.id}-#{session.mobile_number}-activity")
25
+ return if previous_activity.empty?
26
+
27
+ previous_activity_data = JSON.parse(previous_activity["data"]).with_indifferent_access
28
+
29
+ menu = Menu.new(previous_activity_data[:menu])
30
+ page_number = previous_activity_data[:page_number]
31
+ params = previous_activity_data[:params]
32
+ Session.new(params, menu, page_number)
33
+ end
34
+
35
+ def get(key)
36
+ parse_value @redis.hget("#{session.id}-#{session.mobile_number}-store", key)
37
+ end
38
+
39
+ def all
40
+ parse_values @redis.hgetall("#{session.id}-#{session.mobile_number}-store")
41
+ end
42
+
43
+ def set(key, value)
44
+ @redis.hset("#{session.id}-#{session.mobile_number}-store", { key => value.to_json })
45
+ end
46
+
47
+ def parse_values(data)
48
+ data.transform_values { |v| parse_value v }
49
+ end
50
+
51
+ def parse_value(value)
52
+ JSON.parse(value)
53
+ rescue StandardError
54
+ value
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bianchi
4
+ VERSION = "0.1.0"
5
+ end
data/lib/bianchi.rb ADDED
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/all"
4
+ require "redis"
5
+ require "json"
6
+ require "thor"
7
+
8
+ require_relative "bianchi/version"
9
+ require_relative "bianchi/ussd/provider_configurations"
10
+ require_relative "bianchi/ussd/engine"
11
+ require_relative "bianchi/ussd/menu"
12
+ require_relative "bianchi/ussd/session"
13
+ require_relative "bianchi/ussd/page_delegators"
14
+ require_relative "bianchi/ussd/page"
15
+ require_relative "bianchi/ussd/store"
16
+ require_relative "bianchi/ussd/errors"
17
+
18
+ # cli
19
+ require "bianchi/cli/main"
data/ussd/engine.rb ADDED
@@ -0,0 +1,10 @@
1
+ module USSD
2
+ class Engine
3
+ def self.start(params)
4
+
5
+ Bianchi::USSD::Engine.start(params, provider: :africa_is_talking) do
6
+ # e.g menu :main, options
7
+ end
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,11 @@
1
+ module USSD
2
+ module MainMenu
3
+ class Page1 < Bianchi::USSD::Page
4
+ def request
5
+ end
6
+
7
+ def response
8
+ end
9
+ end
10
+ end
11
+ end
metadata ADDED
@@ -0,0 +1,133 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: bianchi
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Dapilah Sydney
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-01-25 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: json
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: redis
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: thor
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ description:
70
+ email:
71
+ - dapilah.sydney@gmail.com
72
+ executables:
73
+ - bianchi
74
+ extensions: []
75
+ extra_rdoc_files: []
76
+ files:
77
+ - ".gitignore"
78
+ - ".rspec"
79
+ - ".rubocop.yml"
80
+ - CODE_OF_CONDUCT.md
81
+ - Gemfile
82
+ - Gemfile.lock
83
+ - LICENSE.txt
84
+ - README.md
85
+ - Rakefile
86
+ - bianchi.gemspec
87
+ - bin/console
88
+ - bin/setup
89
+ - exe/bianchi
90
+ - lib/bianchi.rb
91
+ - lib/bianchi/cli/generator.rb
92
+ - lib/bianchi/cli/main.rb
93
+ - lib/bianchi/cli/templates/engine.erb
94
+ - lib/bianchi/cli/templates/page.erb
95
+ - lib/bianchi/ussd/engine.rb
96
+ - lib/bianchi/ussd/errors.rb
97
+ - lib/bianchi/ussd/menu.rb
98
+ - lib/bianchi/ussd/page.rb
99
+ - lib/bianchi/ussd/page_delegators.rb
100
+ - lib/bianchi/ussd/provider_configurations.rb
101
+ - lib/bianchi/ussd/session.rb
102
+ - lib/bianchi/ussd/store.rb
103
+ - lib/bianchi/version.rb
104
+ - ussd/engine.rb
105
+ - ussd/main_menu/page_1.rb
106
+ homepage: https://github.com/SydDaps/Bianchi
107
+ licenses:
108
+ - MIT
109
+ metadata:
110
+ allowed_push_host: https://rubygems.org/
111
+ homepage_uri: https://github.com/SydDaps/Bianchi
112
+ source_code_uri: https://github.com/SydDaps/Bianchi
113
+ changelog_uri: https://rubygems.org/
114
+ post_install_message:
115
+ rdoc_options: []
116
+ require_paths:
117
+ - lib
118
+ required_ruby_version: !ruby/object:Gem::Requirement
119
+ requirements:
120
+ - - ">="
121
+ - !ruby/object:Gem::Version
122
+ version: 3.0.0
123
+ required_rubygems_version: !ruby/object:Gem::Requirement
124
+ requirements:
125
+ - - ">="
126
+ - !ruby/object:Gem::Version
127
+ version: '0'
128
+ requirements: []
129
+ rubygems_version: 3.2.3
130
+ signing_key:
131
+ specification_version: 4
132
+ summary: Write a short summary, because RubyGems requires one.
133
+ test_files: []