redis_utility 1.0.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: 232c0bf2b0c4a9832e57ec7bd8ab70b12551b8aa92ded0b05be3e33cc8d27736
4
+ data.tar.gz: b9b0e6a4607a7edf853ae96926bd12de777499de71417ebbc86a738418bea17a
5
+ SHA512:
6
+ metadata.gz: f32975b0736c7b5d50331b5682c78dcab7a7a78361613542122e5ac1729feae5a4a8dc6fb1dfa2b063a821d68abaad82b42d3d08a800009c6366a5c88e190a48
7
+ data.tar.gz: 76f1c9b1370dd792f6cf4ccc49f882267b65846084759ca63a7f853c2405db5c6343999cae22ea4ad8dde3db7a8177fb9817531ce3f15fc1e2ee47903976dea4
@@ -0,0 +1,55 @@
1
+ version: 2
2
+ jobs:
3
+ build:
4
+ working_directory: ~/YourMechanic/redis_utility
5
+ parallelism: 1
6
+ shell: /bin/bash --login
7
+
8
+ environment:
9
+ CIRCLE_ARTIFACTS: /tmp/circleci-artifacts
10
+ CIRCLE_TEST_REPORTS: /tmp/circleci-test-results
11
+ docker:
12
+ - image: circleci/ruby:2.6.2
13
+ - image: redis
14
+ steps:
15
+ - checkout
16
+ - run: mkdir -p $CIRCLE_ARTIFACTS $CIRCLE_TEST_REPORTS
17
+ - restore_cache:
18
+ keys:
19
+ # This branch if available
20
+ - v2-dep-{{ .Branch }}-
21
+ # Default branch if not
22
+ - v2-dep-master-
23
+ # Any branch if there are none on the default branch - this should be unnecessary if you have your default branch configured correctly
24
+ - v2-dep-
25
+ - run:
26
+ name: Install bundler for redis_utility
27
+ working_directory: ~/YourMechanic/redis_utility
28
+ command: gem install bundler:2.2.11
29
+ - run:
30
+ name: Install Gems for redis_utility
31
+ working_directory: ~/YourMechanic/redis_utility
32
+ command: bundle install
33
+ # Save dependency cache
34
+ - save_cache:
35
+ key: v2-dep-{{ .Branch }}-{{ epoch }}
36
+ paths:
37
+ - vendor/bundle
38
+ - ~/virtualenvs
39
+ - ~/.m2
40
+ - ~/.ivy2
41
+ - ~/.bundle
42
+ - run:
43
+ working_directory: ~/YourMechanic/redis_utility
44
+ command: bundle exec rubocop
45
+ - run:
46
+ working_directory: ~/YourMechanic/redis_utility
47
+ command: bundle exec rspec --colour --drb --profile -fd --format progress $(circleci tests glob "spec/*_spec.rb" | circleci tests split)
48
+ - store_test_results:
49
+ path: /tmp/circleci-test-results
50
+ - store_artifacts:
51
+ path: /tmp/circleci-artifacts
52
+ - store_artifacts:
53
+ path: /tmp/circleci-test-results
54
+ - store_artifacts:
55
+ path: redis_utility/coverage
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,27 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.6
3
+
4
+ Metrics/PerceivedComplexity:
5
+ Enabled: false
6
+
7
+ Metrics/CyclomaticComplexity:
8
+ Enabled: false
9
+
10
+ Metrics/AbcSize:
11
+ Enabled: false
12
+
13
+ Gemspec/RequiredRubyVersion:
14
+ Enabled: false
15
+
16
+ Metrics/BlockNesting:
17
+ Enabled: false
18
+
19
+ Layout/LineLength:
20
+ Max: 120
21
+
22
+ Metrics/MethodLength:
23
+ Max: 40
24
+ Metrics/ClassLength:
25
+ Max: 300
26
+ Metrics/BlockLength:
27
+ Max: 50
@@ -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 sachinsaxena1996@gmail.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,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ # Specify your gem's dependencies in redis_utility.gemspec
6
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,63 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ redis_utility (1.0.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ ast (2.4.2)
10
+ byebug (11.1.3)
11
+ diff-lcs (1.4.4)
12
+ multi_json (1.15.0)
13
+ parallel (1.21.0)
14
+ parser (3.0.2.0)
15
+ ast (~> 2.4.1)
16
+ rainbow (3.0.0)
17
+ rake (13.0.6)
18
+ redis (4.4.0)
19
+ regexp_parser (2.1.1)
20
+ rexml (3.2.5)
21
+ rspec (3.10.0)
22
+ rspec-core (~> 3.10.0)
23
+ rspec-expectations (~> 3.10.0)
24
+ rspec-mocks (~> 3.10.0)
25
+ rspec-core (3.10.1)
26
+ rspec-support (~> 3.10.0)
27
+ rspec-expectations (3.10.1)
28
+ diff-lcs (>= 1.2.0, < 2.0)
29
+ rspec-support (~> 3.10.0)
30
+ rspec-mocks (3.10.2)
31
+ diff-lcs (>= 1.2.0, < 2.0)
32
+ rspec-support (~> 3.10.0)
33
+ rspec-support (3.10.2)
34
+ rubocop (1.21.0)
35
+ parallel (~> 1.10)
36
+ parser (>= 3.0.0.0)
37
+ rainbow (>= 2.2.2, < 4.0)
38
+ regexp_parser (>= 1.8, < 3.0)
39
+ rexml
40
+ rubocop-ast (>= 1.9.1, < 2.0)
41
+ ruby-progressbar (~> 1.7)
42
+ unicode-display_width (>= 1.4.0, < 3.0)
43
+ rubocop-ast (1.11.0)
44
+ parser (>= 3.0.1.1)
45
+ ruby-progressbar (1.11.0)
46
+ unicode-display_width (2.1.0)
47
+ yajl-ruby (1.4.1)
48
+
49
+ PLATFORMS
50
+ x86_64-linux
51
+
52
+ DEPENDENCIES
53
+ byebug
54
+ multi_json
55
+ rake (~> 13.0)
56
+ redis
57
+ redis_utility!
58
+ rspec (~> 3.0)
59
+ rubocop (~> 1.7)
60
+ yajl-ruby (= 1.4.1)
61
+
62
+ BUNDLED WITH
63
+ 2.2.11
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 YourMechanic
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.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 sachinsaxena1996
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,82 @@
1
+ # RedisUtility
2
+
3
+ An awesome gem which provides utility methods for redis db. Can be used with any rails application which is using redis.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'redis_utility'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle install
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install redis_utility
20
+
21
+ ## Usage
22
+
23
+ After installing the gem create a file redis_utility.rb in config/initializers with following content:
24
+
25
+ ```ruby
26
+ RedisUtility.redis_config = { host: 'localhost', timeout: 60, db: 'redis_db', password: 'password'}
27
+ ```
28
+
29
+ Following are use cases:
30
+
31
+ ### To get the redis config
32
+ ```ruby
33
+ RedisUtility.redis
34
+ ```
35
+
36
+ ### To stop and create a new redis connection
37
+ ```ruby
38
+ RedisUtility.reconnect
39
+ ```
40
+
41
+ ### To import data from a file to redis
42
+ ```ruby
43
+ RedisUtility.import_data('import_file.ljson')
44
+ ```
45
+
46
+ ### To export matching keys values from redis to a file
47
+ ```ruby
48
+ RedisUtility.export_data('Car_Acura|CL|*', 'ouput_export_file.ljson')
49
+ ```
50
+
51
+ ### To cache a string to redis db. It caches the value of the block passed to it
52
+ ```ruby
53
+ RedisUtility.cache_string('cache_this', { expire: 20 }) { 'the value of block passed' }
54
+ ```
55
+
56
+ ### To cache multijson value in redis. It caches the value of the block passed to it
57
+ ```ruby
58
+ RedisUtility.cache('cache_multi_json', { expire: 20 }) { '{"Car_Acura|CL|":"01010000_EE000000000","Car_Acura|CL|L4-2.2L":"01010100_2000000000"}' }
59
+ ```
60
+
61
+ ### To export matching string key data to a file
62
+ ```ruby
63
+ RedisUtility.export_string_data('Car_Acura|CL|*', 'string_export_file.ljson')
64
+ ```
65
+
66
+ ## Development
67
+
68
+ 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.
69
+
70
+ 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).
71
+
72
+ ## Contributing
73
+
74
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/redis_utility. 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]/redis_utility/blob/master/CODE_OF_CONDUCT.md).
75
+
76
+ ## License
77
+
78
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
79
+
80
+ ## Code of Conduct
81
+
82
+ Everyone interacting in the RedisUtility project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/redis_utility/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/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'redis_utility'
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
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RedisUtility
4
+ VERSION = '1.0.0'
5
+ end
@@ -0,0 +1,238 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'redis_utility/version'
4
+ require 'yajl'
5
+ require 'json'
6
+ require 'multi_json'
7
+
8
+ # rubocop:disable Metrics/ModuleLength
9
+
10
+ # module RedisUtility namespace for redis methods
11
+ module RedisUtility
12
+ extend self
13
+ KEY_BATCH_SIZE = 1000
14
+
15
+ # Imports a line-by-line json string
16
+ def import_data(file)
17
+ bzip2_openfile(file, 'rb') do |f1|
18
+ until f1.eof?
19
+ keys = 0
20
+ redis.pipelined do
21
+ # rubocop:disable Lint/AssignmentInCondition
22
+ while curr_line = f1.gets
23
+ # rubocop:enable Lint/AssignmentInCondition
24
+ line = JSON.parse(curr_line)
25
+ line.each do |key, val|
26
+ keys += 1
27
+ # first delete the record from the server before adding new value
28
+ case val
29
+ when Hash
30
+ redis.del key
31
+ redis.mapped_hmset(key, val)
32
+ when Array
33
+ redis.del key
34
+ if val[0].is_a?(Array) && val[0][1].is_a?(Float) # zset
35
+ val = val.map { |v| [v[1], v[0]] }
36
+ redis.zadd(key, val)
37
+ else
38
+ redis.rpush(key, val)
39
+ end
40
+ else
41
+ redis.set(key, val)
42
+ end
43
+ end
44
+ # Done with the line
45
+ if keys > KEY_BATCH_SIZE
46
+ print '.'
47
+ break
48
+ end
49
+ end
50
+ end
51
+ end
52
+ end
53
+ end
54
+
55
+ # Export the key pattern
56
+ def export_data(key_patterns, filename)
57
+ key_patterns = [key_patterns] if key_patterns.is_a? String
58
+
59
+ File.open(filename, 'w+b') do |f|
60
+ key_patterns.each do |kp|
61
+ allkeys = kp.include?('*') ? redis.keys(kp).sort : [kp]
62
+ print "Working on #{kp}: #{quantity_with_unit(allkeys.size, 'key')}\n"
63
+ nstart = 0
64
+ while nstart < allkeys.size
65
+ keys = allkeys[nstart...nstart + KEY_BATCH_SIZE]
66
+ types = redis.pipelined { keys.each { |k| redis.type(k) } }
67
+ # print "Got types\n"
68
+ string_keys = []
69
+ pkeys = []
70
+ pvals = redis.pipelined do
71
+ keys.each_with_index do |key, idx|
72
+ case types[idx]
73
+ when 'string'
74
+ string_keys << key
75
+ when 'hash'
76
+ pkeys << key
77
+ redis.hgetall(key)
78
+ when 'list'
79
+ pkeys << key
80
+ redis.lrange(key, 0, -1)
81
+ when 'zset'
82
+ pkeys << key
83
+ redis.zrange(key, 0, -1, with_scores: true)
84
+ else
85
+ print "RedisUtility: Can not deal with #{types[idx]} for key #{key}, skipped\n"
86
+ end
87
+ end
88
+ end
89
+ write_pipelined_results(pkeys, pvals, f)
90
+ write_string_keys(string_keys, f)
91
+ nstart += KEY_BATCH_SIZE
92
+ print '.' if nstart < allkeys.size
93
+ end
94
+ end
95
+ end
96
+ end
97
+
98
+ def cache_string(key, params = {})
99
+ expire = params[:expire]
100
+ recalculate = params[:recalculate]
101
+
102
+ if recalculate || (value = redis.get(key)).nil?
103
+ value = yield(self).to_s
104
+
105
+ redis.set(key, value)
106
+ redis.expire(key, expire) if expire
107
+ end
108
+
109
+ value
110
+ end
111
+
112
+ def cache(key, params = {})
113
+ expire = params[:expire]
114
+ recalculate = params[:recalculate]
115
+
116
+ if recalculate || (value = redis.get(key)).nil?
117
+ value = MultiJson.encode(yield(self))
118
+
119
+ redis.set(key, value)
120
+ redis.expire(key, expire) if expire
121
+ end
122
+
123
+ MultiJson.decode(value)
124
+ end
125
+
126
+ def export_string_data(key_patterns, filename)
127
+ key_patterns = [key_patterns] if key_patterns.is_a? String
128
+
129
+ File.open(filename, 'w') do |f|
130
+ key_patterns.each do |kp|
131
+ keys = redis.keys(kp)
132
+ write_string_keys(keys, f)
133
+ end
134
+ end
135
+ end
136
+
137
+ def redis_config
138
+ @redis_config
139
+ end
140
+
141
+ def redis_config=(redis_conf)
142
+ @redis_config = redis_conf
143
+ end
144
+
145
+ def redis
146
+ unless @redis
147
+ # print "RedisUtility: Connecting\n"
148
+ cfg = redis_config.dup
149
+ cfg[:timeout] = 60 # Set longer timeout for efficient bulk loading/save
150
+ @redis = Redis.new(cfg)
151
+ end
152
+ @redis
153
+ end
154
+
155
+ def reconnect
156
+ if @redis
157
+ @redis._client.disconnect
158
+ @redis = nil
159
+ redis # This reconnects to redis with right configurations
160
+ end
161
+ nil
162
+ end
163
+
164
+ #########################################
165
+ private
166
+
167
+ def quantity_with_unit(quantity, unit, unit_s = nil)
168
+ "#{quantity} #{quantity > 1 ? (unit_s || "#{unit}s") : unit}"
169
+ end
170
+
171
+ def system_with_print(cmd)
172
+ print "EXEC:#{cmd}\n"
173
+ ret = system(cmd)
174
+ print "EXEC failed\n" if ret.nil?
175
+ end
176
+
177
+ # Opens the bzip2 and yield with File object (file itself is opened)
178
+ def bzip2_openfile(file_nm, mode, &block)
179
+ raise 'Not implemented for writing bzip2 yet' if mode.include?('w')
180
+
181
+ file_nm = file_nm.to_s
182
+ if file_nm.end_with?('.bz2')
183
+ raise "#{file_nm} does not exist" unless File.exist?(file_nm)
184
+
185
+ file = file_nm[0..-5]
186
+ File.delete(file) if File.exist?(file)
187
+ system_with_print("bunzip2 -kd #{file_nm}")
188
+ else
189
+ file = file_nm
190
+ end
191
+
192
+ File.open(file, mode, &block)
193
+
194
+ File.delete(file) if file_nm.end_with?('.bz2')
195
+ end
196
+
197
+ def write_string_keys_chunk(string_keys, file_obj)
198
+ return unless string_keys.size.positive?
199
+
200
+ hash = {}
201
+ string_vals = redis.mget(string_keys)
202
+ string_keys.each_with_index do |key, idx|
203
+ val = string_vals[idx]
204
+ next unless val
205
+ next if key.start_with?('YMProd:rails_cache') # Migration to avoid legacy cache
206
+
207
+ if val.nil?
208
+ print "RedisUtility: Can not get value for key #{key}, skipped\n"
209
+ else
210
+ hash[key] = val
211
+ end
212
+ end
213
+ Yajl::Encoder.encode(hash, file_obj)
214
+ file_obj.write("\n")
215
+ end
216
+
217
+ WRITE_BATCH_SIZE = 100
218
+ def write_string_keys(string_keys, file_obj)
219
+ while string_keys.size > WRITE_BATCH_SIZE
220
+ first_chunk = string_keys.shift(WRITE_BATCH_SIZE)
221
+ write_string_keys_chunk(first_chunk, file_obj)
222
+ end
223
+ write_string_keys_chunk(string_keys, file_obj)
224
+ end
225
+
226
+ def write_pipelined_results(keys, vals, file_obj)
227
+ keys.each_with_index do |key, idx|
228
+ begin
229
+ Yajl::Encoder.encode({ key => vals[idx] }, file_obj)
230
+ rescue EncodingError
231
+ print "Skipped #{key}. Encoding error\n"
232
+ end
233
+ file_obj.write("\n")
234
+ end
235
+ end
236
+ end
237
+
238
+ # rubocop:enable Metrics/ModuleLength
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/redis_utility/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'redis_utility'
7
+ spec.version = RedisUtility::VERSION
8
+ spec.authors = ['sachinsaxena1996']
9
+ spec.email = ['dev@yourmechanic.com']
10
+
11
+ spec.summary = 'An awesome utility gem which provides an api to the redis db'
12
+ spec.description = 'An awesome utility gem which provides an api to the redis db'
13
+ spec.homepage = 'https://github.com/YourMechanic/redis_utility'
14
+ spec.license = 'MIT'
15
+ # spec.required_ruby_version = Gem::Requirement.new(">= 2.4.0")
16
+
17
+ spec.metadata['allowed_push_host'] = 'https://rubygems.org'
18
+
19
+ spec.metadata['homepage_uri'] = spec.homepage
20
+ spec.metadata['source_code_uri'] = 'https://github.com/YourMechanic/redis_utility'
21
+ # spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here."
22
+
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
26
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
27
+ end
28
+ spec.bindir = 'exe'
29
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
30
+ spec.require_paths = ['lib']
31
+
32
+ spec.add_development_dependency 'byebug'
33
+ spec.add_development_dependency 'multi_json'
34
+ spec.add_development_dependency 'rake', '~> 13.0'
35
+ spec.add_development_dependency 'redis'
36
+ spec.add_development_dependency 'rspec', '~> 3.0'
37
+ spec.add_development_dependency 'rubocop', '~> 1.7'
38
+ spec.add_development_dependency 'yajl-ruby', '1.4.1'
39
+ end
metadata ADDED
@@ -0,0 +1,160 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: redis_utility
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - sachinsaxena1996
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-10-12 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: byebug
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :development
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: multi_json
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
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: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '13.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '13.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: redis
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rspec
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rubocop
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '1.7'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '1.7'
97
+ - !ruby/object:Gem::Dependency
98
+ name: yajl-ruby
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - '='
102
+ - !ruby/object:Gem::Version
103
+ version: 1.4.1
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - '='
109
+ - !ruby/object:Gem::Version
110
+ version: 1.4.1
111
+ description: An awesome utility gem which provides an api to the redis db
112
+ email:
113
+ - dev@yourmechanic.com
114
+ executables: []
115
+ extensions: []
116
+ extra_rdoc_files: []
117
+ files:
118
+ - ".circleci/config.yml"
119
+ - ".gitignore"
120
+ - ".rspec"
121
+ - ".rubocop.yml"
122
+ - CODE_OF_CONDUCT.md
123
+ - Gemfile
124
+ - Gemfile.lock
125
+ - LICENSE
126
+ - LICENSE.txt
127
+ - README.md
128
+ - Rakefile
129
+ - bin/console
130
+ - bin/setup
131
+ - lib/redis_utility.rb
132
+ - lib/redis_utility/version.rb
133
+ - redis_utility.gemspec
134
+ homepage: https://github.com/YourMechanic/redis_utility
135
+ licenses:
136
+ - MIT
137
+ metadata:
138
+ allowed_push_host: https://rubygems.org
139
+ homepage_uri: https://github.com/YourMechanic/redis_utility
140
+ source_code_uri: https://github.com/YourMechanic/redis_utility
141
+ post_install_message:
142
+ rdoc_options: []
143
+ require_paths:
144
+ - lib
145
+ required_ruby_version: !ruby/object:Gem::Requirement
146
+ requirements:
147
+ - - ">="
148
+ - !ruby/object:Gem::Version
149
+ version: '0'
150
+ required_rubygems_version: !ruby/object:Gem::Requirement
151
+ requirements:
152
+ - - ">="
153
+ - !ruby/object:Gem::Version
154
+ version: '0'
155
+ requirements: []
156
+ rubygems_version: 3.0.3
157
+ signing_key:
158
+ specification_version: 4
159
+ summary: An awesome utility gem which provides an api to the redis db
160
+ test_files: []