bit_magic 0.1.1

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: 82716dcf8e54d3738278f98af111dfedb4cd1884
4
+ data.tar.gz: a6385df6cdea437a50a9244be17591510b8fd56d
5
+ SHA512:
6
+ metadata.gz: c8943a196330e9d762e2905bf3a2e8f4559a72496981b3af10b0135462c7b881b42003be8fb1b79634c2f74d80773279a82d9acefff24e9346e2033a7f3b83a9
7
+ data.tar.gz: c5f535ecfb9a38c144be10efc1635820f4a10193bd8f73332e36f0313e19a8a13b5341e2e3148ee4bbc383491ad8f2e438fcdfd91432b0c8fe44f4cc324850bf
data/.coco.yml ADDED
@@ -0,0 +1,4 @@
1
+ :include:
2
+ - lib
3
+ :always_run: false
4
+ :theme: light
data/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ /test/adapters/mongoid.yml
10
+ .ruby-version
data/.travis.yml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.1.3
7
+ before_install: gem install bundler -v 1.16.3
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at kiafaldorius@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in bit_magic.gemspec
6
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,24 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ bit_magic (0.1.1)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ coco (0.15.0)
10
+ minitest (5.11.3)
11
+ rake (10.5.0)
12
+
13
+ PLATFORMS
14
+ ruby
15
+
16
+ DEPENDENCIES
17
+ bit_magic!
18
+ bundler (~> 1.16)
19
+ coco (~> 0.15)
20
+ minitest (~> 5.0)
21
+ rake (~> 10.0)
22
+
23
+ BUNDLED WITH
24
+ 1.16.4
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 User Hello LLC
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,290 @@
1
+ # BitMagic
2
+
3
+ Bit field and bit flag utility library with integration for ActiveRecord and Mongoid.
4
+
5
+ | Project | bit_magic |
6
+ |------------------------ | ----------------- |
7
+ | gem name | bit_magic |
8
+ | license | [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) |
9
+ | download rank | [![Total Downloads](https://img.shields.io/gem/rt/bit_magic.svg)](https://rubygems.org/gems/bit_magic) |
10
+ | homepage | [homepage (github)](https://github.com/userhello/bit_magic) |
11
+ | documentation | [rubydoc.info](https://www.rubydoc.info/gems/bit_magic/frames) |
12
+
13
+ ## Summary
14
+
15
+ This gem provides basic utility classes for reading and writing specific bits as flags or fields on Integer values. It lets you turn a single integer value into a collection of boolean values (flags) or smaller numbers (fields). Includes integration adapters for ActiveRecord and Mongoid and a simple interface to make your own custom adapter for any other ORM (ActiveModel, ActiveResource, etc) or just a plan ruby class.
16
+
17
+ Flags can be used as though they were a boolean attribute and fields can be treated as an integer with limited range (based on the number of bits allocated to the field).
18
+
19
+ Pros:
20
+
21
+ * For SQL: No migrations necessary for new boolean attributes. For large tables with lots of rows and/or columns, this avoids costly `ALTER TABLE` calls.
22
+ * Only need to index one integer field, rather than multiple booleans
23
+ * Bitwise operations are fast!
24
+ * Save on database memory allocation. Since booleans are often stored as a full byte by many databases, using a 4-byte integer value allows up to 32 booleans for the same storage as 4.
25
+
26
+ Cons: (That's why you have this gem!)
27
+
28
+ * Querying individual boolean fields can be more complicated.
29
+ * Bit allocations need to be maintained
30
+ * Uses up more memory initially until you need more than a couple flags or fields
31
+
32
+
33
+ ## Installation
34
+
35
+ Add this line to your application's Gemfile:
36
+
37
+ ```ruby
38
+ gem 'bit_magic'
39
+ ```
40
+
41
+ And then execute:
42
+
43
+ $ bundle
44
+
45
+ Or install it yourself as:
46
+
47
+ $ gem install bit_magic
48
+
49
+ ## Usage
50
+
51
+ Bit magic provides bare utility classes and integrations with Rails, ActiveRecord and Mongoid. Use the utility classes if you're working with bits directly such as within a library. For usage with ORMs, you'll want to use it with an integration, so you can skip the section on utility classes and go directly to your Integration below.
52
+
53
+ ### Utility Classes
54
+
55
+ #### Bit Field
56
+
57
+ Bit Field is a wraper around integer values.
58
+
59
+ _Note: Because of the way ruby handles Integers--and specifically negative integers with two's complement--it's currently not recommended to use this with a negative value. Read bits and write bits will work, but the value will always remain negative because there's no specific sign bit as the case with typecasted languages._
60
+
61
+ _If there's demand for it, I can implement byte sizes to restrict maximum size and define the sign bit. Let me know if you have a use case that requires it._
62
+
63
+ ```ruby
64
+ field = BitMagic::BitField.new(0)
65
+ field.write_bits(1 => true, 2 => true, 5 => true)
66
+ # => 38 # in binary 38 is 100110
67
+ field.value
68
+ # => 38
69
+ field.read_bits(0, 1, 2, 3, 5)
70
+ # => {0=>0, 1=>1, 2=>1, 3=>0, 5=>1}
71
+ field.read_field(0)
72
+ # => 0
73
+ field.read_field(1, 2)
74
+ # => 3 # <- because '11' in binary is 3
75
+ field.read_field(1, 3, 2)
76
+ # => 5 # <- because '101' is 5
77
+ ```
78
+
79
+ #### Bit Generator
80
+
81
+ Bits Generator is a generator for Integer bit representations or arrays of values that match certain bitwise criteria. The criteria are:
82
+
83
+ | Name / Alias | Criteria |
84
+ |------------------------ | ----------------- |
85
+ | with\_any / any\_of | any of these bits specified are true |
86
+ | with\_all / all\_of | all of these bits are true |
87
+ | without\_any / none\_of | none of these bits are true |
88
+ | without\_all / instead\_of | all of these bits are *not* true |
89
+ | equal\_to(field\_name => value) | the bits for field\_name must equal bits in value |
90
+
91
+ These all have a corresponding *_number method that returns an integer. (equal\_to's version is named equal\_to\_numbers and returns an array of two numbers, one for bit values 1 and the other for bit values 0).
92
+
93
+ * Warning: Although bitwise operations are fast, when using this class, you need to be careful when you use lots of bits (more than 20) to return arrays because memory usage grows exponentially! 2**20 is over 1 million, that's 8 megabytes of memory for the array on a 64-bit OS, with 24 bits, it explodes to 134 megabytes!
94
+
95
+ Example:
96
+
97
+ ```ruby
98
+ gen = BitMagic::BitsGenerator.new({:is_odd => 0, :count => [1, 2, 3], :is_cool => 4})
99
+ gen.bits_for(:is_cool, :count)
100
+ # => [4, 1, 2, 3]
101
+ gen.any_of_number(:is_odd, :is_cool)
102
+ # => 17 # 10001 (4th bit for is_cool=1, 0th bit for is_odd=1)
103
+ gen.any_of(:is_odd, :is_cool) # same as gen.with_any(0, 4)
104
+ # => [1, 16, 3, 5, 9, 17, 18, 20, 24, 7, 11, 19, 13, 21, 25, 22, 26, 28, 15, 23, 27, 29, 30, 31]
105
+ # or some variation of the above, the order of the numbers is not guaranteed!
106
+ # you can #sort the array if you need well-defined ordering
107
+ gen.all_of(:is_odd, :count)
108
+ # => [15, 31]
109
+ # only available choices are 15 (is_cool = false) and 31 (is_cool = true)
110
+ gen.equal_to(:count => 5)
111
+
112
+ ```
113
+
114
+ ### Integrations
115
+
116
+ Integrations inject bit\_magic functionality into your ORM. ActiveRecord and Mongoid are supported and built-in. It's easy to build your own.
117
+
118
+ The built-in integrations add a class method, `bit_magic` to the class that it's included in. You call this method to define your integration name and flag bits on the model, and it becomes available as additional scopes for querying and instance methods.
119
+
120
+ | Config | What it does |
121
+ |------------------ | --------------------- |
122
+ | :bool_caster | a proc/lambda to use to cast input as a boolean. default varies by adapter |
123
+ | :named_scopes | add extra named scopes for querying individual fields. default: true |
124
+ | :query\_by\_value | decides whether to query by value (arrays of individual values) or by bitwise operation. Can be true, false, or an integer. If it's an integer, it will use by value if the total bits defined is less than that value. default: 8 |
125
+ | :default | the default value. default: 0 |
126
+ | :helpers | add extra helper methods to read fields. default: true |
127
+ | :attribute\_name | name of the method that returns the integer to use as the fields container. default: 'flags' |
128
+ | :column\_name | (ActiveRecord only) name of the column. default: same as attribute\_name |
129
+ | :updater | proc that sets the new value for the integer used as the fields container, receives instance as an argument. default: calls '#attribute_name=(value)' |
130
+
131
+ Example:
132
+
133
+ ```ruby
134
+ class YourModel
135
+ bit_magic :settings, 0 => :notify, [1, 2, 3] => :max_backlog, 4 => :disabled, :default => 0, :attribute_name => 'settings_flags'
136
+ end
137
+ ```
138
+
139
+ You must have an integer column, field, or attribute in the table to use as the bit field container. By default, we assume it is named `flags`, you can change it with `:attribute_name => 'some_other_attribute'`. It also must be a different name than the `bit_magic :name`
140
+
141
+ Note: bits are zero-indexed, LSB first
142
+
143
+ Warning: because you are setting bits to have specific meanings, you can not change their meaning in the code without also doing a migration in the database. You can add new fields all you want, change the name, or even add additional bits to arrays of bit fields, but avoid changing one bit to have a different meaning and don't remove it from the list once defined.
144
+
145
+ The bit field definition above will define methods based on the name given. For example, with the definition above, where the name is `:settings`, the following methods are defined:
146
+
147
+ * Class Methods:
148
+ * YourModel.settings\_with\_any(*field\_names)
149
+ returns a query where at least one of the listed fields are set to true
150
+ This is equivalent to the conditional: `field[0] or field[1] or field[2] ...`
151
+ * YourModel.settings\_with\_all(*field\_names)
152
+ returns a query where all of the listed fields are set to true
153
+ This is equivalent to the conditional: `field[0] and field[1] and field[2] ...`
154
+ * YourModel.settings\_without\_any(*field\_names)
155
+ returns a query where at least one of the listed fields are not set (set to false)
156
+ This is equivalent to the conditional: `!field[0] or !field[1] or !field[2] ...`
157
+ * YourModel.settings\_without\_all(*field\_names)
158
+ returns a query where all of the listed fields are not set (set to false)
159
+ This is equivalent to the conditional: `!field[0] and !field[1] and !field[2] ...`
160
+ * YourModel.settings\_equals(field\_value\_list)
161
+ takes a Hash of `field_name => value` key-pairs, and returns a query where
162
+ the value of the bits of field\_name is equal to value (after truncating to
163
+ total bits in the field)
164
+ This is equivalent to the conditional: `field[0] = value[0] and field[1] = value[1] ...`
165
+ * YourModel.settings\_notify [1]
166
+ shorthand for `settings\_with\_all(:notify)`
167
+ * YourModel.settings\_not\_notify [1]
168
+ shorthand for `settings\_without\_all(:notify)`
169
+ * YourModel.settings\_max\_backlog [1]
170
+ shorthand for `settings\_with\_all(:max\_backlog)`
171
+ note that because this is a field with 3 bits, it's equivalent to max\_backlog=4
172
+ * YourModel.settings\_not\_max\_backlog [1]
173
+ shorthand for `settings\_without\_all(:max\_backlog)`
174
+ * YourModel.settings\_max\_backlog\_equals(val) [1]
175
+ returns a query where max\_backlog equals the value. Note: Only compares bit up to 3 bits because that's how big max_backlog is.
176
+ * YourModel.settings\_disabled [1] - shorthand for `settings\_with\_all(:disabled)`
177
+ * YourModel.settings\_not\_disabled [1] - shorthand for `settings\_without\_all(:disabled)`
178
+ * Instance Methods
179
+ * YourModel#settings - returns a Bits object for you to work with fields directly
180
+ * YourModel#settings\_enabled?(\*field\_names) - shorthand for `settings.enabled?(\*field\_names)`
181
+ * YourModel#settings\_disabled?(\*field\_names) - shorthand for `settings.disabled?(\*field\_names)`
182
+ * YourModel#notify [2] - returns 1 or 0, shorthand for `settings.read(:notify)`
183
+ * YourModel#notify? [2] - returns true or false, shorthand for `settings.read(:notify) == 1`
184
+ * YourModel#notify=(val) [2] - sets value for notify flag, shorthand for `settings.write(:notify, val)`
185
+ * YourModel#max\_backlog [2] - returns a number from 0 to 7 (3 bits), shorthand for `settings.read(:max_backlog)`
186
+ * YourModel#max\_backlog=(val) [2]
187
+ sets value for max\_backlog, only cares about the last 3 bits, so numbers larger than 3 bits are truncated.
188
+ shorthand for `settings.write(:max\_backlog, val)`
189
+ * YourModel#disabled [2] - returns 1 or 0, shorthand for `settings.read(:disabled)`
190
+ * YourModel#disabled? [2] - returns true or false, shorthand for `settings.read(:disabled) == 1`
191
+ * YourModel#disabled=(val) [2] - sets value for disabled
192
+
193
+ [1] You can disable these by adding `:named_scope => false` to the bit\_magic options.
194
+ [2] You can disable these by adding `:helpers => false` to the bit\_magic options.
195
+
196
+ #### Ruby on Rails
197
+
198
+ All official stable, maintained versions of Rails are supported. We include a railtie to activate integration seamlessly.
199
+
200
+ In your Gemfile, change the gem line to add the require railtie like below.
201
+
202
+ ```ruby
203
+ gem 'bit_magic', require: 'bit_magic/railtie'
204
+ ```
205
+
206
+ It will activate the ActiveRecord and/or Mongoid adapters globally if it finds it. You do not need to include the adapters as specified below if you go this route.
207
+
208
+ #### ActiveRecord
209
+
210
+ To make bit\_magic available to all your models, include the adapter into the Base class. This is done automatically if you are using the Rails integration as defined above.
211
+
212
+ ```ruby
213
+ require 'bit_magic/adapters/active_record_adapter'
214
+ ActiveRecord::Base.include BitMagic::Adapters::ActiveRecordAdapter
215
+ ```
216
+
217
+ Otherwise, you'll need to include it on every model where you want to use bit_magic:
218
+
219
+ ```ruby
220
+ class YourModel < ActiveRecord::Base
221
+ # the include below can be removed if activated globally above
222
+ include BitMagic::Adapters::ActiveRecordAdapter
223
+
224
+ # this defines the bits we will be using for our bitfield.
225
+ # total usable bits is based off what int you are using in the database.
226
+ bit_magic :example, 0 => :is_odd, 1 => :one, 2 => :two, 3 => :wiggle, [4, 5, 6] => :my_shoe
227
+ end
228
+ ```
229
+
230
+ You must have an integer column or attribute in the table to use as the bit field container. By default, we assume the column is named `flags`. It should be `NOT NULL` and have a default set.
231
+
232
+ After defining `bit_magic :name`, you can use the methods signature described above.
233
+
234
+ #### Mongoid
235
+
236
+ To make bit\_magic available to all your models, include the adapter into the Document module. This is done automatically if you are using the Rails integration as defined above.
237
+
238
+ ```ruby
239
+ require 'bit_magic/adapters/mongoid_adapter'
240
+ Mongoid::Document.include BitMagic::Adapters::MongoidAdapter
241
+ ```
242
+
243
+ Otherwise, you'll need to include it on every model where you want to use bit_magic:
244
+
245
+ ```ruby
246
+ class YourModel
247
+ include Mongoid::Document
248
+
249
+ # the include below can be removed if activated globally above
250
+ include BitMagic::Adapters::MongoidAdapter
251
+
252
+ # this defines the bits we will be using for our bitfield.
253
+ bit_magic :example, 0 => :is_odd, 1 => :one, 2 => :two, 3 => :wiggle, [4, 5, 6] => :my_shoe
254
+ field :flags, type: Integer, default: 0
255
+ end
256
+ ```
257
+
258
+ You must have an integer field or attribute in the table to use as the bit field container. By default, we assume the column is named `flags`.
259
+
260
+ ### Custom Integrations
261
+
262
+ You can make your own custom adapter for your own use-case. At its core, all integrations boil down to:
263
+
264
+ 1. defining custom defaults via a class method `bit_magic_adapter_defaults(options)`
265
+ 2. injecting base adapter functionality with `extend BitMagic::Adapters::Base`
266
+ 3. injection of querying functionality via a class method `bit_magic_adapter(name)`
267
+
268
+ TODO: Better documentation on the process. In the meantime, you can look at the source for the ActiveRecord and Mongoid adapters for examples.
269
+
270
+ ## Development
271
+
272
+ 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.
273
+
274
+ 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).
275
+
276
+ Adapters will need separate gems to be installed if you want to run them. ActiveRecordAdapter needs sqlite3 and activerecord. MongoidAdapter needs mongoid and a running Mongodb server. RailsAdapter needs rails (duh?). You can run them directly with `ruby [testfile]` to avoid bundler restricting the list to specifically bundled gems.
277
+
278
+ TODO: Define separate Gemfiles for adapter tests.
279
+
280
+ ## Contributing
281
+
282
+ Bug reports and pull requests are welcome on GitHub at https://github.com/userhello/bit_magic. 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.
283
+
284
+ ## License
285
+
286
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
287
+
288
+ ## Code of Conduct
289
+
290
+ Everyone interacting in the BitMagic project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/userhello/bit_magic/blob/master/CODE_OF_CONDUCT.md).