case_register 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,29 @@
1
+ sudo: false
2
+ env:
3
+ global:
4
+ - CC_TEST_REPORTER_ID=2f9bf253ef3487d24d1028eaee27bb105be5c5c31815749606612522a4ff1647
5
+ language: ruby
6
+ rvm:
7
+ - 2.2
8
+ - 2.6
9
+ - 2.7
10
+ gemfile:
11
+ - gemfiles/Gemfile
12
+ matrix:
13
+ include:
14
+ - dist: trusty
15
+ rvm: 1.8.7
16
+ gemfile: gemfiles/ruby_1_8_7.gemfile
17
+ before_install:
18
+ - if `ruby -e 'exit(RUBY_VERSION.to_f < 2.7)'`; then
19
+ gem i rubygems-update -v '< 3' && update_rubygems;
20
+ gem install bundler -v '< 2';
21
+ fi
22
+ - gem --version
23
+ - curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
24
+ - chmod +x ./cc-test-reporter
25
+ - ./cc-test-reporter before-build
26
+ script:
27
+ - bundle exec rake test
28
+ after_script:
29
+ - ./cc-test-reporter after-build --exit-code $TRAVIS_TEST_RESULT
@@ -0,0 +1 @@
1
+ ## Change Log
@@ -0,0 +1,49 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, and in the interest of
4
+ fostering an open and welcoming community, we pledge to respect all people who
5
+ contribute through reporting issues, posting feature requests, updating
6
+ documentation, submitting pull requests or patches, and other activities.
7
+
8
+ We are committed to making participation in this project a harassment-free
9
+ experience for everyone, regardless of level of experience, gender, gender
10
+ identity and expression, sexual orientation, disability, personal appearance,
11
+ body size, race, ethnicity, age, religion, or nationality.
12
+
13
+ Examples of unacceptable behavior by participants include:
14
+
15
+ * The use of sexualized language or imagery
16
+ * Personal attacks
17
+ * Trolling or insulting/derogatory comments
18
+ * Public or private harassment
19
+ * Publishing other's private information, such as physical or electronic
20
+ addresses, without explicit permission
21
+ * Other unethical or unprofessional conduct
22
+
23
+ Project maintainers have the right and responsibility to remove, edit, or
24
+ reject comments, commits, code, wiki edits, issues, and other contributions
25
+ that are not aligned to this Code of Conduct, or to ban temporarily or
26
+ permanently any contributor for other behaviors that they deem inappropriate,
27
+ threatening, offensive, or harmful.
28
+
29
+ By adopting this Code of Conduct, project maintainers commit themselves to
30
+ fairly and consistently applying these principles to every aspect of managing
31
+ this project. Project maintainers who do not follow or enforce the Code of
32
+ Conduct may be permanently removed from the project team.
33
+
34
+ This code of conduct applies both within project spaces and in public spaces
35
+ when an individual is representing the project or its community.
36
+
37
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
38
+ reported by contacting a project maintainer at mrtmrt15xn@yahoo.com.tw. All
39
+ complaints will be reviewed and investigated and will result in a response that
40
+ is deemed necessary and appropriate to the circumstances. Maintainers are
41
+ obligated to maintain confidentiality with regard to the reporter of an
42
+ incident.
43
+
44
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
45
+ version 1.3.0, available at
46
+ [http://contributor-covenant.org/version/1/3/0/][version]
47
+
48
+ [homepage]: http://contributor-covenant.org
49
+ [version]: http://contributor-covenant.org/version/1/3/0/
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Rumble Huang
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 all
13
+ 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 THE
21
+ SOFTWARE.
@@ -0,0 +1,171 @@
1
+ # CaseRegister
2
+
3
+ [![Gem Version](https://img.shields.io/gem/v/case_register.svg?style=flat)](http://rubygems.org/gems/case_register)
4
+ [![Build Status](https://travis-ci.com/khiav223577/case_register.svg?branch=master)](https://travis-ci.org/khiav223577/case_register)
5
+ [![RubyGems](http://img.shields.io/gem/dt/case_register.svg?style=flat)](http://rubygems.org/gems/case_register)
6
+ [![Code Climate](https://codeclimate.com/github/khiav223577/case_register/badges/gpa.svg)](https://codeclimate.com/github/khiav223577/case_register)
7
+ [![Test Coverage](https://codeclimate.com/github/khiav223577/case_register/badges/coverage.svg)](https://codeclimate.com/github/khiav223577/case_register/coverage)
8
+
9
+ ## Supports
10
+ - Ruby 1.8 ~ 2.7
11
+
12
+ ## Installation
13
+
14
+ ```ruby
15
+ gem 'case_register'
16
+ ```
17
+
18
+ And then execute:
19
+
20
+ $ bundle
21
+
22
+ Or install it yourself as:
23
+
24
+ $ gem install case_register
25
+
26
+ ## Usage
27
+
28
+ ### Refactor case statements
29
+
30
+ Take the examples from this [article](http://bobnadler.com/articles/2010/08/02/refactoring-case-statements-in-ruby.html). Let you have a method like this:
31
+
32
+ ```rb
33
+ def output(data, format)
34
+ case format
35
+ when :html
36
+ return "<p>#{data}</p>"
37
+ when :text
38
+ return data
39
+ when :pdf
40
+ return "<pdf>#{data}</pdf>" # pseudocode -- obviously not valid PDF output
41
+ else
42
+ raise ArgumentError, "Invalid format (#{format})."
43
+ end
44
+ end
45
+
46
+ output('Hi', :html)
47
+ # => "<p>Hi</p>"
48
+ ```
49
+
50
+ You can refactor it by using a hash table to map the input, like what the article says.
51
+
52
+ Or use `CaseRegister` to register cases. Then, you are able to invoke the case directly without using switch-statements.
53
+ ```rb
54
+ class MyFormatter
55
+ include CaseRegister
56
+
57
+ def initialize(text)
58
+ @text = text
59
+ end
60
+
61
+ register_case(:pdf){ "<pdf>#{@text}</pdf>" }
62
+ register_case(:text){ @text }
63
+ register_case(:html){ "<p>#{@text}</p>" }
64
+ end
65
+
66
+ MyFormatter.new('Hi').invoke_case(:html)
67
+ # => "<p>Hi</p>"
68
+ ```
69
+
70
+ ### Isolate methods
71
+
72
+ Let you have an api that allow the frontend to pass params to determetine which information it wants.
73
+
74
+ Since you have to use `send` to call the methods in user model dynamically, it will cause security issues if you do not use a whitelist to limit the methods it can access.
75
+
76
+ ```rb
77
+ class User < ApplicationRecord
78
+ def money_info
79
+ { value: money, rate: gain_money_rate }
80
+ end
81
+
82
+ def notification_info
83
+ { msg_count: new_msgs_count, last_recieved_at: last_recieved_at }
84
+ end
85
+ end
86
+
87
+ class UserController
88
+ METHOD_WHITE_LIST = [:money_info, :notification_info]
89
+
90
+ def refresh
91
+ result = params[:needs].slice(METHOD_WHITE_LIST).index_with{|method| current_user.send(method) }
92
+ render json: result
93
+ end
94
+ end
95
+ ```
96
+
97
+ You may use if-statements or switch-statments to map the input to the desired method. But you will find you repeat writing similiar things and it seems redundant.
98
+
99
+ ```rb
100
+ class UserController
101
+ def refresh
102
+ result = {}
103
+ result[:money_info] = current_user.money_info if params[:needs][:money_info]
104
+ result[:notification_info] = current_user.notification_info if params[:needs][:notification_info]
105
+ # ...
106
+
107
+ render json: result
108
+ end
109
+ end
110
+ ```
111
+
112
+ In this case, you can use `CaseRegister` to DRYing up and isolate the methods to prevent unsafely calling `send`, which can access all the methods defined in the model.
113
+
114
+ ```rb
115
+ class RefreshHelper
116
+ include CaseRegister
117
+
118
+ def initialize(user)
119
+ @user = user
120
+ end
121
+
122
+ register_case 'money_info' do
123
+ { value: @user.money, rate: @user.gain_money_rate }
124
+ end
125
+
126
+ register_case 'notification_info' do
127
+ { msg_count: @user.new_msgs_count, last_recieved_at: @user.last_recieved_at }
128
+ end
129
+ end
130
+
131
+ class UserController
132
+ def refresh
133
+ helper = RefreshHelper.new(current_user)
134
+ result = params[:needs].index_with{|need| helper.invoke_case(need) }
135
+ render json: result
136
+ end
137
+ end
138
+ ```
139
+
140
+ ### Check if a case is registered
141
+
142
+ Something, you may want to check if a case is valid or not, and return error message if not.
143
+
144
+ It can be accomplish by using `may_invoke_case?` method. See the following example:
145
+
146
+ ```rb
147
+ class UserController
148
+ def refresh
149
+ helper = RefreshHelper.new(current_user)
150
+ invalid_needs = params[:needs].select{|need| !helper.may_invoke_case?(need) }
151
+ return render json: { invalid_needs: invalid_needs } if invalid_needs.any?
152
+ # ...
153
+ end
154
+ end
155
+ ```
156
+
157
+ ## Development
158
+
159
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
160
+
161
+ 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).
162
+
163
+ ## Contributing
164
+
165
+ Bug reports and pull requests are welcome on GitHub at https://github.com/khiav223577/case_register. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
166
+
167
+
168
+ ## License
169
+
170
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
171
+
@@ -0,0 +1,10 @@
1
+ require 'bundler/gem_tasks'
2
+ require 'rake/testtask'
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << 'test'
6
+ t.libs << 'lib'
7
+ t.test_files = FileList['test/**/*_test.rb']
8
+ end
9
+
10
+ task :default => :test
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'bundler/setup'
4
+ require 'case_register'
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
12
+
13
+ require 'irb'
14
+ IRB.start
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install --gemfile=gemfiles/4.2.gemfile
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,40 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'case_register/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'case_register'
8
+ spec.version = CaseRegister::VERSION
9
+ spec.authors = ['khiav reoy']
10
+ spec.email = ['mrtmrt15xn@yahoo.com.tw']
11
+
12
+ spec.summary = 'Provide a design pattern to manage large switch statements by mapping it to methods.'
13
+ spec.description = 'Provide a design pattern to manage large switch statements by mapping it to methods.'
14
+ spec.homepage = 'https://github.com/khiav223577/case_register'
15
+ spec.license = 'MIT'
16
+
17
+ # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
18
+ # delete this section to allow pushing this gem to any host.
19
+ # if spec.respond_to?(:metadata)
20
+ # spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
21
+ # else
22
+ # raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
23
+ # end
24
+
25
+ spec.files = `git ls-files -z`.split("\x0").reject{|f| f.match(%r{^(test|spec|features)/}) }
26
+ spec.bindir = 'exe'
27
+ spec.executables = spec.files.grep(%r{^exe/}){|f| File.basename(f) }
28
+ spec.require_paths = ['lib']
29
+ spec.metadata = {
30
+ 'homepage_uri' => 'https://github.com/khiav223577/case_register',
31
+ 'changelog_uri' => 'https://github.com/khiav223577/case_register/blob/master/CHANGELOG.md',
32
+ 'source_code_uri' => 'https://github.com/khiav223577/case_register',
33
+ 'documentation_uri' => 'https://www.rubydoc.info/gems/case_register',
34
+ 'bug_tracker_uri' => 'https://github.com/khiav223577/case_register/issues',
35
+ }
36
+
37
+ spec.add_development_dependency 'bundler', '>= 1.17', '< 3.x'
38
+ spec.add_development_dependency 'rake', '>= 10.5.0'
39
+ spec.add_development_dependency 'minitest', '~> 5.0'
40
+ end
@@ -0,0 +1,9 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in rails_or.gemspec
4
+
5
+ group :test do
6
+ gem 'simplecov'
7
+ end
8
+
9
+ gemspec :path => '../'
@@ -0,0 +1,10 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in rails_or.gemspec
4
+
5
+ group :test do
6
+ gem 'simplecov'
7
+ gem 'minitest', '~> 5.11.3'
8
+ end
9
+
10
+ gemspec :path => '../'
@@ -0,0 +1,43 @@
1
+ require 'case_register/version'
2
+
3
+ module CaseRegister
4
+ def self.included(klass)
5
+ type_hash = {}
6
+ type_counter = 0
7
+
8
+ get_method_name = proc do |type|
9
+ next nil if type_hash == nil
10
+ next type_hash[type]
11
+ end
12
+
13
+ gen_method_name = proc do |type|
14
+ id = type_counter += 1
15
+ next (type_hash[type] = :"case_register_auto_method_name#{id}")
16
+ end
17
+
18
+ klass.extend(
19
+ Module.new do
20
+ define_method(:case_register_get_method_name){|type| get_method_name[type] }
21
+ define_method(:case_register_gen_method_name){|type| gen_method_name[type] }
22
+
23
+ def register_case(type, &block)
24
+ method_name = case_register_gen_method_name(type)
25
+ define_method(method_name, &block)
26
+ private(method_name)
27
+ return method_name
28
+ end
29
+ end
30
+ )
31
+ end
32
+
33
+ def invoke_case(type, *args)
34
+ method_name = self.class.case_register_get_method_name(type)
35
+
36
+ fail "Undefined case `#{type}` for #{self.class}" if method_name == nil
37
+ return send(method_name, *args)
38
+ end
39
+
40
+ def may_invoke_case?(type)
41
+ self.class.case_register_get_method_name(type) != nil
42
+ end
43
+ end
@@ -0,0 +1,3 @@
1
+ module CaseRegister
2
+ VERSION = '0.0.1'
3
+ end
metadata ADDED
@@ -0,0 +1,113 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: case_register
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - khiav reoy
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-09-09 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.17'
20
+ - - "<"
21
+ - !ruby/object:Gem::Version
22
+ version: 3.x
23
+ type: :development
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - ">="
28
+ - !ruby/object:Gem::Version
29
+ version: '1.17'
30
+ - - "<"
31
+ - !ruby/object:Gem::Version
32
+ version: 3.x
33
+ - !ruby/object:Gem::Dependency
34
+ name: rake
35
+ requirement: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: 10.5.0
40
+ type: :development
41
+ prerelease: false
42
+ version_requirements: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: 10.5.0
47
+ - !ruby/object:Gem::Dependency
48
+ name: minitest
49
+ requirement: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - "~>"
52
+ - !ruby/object:Gem::Version
53
+ version: '5.0'
54
+ type: :development
55
+ prerelease: false
56
+ version_requirements: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - "~>"
59
+ - !ruby/object:Gem::Version
60
+ version: '5.0'
61
+ description: Provide a design pattern to manage large switch statements by mapping
62
+ it to methods.
63
+ email:
64
+ - mrtmrt15xn@yahoo.com.tw
65
+ executables: []
66
+ extensions: []
67
+ extra_rdoc_files: []
68
+ files:
69
+ - ".gitignore"
70
+ - ".rubocop.yml"
71
+ - ".travis.yml"
72
+ - CHANGELOG.md
73
+ - CODE_OF_CONDUCT.md
74
+ - LICENSE
75
+ - README.md
76
+ - Rakefile
77
+ - bin/console
78
+ - bin/setup
79
+ - case_register.gemspec
80
+ - gemfiles/Gemfile
81
+ - gemfiles/ruby_1_8_7.gemfile
82
+ - lib/case_register.rb
83
+ - lib/case_register/version.rb
84
+ homepage: https://github.com/khiav223577/case_register
85
+ licenses:
86
+ - MIT
87
+ metadata:
88
+ homepage_uri: https://github.com/khiav223577/case_register
89
+ changelog_uri: https://github.com/khiav223577/case_register/blob/master/CHANGELOG.md
90
+ source_code_uri: https://github.com/khiav223577/case_register
91
+ documentation_uri: https://www.rubydoc.info/gems/case_register
92
+ bug_tracker_uri: https://github.com/khiav223577/case_register/issues
93
+ post_install_message:
94
+ rdoc_options: []
95
+ require_paths:
96
+ - lib
97
+ required_ruby_version: !ruby/object:Gem::Requirement
98
+ requirements:
99
+ - - ">="
100
+ - !ruby/object:Gem::Version
101
+ version: '0'
102
+ required_rubygems_version: !ruby/object:Gem::Requirement
103
+ requirements:
104
+ - - ">="
105
+ - !ruby/object:Gem::Version
106
+ version: '0'
107
+ requirements: []
108
+ rubygems_version: 3.0.3
109
+ signing_key:
110
+ specification_version: 4
111
+ summary: Provide a design pattern to manage large switch statements by mapping it
112
+ to methods.
113
+ test_files: []