tamashii-common 0.1.2

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
+ SHA1:
3
+ metadata.gz: 42c6412b9b89caad362873fbe9d00502752d9bc5
4
+ data.tar.gz: ad23a587e0eaeb5317b355343c4e090ac7d5e026
5
+ SHA512:
6
+ metadata.gz: 37166b5b562dcebbea26154bd8d9452bcf222442e4a6b2062cd7292480bea0e8e4e665fe5523178cb13e67fa0840ac3d8f79beb354f4f26d90949719794b6058
7
+ data.tar.gz: 5707c506cdac9800499300687250819dd6a59dd1f8028868b7ff33b37f85f56ca8c2a4f7caee45ea86742d5e9d49b87ef6008290cc4b0713ea79df294c27d832
data/.gitignore ADDED
@@ -0,0 +1,15 @@
1
+ # Vim related
2
+ /.bundle/
3
+ *.swp
4
+ /.yardoc
5
+ *.swo
6
+ /Gemfile.lock
7
+
8
+ /_yardoc/
9
+ .byebug_history
10
+ /coverage/
11
+ .ruby-version
12
+ /doc/
13
+ /pkg/
14
+ /spec/reports/
15
+ /tmp/
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.3.1
5
+ before_install: gem install bundler -v 1.13.6
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in tamashii-common.gemspec
4
+ gemspec
data/Guardfile ADDED
@@ -0,0 +1,70 @@
1
+ # A sample Guardfile
2
+ # More info at https://github.com/guard/guard#readme
3
+
4
+ ## Uncomment and set this to only include directories you want to watch
5
+ # directories %w(app lib config test spec features) \
6
+ # .select{|d| Dir.exists?(d) ? d : UI.warning("Directory #{d} does not exist")}
7
+
8
+ ## Note: if you are using the `directories` clause above and you are not
9
+ ## watching the project directory ('.'), then you will want to move
10
+ ## the Guardfile to a watched dir and symlink it back, e.g.
11
+ #
12
+ # $ mkdir config
13
+ # $ mv Guardfile config/
14
+ # $ ln -s config/Guardfile .
15
+ #
16
+ # and, you'll have to watch "config/Guardfile" instead of "Guardfile"
17
+
18
+ # Note: The cmd option is now required due to the increasing number of ways
19
+ # rspec may be run, below are examples of the most common uses.
20
+ # * bundler: 'bundle exec rspec'
21
+ # * bundler binstubs: 'bin/rspec'
22
+ # * spring: 'bin/rspec' (This will use spring if running and you have
23
+ # installed the spring binstubs per the docs)
24
+ # * zeus: 'zeus rspec' (requires the server to be started separately)
25
+ # * 'just' rspec: 'rspec'
26
+
27
+ guard :rspec, cmd: "bundle exec rspec" do
28
+ require "guard/rspec/dsl"
29
+ dsl = Guard::RSpec::Dsl.new(self)
30
+
31
+ # Feel free to open issues for suggestions and improvements
32
+
33
+ # RSpec files
34
+ rspec = dsl.rspec
35
+ watch(rspec.spec_helper) { rspec.spec_dir }
36
+ watch(rspec.spec_support) { rspec.spec_dir }
37
+ watch(rspec.spec_files)
38
+
39
+ # Ruby files
40
+ ruby = dsl.ruby
41
+ dsl.watch_spec_files_for(ruby.lib_files)
42
+
43
+ # Rails files
44
+ rails = dsl.rails(view_extensions: %w(erb haml slim))
45
+ dsl.watch_spec_files_for(rails.app_files)
46
+ dsl.watch_spec_files_for(rails.views)
47
+
48
+ watch(rails.controllers) do |m|
49
+ [
50
+ rspec.spec.call("routing/#{m[1]}_routing"),
51
+ rspec.spec.call("controllers/#{m[1]}_controller"),
52
+ rspec.spec.call("acceptance/#{m[1]}")
53
+ ]
54
+ end
55
+
56
+ # Rails config changes
57
+ watch(rails.spec_helper) { rspec.spec_dir }
58
+ watch(rails.routes) { "#{rspec.spec_dir}/routing" }
59
+ watch(rails.app_controller) { "#{rspec.spec_dir}/controllers" }
60
+
61
+ # Capybara features specs
62
+ watch(rails.view_dirs) { |m| rspec.spec.call("features/#{m[1]}") }
63
+ watch(rails.layouts) { |m| rspec.spec.call("features/#{m[1]}") }
64
+
65
+ # Turnip features and steps
66
+ watch(%r{^spec/acceptance/(.+)\.feature$})
67
+ watch(%r{^spec/acceptance/steps/(.+)_steps\.rb$}) do |m|
68
+ Dir[File.join("**/#{m[1]}.feature")][0] || "spec/acceptance"
69
+ end
70
+ end
data/LICENSE.md ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,38 @@
1
+ # Tamashii::Common
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/tamashii/common`. 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 'tamashii-common'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install tamashii-common
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 tags, 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/lctseng/tamashii-common.
36
+
37
+ Contributed by [5xruby Inc.](https://5xruby.tw/)
38
+
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "tamashii/common"
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
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
@@ -0,0 +1,5 @@
1
+ module Tamashii
2
+ module Common
3
+ VERSION = "0.1.2"
4
+ end
5
+ end
@@ -0,0 +1,14 @@
1
+ require "tamashii/common/version"
2
+ require "tamashii/packet"
3
+ require "tamashii/type"
4
+ require "tamashii/handler"
5
+ require "tamashii/hook"
6
+ require "tamashii/resolver"
7
+ require "tamashii/logger"
8
+ require "tamashii/config"
9
+ require "tamashii/environment"
10
+
11
+ module Tamashii
12
+ module Common
13
+ end
14
+ end
@@ -0,0 +1,55 @@
1
+ require "tamashii/environment"
2
+
3
+ module Tamashii
4
+ class Config < Hash
5
+ SHARED_CONFIG = %i(auth_type token log_file log_level token env).freeze
6
+
7
+ class << self
8
+ attr_accessor :default_config
9
+
10
+ def method_missing(name, *args, &block)
11
+ (@instance ||= self.new).send(name, *args, &block)
12
+ end
13
+
14
+ def register(name, default = nil)
15
+ self.default_config ||= {}
16
+ self.default_config[name.to_sym] = default
17
+ end
18
+
19
+ def [](name)
20
+ send(name.to_sym)
21
+ end
22
+ end
23
+
24
+ def initialize
25
+ @accept_config = Set.new(SHARED_CONFIG)
26
+ (self.class.default_config || {}).each { |name, value| register(name, value) }
27
+ end
28
+
29
+ def method_missing(name, *args, &block)
30
+ return unless accept?(name) || accept?(name[0..-2])
31
+ return register(name[0..-2], args.first) if name[-1..-1] == "="
32
+ return register(name, args.first) if args.size > 0
33
+ return register(name, yield(self)) if block_given?
34
+ self[name]
35
+ end
36
+
37
+ def register(key, default = nil)
38
+ @accept_config.add(key.to_sym)
39
+ self[key.to_sym] = default if default
40
+ end
41
+
42
+ def accept?(key)
43
+ @accept_config.include?(key.to_sym)
44
+ end
45
+
46
+ def env(env = nil)
47
+ return Environment.new(self[:env]) if env.nil?
48
+ self[:env] = env.to_s
49
+ end
50
+
51
+ def env=(env)
52
+ self[:env] = env.to_s
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,28 @@
1
+ module Tamashii
2
+ class Environment < Hash
3
+
4
+ RUNTIME_ENV = %w(test development production)
5
+
6
+ def initialize(env = nil, **options)
7
+ self.merge!(options)
8
+ self[:env] = env.to_s unless env.nil?
9
+ end
10
+
11
+ def method_missing(name, *args, &block)
12
+ return is_env(name[0..-2]) if RUNTIME_ENV.include?(name[0..-2])
13
+ super
14
+ end
15
+
16
+ def ==(other)
17
+ self.to_s == other.to_s
18
+ end
19
+
20
+ def is_env(env)
21
+ self.to_s == env.to_s
22
+ end
23
+
24
+ def to_s
25
+ (self[:env] || ENV['RACK_ENV'] || "development").to_s
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,14 @@
1
+ module Tamashii
2
+ class Handler
3
+ attr_reader :type, :env
4
+ def initialize(type, env = {})
5
+ @type = type
6
+ @env = env
7
+ end
8
+
9
+ def resolve(data = nil)
10
+ raise NotImplementedError.new("The resolve method should be implemented.")
11
+ end
12
+ end
13
+ end
14
+
@@ -0,0 +1,13 @@
1
+ module Tamashii
2
+ class Hook
3
+ attr_reader :env
4
+
5
+ def initialize(env)
6
+ @env = env
7
+ end
8
+
9
+ def call(pkt)
10
+ raise NotImplementedError.new("Hook should implement the #call method")
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,86 @@
1
+ require 'logger'
2
+
3
+ module Tamashii
4
+ class Logger < ::Logger
5
+ module Colors
6
+ NOTHING = '0;0'
7
+ BLACK = '0;30'
8
+ RED = '0;31'
9
+ GREEN = '0;32'
10
+ BROWN = '0;33'
11
+ BLUE = '0;34'
12
+ PURPLE = '0;35'
13
+ CYAN = '0;36'
14
+ LIGHT_GRAY = '0;37'
15
+ DARK_GRAY = '1;30'
16
+ LIGHT_RED = '1;31'
17
+ LIGHT_GREEN = '1;32'
18
+ YELLOW = '1;33'
19
+ LIGHT_BLUE = '1;34'
20
+ LIGHT_PURPLE = '1;35'
21
+ LIGHT_CYAN = '1;36'
22
+ WHITE = '1;37'
23
+
24
+ SCHEMA = {
25
+ STDOUT => %w[nothing green brown red purple cyan],
26
+ STDERR => %w[nothing green yellow light_red light_purple light_cyan],
27
+ }
28
+ end
29
+
30
+ attr_accessor :enable_filter
31
+
32
+ FILTER_PARAMS = %i(token password)
33
+
34
+ alias format_message_colorless format_message
35
+
36
+ def initialize(*args)
37
+ super
38
+ @enable_filter = false
39
+ self.formatter = proc do |severity, datetime, progname, message|
40
+ severity = "UNKNOWN" if severity == "ANY"
41
+ datetime = datetime.strftime("%Y-%m-%d %H:%M:%S")
42
+ progname = " -- #{progname}" if progname
43
+ "[#{datetime}] #{severity}#{progname}\t: #{message}\n"
44
+ end
45
+ end
46
+
47
+ def format_message(level, *args)
48
+ if schema[Logger.const_get(level.sub "ANY", "UNKNOWN")].to_s.upcase
49
+ color = begin
50
+ Logger::Colors.const_get \
51
+ schema[Logger.const_get(level.sub "ANY", "UNKNOWN")].to_s.upcase
52
+ rescue NameError
53
+ "0;0"
54
+ end
55
+ "\e[#{ color }m#{ format_message_colorless(level, *args) }\e[0;0m"
56
+ else
57
+ format_message_colorless(level, *args)
58
+ end
59
+ end
60
+
61
+ def schema
62
+ Logger::Colors::SCHEMA[@logdev.dev] || Logger::Colors::SCHEMA[STDOUT]
63
+ end
64
+
65
+ def filter(progname = nil, **options, &block)
66
+ FILTER_PARAMS.each { |param| options[param] = "FILTERED" if options.include?(param) } if @enable_filter
67
+ if block_given?
68
+ yield
69
+ else
70
+ progname
71
+ end % options
72
+ end
73
+
74
+ def info(progname = nil, **options, &block)
75
+ severity = ::Logger.const_get(__callee__.upcase)
76
+ _progname = block_given? ? progname : nil
77
+ add(severity, filter(progname, **options, &block), _progname)
78
+ end
79
+
80
+ alias debug info
81
+ alias error info
82
+ alias warn info
83
+ alias fatal info
84
+ alias unknown info
85
+ end
86
+ end
@@ -0,0 +1,84 @@
1
+ module Tamashii
2
+ class Packet
3
+
4
+
5
+ DEVICE_TYPE_AGENT = 0
6
+ DEVICE_TYPE_CHECKIN = 1
7
+
8
+ STRING_TRUE = "0".freeze
9
+ STRING_FALSE = "1".freeze
10
+
11
+ attr_reader :type
12
+ attr_reader :tag
13
+ attr_reader :body
14
+
15
+
16
+ # 1 byte: type
17
+ # 2 bytes: tag
18
+ # 2 bytes: size of body
19
+ # variable-length body, in string
20
+ def self.dump(obj)
21
+ raise TypeError.new("Only Packet can be dump") unless obj.is_a?(self)
22
+ raise TypeError.new("Body must be a string") unless obj.body.is_a?(String)
23
+ header = [obj.type, *split_integer(obj.tag), *split_integer(obj.body.bytesize)]
24
+ header + obj.body.unpack("C*")
25
+ end
26
+
27
+ def self.split_integer(n, byte_num = 2)
28
+ res = []
29
+ byte_num.times do
30
+ res.unshift(n & 0xFF)
31
+ n >>= 8
32
+ end
33
+ res
34
+ end
35
+
36
+ def self.combine_integer(bytes)
37
+ n = 0
38
+ bytes.each do |byte|
39
+ n = n << 8 | byte
40
+ end
41
+ n
42
+ end
43
+
44
+ def self.load(byte_array)
45
+ header_bytes = byte_array[0..4]
46
+ body_bytes = byte_array[5..-1] || ""
47
+ packed_data = if body_bytes.is_a? String
48
+ body_bytes
49
+ else
50
+ body_bytes.pack("C*")
51
+ end
52
+ new(header_bytes[0], combine_integer(header_bytes[1..2]), packed_data)
53
+ rescue
54
+ nil
55
+ end
56
+
57
+ def initialize(type, tag = 0, body = '')
58
+ @type = type
59
+ @tag = tag
60
+ @body = body
61
+ body_conversion
62
+ end
63
+
64
+ def body_conversion
65
+ if @body.is_a? TrueClass
66
+ @body = STRING_TRUE.clone
67
+ elsif @body.is_a? FalseClass
68
+ @body = STRING_FALSE.clone
69
+ end
70
+ end
71
+
72
+ def dump
73
+ self.class.dump(self)
74
+ end
75
+
76
+ def type_code
77
+ @type & (0x7 << 3)
78
+ end
79
+
80
+ def action_code
81
+ @type & 0x7
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,60 @@
1
+ require 'tamashii/packet'
2
+
3
+ module Tamashii
4
+ class Resolver
5
+
6
+ class << self
7
+ def method_missing(name, *args, &block)
8
+ self.instance.send(name, *args, &block)
9
+ end
10
+
11
+ def instance
12
+ @instance ||= self.new
13
+ end
14
+ end
15
+
16
+ def handlers
17
+ @handlers ||= {}
18
+ end
19
+
20
+ def hooks
21
+ @hooks ||= []
22
+ end
23
+
24
+ def config(&block)
25
+ instance_eval(&block)
26
+ end
27
+
28
+ def default_handler(handler_class = nil, env = {})
29
+ return @default_handler || [nil, {}] if handler_class.nil?
30
+ @default_handler = [handler_class, env]
31
+ end
32
+
33
+ def handle(type, handler_class, options = {})
34
+ raise NotImplementedError.new("Handler should implement resolve method") unless handler_class.method_defined?(:resolve)
35
+ handlers[type] = [handler_class, options]
36
+ end
37
+
38
+ def hook(hook_class, env = {})
39
+ raise NotImplementedError.new("Hook should implement call method") unless hook_class.method_defined?(:call)
40
+ hooks << [hook_class, env]
41
+ end
42
+
43
+ def resolve(pkt, env = {})
44
+ hooks.each do |hook_data|
45
+ hook_class, hook_env = hook_data
46
+ if hook_class.new(hook_env.merge(env)).call(pkt)
47
+ # terminates the procedure
48
+ return
49
+ end
50
+ end
51
+ handler, options = handlers[pkt.type] || @default_handler
52
+ handler.new(pkt.type, options.merge(env)).resolve(pkt.body) if handler
53
+ end
54
+
55
+ def handle?(type)
56
+ handlers.has_key? type
57
+ end
58
+ end
59
+ end
60
+
@@ -0,0 +1,35 @@
1
+ require 'tamashii/packet'
2
+
3
+ module Tamashii
4
+ module RSpec
5
+ module Helpers
6
+ def websocket_mask
7
+ (1..4).map { rand 255 }
8
+ end
9
+
10
+ def websocket_mask_message(mask, *bytes)
11
+ output = []
12
+ bytes.each_with_index do |byte, i|
13
+ output[i] = byte ^ mask[i % 4]
14
+ end
15
+ output
16
+ end
17
+
18
+ def tamashii_packet(type, tag, body)
19
+ Tamashii::Packet.new(type, tag, body).dump
20
+ end
21
+
22
+ def tamashii_binary_packet(type, tag, body)
23
+ mask = websocket_mask
24
+ packet = tamashii_packet(type, tag, body)
25
+ [0x82, 0x80 + packet.size] + mask + websocket_mask_message(mask, *packet)
26
+ end
27
+
28
+ def tamashii_text_packet(type, tag, body)
29
+ mask = websocket_mask
30
+ packet = tamashii_packet(type, tag, body)
31
+ [0x81, 0x80 + packet.size] + mask + websocket_mask_message(mask, *packet)
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,28 @@
1
+ module Tamashii
2
+ module Type
3
+ # Client Type
4
+ CLIENT = {
5
+ agent: 0,
6
+ checkin: 1,
7
+ }
8
+
9
+ # System Action
10
+ POWEROFF = 000
11
+ REBOOT = 001
12
+ RESTART = 002
13
+ UPDATE = 003
14
+
15
+ # Authorization Action
16
+ AUTH_TOKEN = 010
17
+ AUTH_RESPONSE = 017
18
+
19
+ # Card Reader Action
20
+ RFID_NUMBER = 030
21
+ RFID_DATA = 031
22
+ RFID_RESPONSE_JSON = 036
23
+ RFID_RESPONSE_STRING = 047
24
+
25
+ # Buzzer Action
26
+ BUZZER_SOUND = 040
27
+ end
28
+ end
@@ -0,0 +1,38 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'tamashii/common/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "tamashii-common"
8
+ spec.version = Tamashii::Common::VERSION
9
+ spec.authors = ["蒼時弦也", "Liang-Chi Tseng", "五倍紅寶石"]
10
+ spec.email = ["elct9620@frost.tw", "lctseng@cs.nctu.edu.tw", "hi@5xruby.tw"]
11
+
12
+ spec.summary = %q{The shared module for RubyConfTW checkin system.}
13
+ spec.description = %q{The shared module for RubyConfTW checkin system.}
14
+ spec.homepage = "https://github.com/lctseng/tamashii-common"
15
+
16
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
17
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
18
+ if spec.respond_to?(:metadata)
19
+ # spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
20
+ else
21
+ raise "RubyGems 2.0 or newer is required to protect against " \
22
+ "public gem pushes."
23
+ end
24
+
25
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
26
+ f.match(%r{^(test|spec|features)/})
27
+ end
28
+ spec.bindir = "exe"
29
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
30
+ spec.require_paths = ["lib"]
31
+
32
+ spec.add_development_dependency "bundler", "~> 1.13"
33
+ spec.add_development_dependency "rake", "~> 10.0"
34
+ spec.add_development_dependency "rspec", "~> 3.0"
35
+ spec.add_development_dependency "simplecov"
36
+ spec.add_development_dependency "guard"
37
+ spec.add_development_dependency "guard-rspec"
38
+ end
metadata ADDED
@@ -0,0 +1,153 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: tamashii-common
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.2
5
+ platform: ruby
6
+ authors:
7
+ - 蒼時弦也
8
+ - Liang-Chi Tseng
9
+ - 五倍紅寶石
10
+ autorequire:
11
+ bindir: exe
12
+ cert_chain: []
13
+ date: 2017-02-21 00:00:00.000000000 Z
14
+ dependencies:
15
+ - !ruby/object:Gem::Dependency
16
+ name: bundler
17
+ requirement: !ruby/object:Gem::Requirement
18
+ requirements:
19
+ - - "~>"
20
+ - !ruby/object:Gem::Version
21
+ version: '1.13'
22
+ type: :development
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ requirements:
26
+ - - "~>"
27
+ - !ruby/object:Gem::Version
28
+ version: '1.13'
29
+ - !ruby/object:Gem::Dependency
30
+ name: rake
31
+ requirement: !ruby/object:Gem::Requirement
32
+ requirements:
33
+ - - "~>"
34
+ - !ruby/object:Gem::Version
35
+ version: '10.0'
36
+ type: :development
37
+ prerelease: false
38
+ version_requirements: !ruby/object:Gem::Requirement
39
+ requirements:
40
+ - - "~>"
41
+ - !ruby/object:Gem::Version
42
+ version: '10.0'
43
+ - !ruby/object:Gem::Dependency
44
+ name: rspec
45
+ requirement: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - "~>"
48
+ - !ruby/object:Gem::Version
49
+ version: '3.0'
50
+ type: :development
51
+ prerelease: false
52
+ version_requirements: !ruby/object:Gem::Requirement
53
+ requirements:
54
+ - - "~>"
55
+ - !ruby/object:Gem::Version
56
+ version: '3.0'
57
+ - !ruby/object:Gem::Dependency
58
+ name: simplecov
59
+ requirement: !ruby/object:Gem::Requirement
60
+ requirements:
61
+ - - ">="
62
+ - !ruby/object:Gem::Version
63
+ version: '0'
64
+ type: :development
65
+ prerelease: false
66
+ version_requirements: !ruby/object:Gem::Requirement
67
+ requirements:
68
+ - - ">="
69
+ - !ruby/object:Gem::Version
70
+ version: '0'
71
+ - !ruby/object:Gem::Dependency
72
+ name: guard
73
+ requirement: !ruby/object:Gem::Requirement
74
+ requirements:
75
+ - - ">="
76
+ - !ruby/object:Gem::Version
77
+ version: '0'
78
+ type: :development
79
+ prerelease: false
80
+ version_requirements: !ruby/object:Gem::Requirement
81
+ requirements:
82
+ - - ">="
83
+ - !ruby/object:Gem::Version
84
+ version: '0'
85
+ - !ruby/object:Gem::Dependency
86
+ name: guard-rspec
87
+ requirement: !ruby/object:Gem::Requirement
88
+ requirements:
89
+ - - ">="
90
+ - !ruby/object:Gem::Version
91
+ version: '0'
92
+ type: :development
93
+ prerelease: false
94
+ version_requirements: !ruby/object:Gem::Requirement
95
+ requirements:
96
+ - - ">="
97
+ - !ruby/object:Gem::Version
98
+ version: '0'
99
+ description: The shared module for RubyConfTW checkin system.
100
+ email:
101
+ - elct9620@frost.tw
102
+ - lctseng@cs.nctu.edu.tw
103
+ - hi@5xruby.tw
104
+ executables: []
105
+ extensions: []
106
+ extra_rdoc_files: []
107
+ files:
108
+ - ".gitignore"
109
+ - ".rspec"
110
+ - ".travis.yml"
111
+ - Gemfile
112
+ - Guardfile
113
+ - LICENSE.md
114
+ - README.md
115
+ - Rakefile
116
+ - bin/console
117
+ - bin/setup
118
+ - lib/tamashii/common.rb
119
+ - lib/tamashii/common/version.rb
120
+ - lib/tamashii/config.rb
121
+ - lib/tamashii/environment.rb
122
+ - lib/tamashii/handler.rb
123
+ - lib/tamashii/hook.rb
124
+ - lib/tamashii/logger.rb
125
+ - lib/tamashii/packet.rb
126
+ - lib/tamashii/resolver.rb
127
+ - lib/tamashii/rspec/helpers.rb
128
+ - lib/tamashii/type.rb
129
+ - tamashii-common.gemspec
130
+ homepage: https://github.com/lctseng/tamashii-common
131
+ licenses: []
132
+ metadata: {}
133
+ post_install_message:
134
+ rdoc_options: []
135
+ require_paths:
136
+ - lib
137
+ required_ruby_version: !ruby/object:Gem::Requirement
138
+ requirements:
139
+ - - ">="
140
+ - !ruby/object:Gem::Version
141
+ version: '0'
142
+ required_rubygems_version: !ruby/object:Gem::Requirement
143
+ requirements:
144
+ - - ">="
145
+ - !ruby/object:Gem::Version
146
+ version: '0'
147
+ requirements: []
148
+ rubyforge_project:
149
+ rubygems_version: 2.5.1
150
+ signing_key:
151
+ specification_version: 4
152
+ summary: The shared module for RubyConfTW checkin system.
153
+ test_files: []