bitwise_attributes 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 3d64d7b8f1ab83f3c86a41ae0a2c868f5d5f49599172e597e789484d7bb36834
4
+ data.tar.gz: c57864b2eb6228a95cc7ef390eb1054851682a2af0b3921eaf4cfaa0946b7d59
5
+ SHA512:
6
+ metadata.gz: 411acc6c6b0a0041191c603d213fe563d1c444e3921df4890c21016acc571b1c044ea6a898105f5eca0200551fdb2b3cc6fa7dcaf94a875e2a955a5dfdbf963a
7
+ data.tar.gz: 715f9fba193a68687e85a0bdf1f52df8f6260972ed9bb6353298c75ff5a24011e0f87a100b3addc262775e264b6ef6521273569982fd4c40a9b6c6a1464df92b
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,13 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.6
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
data/CHANGELOG.md ADDED
@@ -0,0 +1,19 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2026-07-05
4
+
5
+ ### Added
6
+ - `bitwise_attribute` DSL macro to declare bitwise flags on any ActiveRecord model
7
+ - Per-flag instance methods: `key_bit?`, `set_key_bit`, `unset_key_bit`
8
+ - Boolean getter/setter pair: `attr_key` and `attr_key=` (accepts truthy/falsy values)
9
+ - Dirty-tracking predicate: `was_previously_key_bit?`
10
+ - Bulk instance methods: `set_attr(*keys)` and `unset_attr(*keys)`
11
+ - `associated_attr` to retrieve all currently-set key names as an array
12
+ - `attr_values` and `attr_aliases` instance accessors for the mapping and alias hashes
13
+ - Class-level `extract_bitmask_keys(attr, integer)` to decode a raw integer into key names
14
+ - Class-level `decode_bitwise_values(attr, hash)` to decode a `{id => bitmask}` hash in bulk
15
+ - Query scopes: `with_attr`, `with_exact_attr`, `without_attr`
16
+ - `aliases:` keyword on `bitwise_attribute` to define alternative names for existing keys; aliases are resolved transparently in all scopes and bulk operations
17
+ - Inheritance support: subclasses receive a copy of the parent's bitwise attributes and aliases, and can extend or redefine them independently
18
+ - Requires Ruby >= 3.1.4 and Rails >= 6.1.7.3
19
+ - CI matrix covering Rails 6.1 / 7.0 / 7.1 / 7.2 on Ruby 3.1–3.3
data/CLAUDE.md ADDED
@@ -0,0 +1,79 @@
1
+ # CLAUDE.md
2
+
3
+ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
+
5
+ ## Commands
6
+
7
+ ```bash
8
+ # Install dependencies
9
+ bin/setup
10
+
11
+ # Run all tests and linter (default task)
12
+ bundle exec rake
13
+
14
+ # Run tests only
15
+ bundle exec rake spec
16
+
17
+ # Run a single spec file
18
+ bundle exec rspec spec/bitwise_attributes_spec.rb
19
+
20
+ # Run linter
21
+ bundle exec rake rubocop
22
+
23
+ # Open an interactive console with the gem loaded
24
+ bin/console
25
+
26
+ # Install gem locally
27
+ bundle exec rake install
28
+
29
+ # Release a new version (bumps version.rb, tags, pushes to RubyGems)
30
+ bundle exec rake release
31
+ ```
32
+
33
+ ## Architecture
34
+
35
+ This is a Ruby gem that adds **bitwise attribute management** to ActiveRecord models via an `ActiveSupport::Concern`.
36
+
37
+ ### How it works
38
+
39
+ A single integer column stores multiple boolean flags packed as bits. Each flag occupies one bit position (1, 2, 4, 8, …). Defining `bitwise_attribute :permissions, :read, :write, :admin` maps:
40
+ - `read` → bit 1
41
+ - `write` → bit 2
42
+ - `admin` → bit 4
43
+
44
+ ### Key files
45
+
46
+ - `lib/bitwise_attributes.rb` — Entry point. Includes `ActiveRecordExtension` into the `BitwiseAttributes` concern.
47
+ - `lib/bitwise_attributes/active_record_extension.rb` — All the logic: the `bitwise_attribute` DSL macro, dynamically generated instance methods, and ActiveRecord scopes.
48
+
49
+ ### Generated API (per-attribute `attr_name`, per-key `key`)
50
+
51
+ | Method / Scope | Purpose |
52
+ |---|---|
53
+ | `key_bit?` | Check if a specific bit is set |
54
+ | `set_key_bit` / `unset_key_bit` | Set or clear a single bit |
55
+ | `attr_name_key` / `attr_name_key=` | Boolean getter/setter (accepts truthy values) |
56
+ | `was_previously_key_bit?` | Dirty-tracking: was bit set before last save |
57
+ | `associated_attr_name` | Returns array of all currently-set key names |
58
+ | `set_attr_name(*keys)` / `unset_attr_name(*keys)` | Bulk OR-in / AND-NOT-out |
59
+ | `with_attr_name(keys)` | Scope: any of the given bits set |
60
+ | `with_exact_attr_name(keys)` | Scope: exactly these bits set |
61
+ | `without_attr_name(keys)` | Scope: none of the given bits set |
62
+
63
+ ### Aliases
64
+
65
+ The `aliases:` keyword lets you define alternative names that map to existing keys:
66
+
67
+ ```ruby
68
+ bitwise_attribute :flags, :feature_a, :feature_b, aliases: { fa: :feature_a }
69
+ ```
70
+
71
+ Aliases are resolved transparently in scopes and bulk set/unset operations.
72
+
73
+ ### Inheritance
74
+
75
+ `inherited` hook propagates `@bitwise_attributes` and `@bitwise_aliases` to subclasses via `dup`, so STI subclasses pick up parent definitions and can add their own.
76
+
77
+ ## RuboCop
78
+
79
+ Configured in `.rubocop.yml`: Ruby 2.6 target, double-quoted strings enforced, max line length 120.
@@ -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 mehboob.ali@7vals.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,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in bitwise_attributes.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+
12
+ gem "rubocop", "~> 1.21"
13
+
14
+ rails_version = ENV["RAILS_VERSION"]
15
+ gem "activerecord", *(rails_version ? ["~> #{rails_version}.0"] : [">= 6.1.7.3", "< 9"])
16
+ gem "sqlite3", ">= 1.4", "< 3"
data/Gemfile.lock ADDED
@@ -0,0 +1,102 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ bitwise_attributes (0.1.0)
5
+ activerecord (>= 6.1.7.3, < 9)
6
+ activesupport (>= 6.1.7.3, < 9)
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ activemodel (7.2.3.1)
12
+ activesupport (= 7.2.3.1)
13
+ activerecord (7.2.3.1)
14
+ activemodel (= 7.2.3.1)
15
+ activesupport (= 7.2.3.1)
16
+ timeout (>= 0.4.0)
17
+ activesupport (7.2.3.1)
18
+ base64
19
+ benchmark (>= 0.3)
20
+ bigdecimal
21
+ concurrent-ruby (~> 1.0, >= 1.3.1)
22
+ connection_pool (>= 2.2.5)
23
+ drb
24
+ i18n (>= 1.6, < 2)
25
+ logger (>= 1.4.2)
26
+ minitest (>= 5.1, < 6)
27
+ securerandom (>= 0.3)
28
+ tzinfo (~> 2.0, >= 2.0.5)
29
+ ast (2.4.3)
30
+ base64 (0.3.0)
31
+ benchmark (0.5.0)
32
+ bigdecimal (4.1.2)
33
+ concurrent-ruby (1.3.7)
34
+ connection_pool (2.5.5)
35
+ diff-lcs (1.6.2)
36
+ drb (2.2.3)
37
+ i18n (1.15.2)
38
+ concurrent-ruby (~> 1.0)
39
+ json (2.20.0)
40
+ language_server-protocol (3.17.0.6)
41
+ lint_roller (1.1.0)
42
+ logger (1.7.0)
43
+ minitest (5.27.0)
44
+ parallel (1.28.0)
45
+ parser (3.3.11.1)
46
+ ast (~> 2.4.1)
47
+ racc
48
+ prism (1.9.0)
49
+ racc (1.8.1)
50
+ rainbow (3.1.1)
51
+ rake (13.4.2)
52
+ regexp_parser (2.12.0)
53
+ rspec (3.13.2)
54
+ rspec-core (~> 3.13.0)
55
+ rspec-expectations (~> 3.13.0)
56
+ rspec-mocks (~> 3.13.0)
57
+ rspec-core (3.13.6)
58
+ rspec-support (~> 3.13.0)
59
+ rspec-expectations (3.13.5)
60
+ diff-lcs (>= 1.2.0, < 2.0)
61
+ rspec-support (~> 3.13.0)
62
+ rspec-mocks (3.13.8)
63
+ diff-lcs (>= 1.2.0, < 2.0)
64
+ rspec-support (~> 3.13.0)
65
+ rspec-support (3.13.7)
66
+ rubocop (1.88.1)
67
+ json (~> 2.3)
68
+ language_server-protocol (~> 3.17.0.2)
69
+ lint_roller (~> 1.1.0)
70
+ parallel (>= 1.10)
71
+ parser (>= 3.3.0.2)
72
+ rainbow (>= 2.2.2, < 4.0)
73
+ regexp_parser (>= 2.9.3, < 3.0)
74
+ rubocop-ast (>= 1.49.0, < 2.0)
75
+ ruby-progressbar (~> 1.7)
76
+ unicode-display_width (>= 2.4.0, < 4.0)
77
+ rubocop-ast (1.50.0)
78
+ parser (>= 3.3.7.2)
79
+ prism (~> 1.7)
80
+ ruby-progressbar (1.13.0)
81
+ securerandom (0.4.1)
82
+ sqlite3 (1.7.3-arm64-darwin)
83
+ timeout (0.6.1)
84
+ tzinfo (2.0.6)
85
+ concurrent-ruby (~> 1.0)
86
+ unicode-display_width (3.2.0)
87
+ unicode-emoji (~> 4.1)
88
+ unicode-emoji (4.2.0)
89
+
90
+ PLATFORMS
91
+ arm64-darwin-23
92
+
93
+ DEPENDENCIES
94
+ activerecord (>= 6.1.7.3, < 9)
95
+ bitwise_attributes!
96
+ rake (~> 13.0)
97
+ rspec (~> 3.0)
98
+ rubocop (~> 1.21)
99
+ sqlite3 (>= 1.4, < 3)
100
+
101
+ BUNDLED WITH
102
+ 2.4.8
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mehboob Ali
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) 2026 Mehboob Ali
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,138 @@
1
+ # BitwiseAttributes
2
+
3
+ Pack multiple boolean flags into a single integer column on an ActiveRecord model. Each flag occupies one bit, so you get cheap storage and fast bitwise SQL queries with no schema changes per new flag.
4
+
5
+ ## Installation
6
+
7
+ Add to your Gemfile:
8
+
9
+ ```ruby
10
+ gem "bitwise_attributes"
11
+ ```
12
+
13
+ Or install directly:
14
+
15
+ ```sh
16
+ gem install bitwise_attributes
17
+ ```
18
+
19
+ ## Requirements
20
+
21
+ - Ruby >= 3.1.4
22
+ - Rails (ActiveRecord) >= 6.1.7.3
23
+
24
+ ## Usage
25
+
26
+ ### Setup
27
+
28
+ Add an integer column to your table (default `0`, not null):
29
+
30
+ ```ruby
31
+ add_column :users, :permissions, :integer, null: false, default: 0
32
+ ```
33
+
34
+ Include the concern and declare your attribute:
35
+
36
+ ```ruby
37
+ class User < ApplicationRecord
38
+ include BitwiseAttributes
39
+
40
+ bitwise_attribute :permissions, :read, :write, :admin
41
+ end
42
+ ```
43
+
44
+ Keys are assigned bit positions in declaration order: `read` → 1, `write` → 2, `admin` → 4.
45
+
46
+ ### Per-flag methods
47
+
48
+ For each key the following methods are generated (shown for `read`):
49
+
50
+ ```ruby
51
+ user.read_bit? # => true / false
52
+ user.set_read_bit # sets the bit in memory
53
+ user.unset_read_bit # clears the bit in memory
54
+
55
+ user.permissions_read # alias for read_bit?
56
+ user.permissions_read = true # accepts any truthy/falsy value
57
+ user.permissions_read = false
58
+
59
+ user.was_previously_read_bit? # dirty-tracking: state before last save
60
+ ```
61
+
62
+ ### Bulk operations
63
+
64
+ ```ruby
65
+ user.set_permissions(:read, :admin) # OR-in multiple bits
66
+ user.unset_permissions(:write) # AND-NOT-out multiple bits
67
+
68
+ user.associated_permissions # => ["read", "admin"]
69
+ user.permissions_values # => {"read"=>1, "write"=>2, "admin"=>4}
70
+ ```
71
+
72
+ ### Scopes
73
+
74
+ ```ruby
75
+ User.with_permissions(:read) # any of the given bits set
76
+ User.with_permissions([:read, :write])
77
+
78
+ User.with_exact_permissions([:read, :write]) # ALL given bits set (superset)
79
+
80
+ User.without_permissions(:admin) # none of the given bits set
81
+ ```
82
+
83
+ ### Aliases
84
+
85
+ Map alternative names to existing keys:
86
+
87
+ ```ruby
88
+ bitwise_attribute :flags, :active, :verified, aliases: { confirmed: :verified }
89
+
90
+ user.set_flags(:confirmed) # sets :verified bit
91
+ User.with_flags(:confirmed) # same as with_flags(:verified)
92
+ ```
93
+
94
+ ### Class-level helpers
95
+
96
+ ```ruby
97
+ User.extract_bitmask_keys(:permissions, 5)
98
+ # => ["read", "admin"]
99
+
100
+ User.decode_bitwise_values(:permissions, { 1 => 3, 2 => 4 })
101
+ # => { 1 => ["read", "write"], 2 => ["admin"] }
102
+ ```
103
+
104
+ ### Inheritance
105
+
106
+ Subclasses inherit all bitwise attribute definitions from their parent. Each subclass gets its own independent copy, so adding or redefining an attribute on a subclass does not affect the parent.
107
+
108
+ ```ruby
109
+ class AdminUser < User
110
+ bitwise_attribute :permissions, :read, :write, :admin, :superadmin
111
+ end
112
+
113
+ AdminUser.bitwise_attributes[:permissions].keys # => [..., "superadmin"]
114
+ User.bitwise_attributes[:permissions].keys # unchanged
115
+ ```
116
+
117
+ ## Development
118
+
119
+ ```sh
120
+ bin/setup # install dependencies
121
+ bundle exec rake # run tests + rubocop
122
+ bundle exec rspec # tests only
123
+ bin/console # interactive prompt with the gem loaded
124
+ ```
125
+
126
+ To test against a specific Rails version:
127
+
128
+ ```sh
129
+ RAILS_VERSION=6.1 bundle install && bundle exec rake
130
+ ```
131
+
132
+ ## Contributing
133
+
134
+ Bug reports and pull requests are welcome on GitHub at https://github.com/mehboobali98/bitwise_attributes. Contributors are expected to adhere to the [code of conduct](https://github.com/mehboobali98/bitwise_attributes/blob/main/CODE_OF_CONDUCT.md).
135
+
136
+ ## License
137
+
138
+ Available as open source under the [MIT License](https://opensource.org/licenses/MIT).
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]
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/bitwise_attributes/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "bitwise_attributes"
7
+ spec.version = BitwiseAttributes::VERSION
8
+ spec.authors = ["Mehboob Ali"]
9
+ spec.email = ["mehboob.ali@7vals.com"]
10
+
11
+ spec.summary = "Store multiple boolean flags in a single integer column using bitwise operations."
12
+ spec.description = "BitwiseAttributes extends ActiveRecord models with a bitwise_attribute DSL that packs multiple boolean flags into a single integer column, generating per-flag getter/setter methods and query scopes automatically."
13
+ spec.homepage = "https://github.com/mehboobali98/bitwise_attributes"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 3.1.4"
16
+
17
+ spec.metadata["homepage_uri"] = spec.homepage
18
+ spec.metadata["source_code_uri"] = "https://github.com/mehboobali98/bitwise_attributes"
19
+
20
+ # Specify which files should be added to the gem when it is released.
21
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
22
+ spec.files = Dir.chdir(__dir__) do
23
+ `git ls-files -z`.split("\x0").reject do |f|
24
+ (File.expand_path(f) == __FILE__) || f.start_with?(*%w[bin/ test/ spec/ features/ .git .circleci appveyor])
25
+ end
26
+ end
27
+ spec.bindir = "exe"
28
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
29
+ spec.require_paths = ["lib"]
30
+
31
+ spec.add_dependency "activerecord", ">= 6.1.7.3", "< 9"
32
+ spec.add_dependency "activesupport", ">= 6.1.7.3", "< 9"
33
+
34
+ # For more information and examples about making a new gem, check out our
35
+ # guide at: https://bundler.io/guides/creating_gem.html
36
+ end
@@ -0,0 +1,155 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/concern"
4
+
5
+ module BitwiseAttributes
6
+ module ActiveRecordExtension
7
+ extend ActiveSupport::Concern
8
+
9
+ class_methods do
10
+ # Define a bitwise attribute and dynamically generate methods and scopes
11
+ def bitwise_attribute(attribute_name, *keys, aliases: {})
12
+ invalid_aliases = aliases.values - keys
13
+ raise ArgumentError, "Invalid aliases for #{attribute_name}: #{invalid_aliases}" if invalid_aliases.any?
14
+
15
+ bitwise_aliases[attribute_name] = aliases.with_indifferent_access.freeze
16
+ bitwise_attributes[attribute_name] = keys.map.with_index { |key, index| [key, 1 << index] }.to_h.with_indifferent_access.freeze
17
+ define_bitwise_methods(attribute_name, keys)
18
+ end
19
+
20
+ # Retrieve all defined bitwise aliases
21
+ def bitwise_aliases
22
+ @bitwise_aliases ||= Hash.new { |h, k| h[k] = {} }
23
+ end
24
+
25
+ # Retrieve all defined bitwise attributes
26
+ def bitwise_attributes
27
+ @bitwise_attributes ||= {}
28
+ end
29
+
30
+ # Ensure inheritance propagates bitwise attributes to subclasses
31
+ def inherited(subclass)
32
+ super
33
+
34
+ # Copy bitwise attributes to the subclass
35
+ subclass.instance_variable_set(:@bitwise_aliases, bitwise_aliases.dup)
36
+ subclass.instance_variable_set(:@bitwise_attributes, bitwise_attributes.dup)
37
+ end
38
+
39
+ def extract_bitmask_keys(attribute_name, attribute_value)
40
+ attribute_value = attribute_value.to_i
41
+ bitwise_attributes[attribute_name].filter { |_key, bit_value| attribute_value & bit_value == bit_value }.keys
42
+ end
43
+
44
+ def decode_bitwise_values(attribute_name, bitwise_hash)
45
+ bitwise_mapping = bitwise_attributes[attribute_name]
46
+ bitwise_hash.transform_values do |bitwise_value|
47
+ bitwise_mapping.select { |_key, bit| bitwise_value & bit == bit }.keys
48
+ end
49
+ end
50
+
51
+ private
52
+
53
+ # Dynamically define methods and scopes for a bitwise attribute
54
+ def define_bitwise_methods(attribute_name, keys)
55
+ # Define a method to return the bitwise mapping for this attribute
56
+ define_method(:"#{attribute_name}_values") do
57
+ self.class.bitwise_attributes[attribute_name]
58
+ end
59
+
60
+ define_method(:"#{attribute_name}_aliases") do
61
+ self.class.bitwise_aliases[attribute_name]
62
+ end
63
+
64
+ # Define methods for individual keys
65
+ keys.each do |key|
66
+ define_method(:"#{key}_bit?") do
67
+ bit_value = send(:"#{attribute_name}_values")[key]
68
+ (self[attribute_name] & bit_value) != 0
69
+ end
70
+
71
+ define_method(:"set_#{key}_bit") do
72
+ bit_value = send(:"#{attribute_name}_values")[key]
73
+ self[attribute_name] |= bit_value
74
+ end
75
+
76
+ define_method(:"unset_#{key}_bit") do
77
+ bit_value = send(:"#{attribute_name}_values")[key]
78
+ self[attribute_name] &= ~bit_value
79
+ end
80
+
81
+ define_method(:"#{attribute_name}_#{key}=") do |val|
82
+ send(ActiveModel::Type::Boolean.new.cast(val) ? :"set_#{key}_bit" : :"unset_#{key}_bit")
83
+ end
84
+
85
+ define_method(:"#{attribute_name}_#{key}") do
86
+ send(:"#{key}_bit?")
87
+ end
88
+
89
+ define_method(:"was_previously_#{key}_bit?") do
90
+ bit_value = send(:"#{attribute_name}_values")[key]
91
+ (attribute_previously_was(attribute_name) & bit_value) != 0
92
+ end
93
+ end
94
+
95
+ # Define helper methods for bulk operations
96
+ define_method(:"set_#{attribute_name}") do |*keys_to_add|
97
+ update_bitwise_attribute(attribute_name, keys_to_add, :add)
98
+ end
99
+
100
+ define_method(:"unset_#{attribute_name}") do |*keys_to_remove|
101
+ update_bitwise_attribute(attribute_name, keys_to_remove, :remove)
102
+ end
103
+
104
+ # Define method to retrieve associated keys
105
+ define_method(:"associated_#{attribute_name}") do
106
+ send(:"#{attribute_name}_values").reject { |_key, bit| (self[attribute_name] & bit).zero? }.keys
107
+ end
108
+
109
+ # Define dynamic scopes for filtering
110
+ scope :"with_#{attribute_name}", lambda { |bit_keys|
111
+ bitmask = model.send(:calculate_bitmask, attribute_name, bit_keys)
112
+ where("#{attribute_name} & ? != 0", bitmask)
113
+ }
114
+
115
+ scope :"with_exact_#{attribute_name}", lambda { |bit_keys|
116
+ bitmask = model.send(:calculate_bitmask, attribute_name, bit_keys)
117
+ where("#{attribute_name} & :bitmask = :bitmask", { bitmask: bitmask })
118
+ }
119
+
120
+ scope :"without_#{attribute_name}", lambda { |bit_keys|
121
+ bitmask = model.send(:calculate_bitmask, attribute_name, bit_keys)
122
+ where("#{attribute_name} & ? = 0", bitmask)
123
+ }
124
+ end
125
+
126
+ # Calculate the bitmask for given keys (now supports aliases)
127
+ def calculate_bitmask(attribute_name, keys)
128
+ valid_values = normalize_and_fetch_values(attribute_name, keys)
129
+ raise ArgumentError, "Invalid #{attribute_name}: #{keys}" if valid_values.include?(nil)
130
+
131
+ valid_values.sum
132
+ end
133
+
134
+ def normalize_and_fetch_values(attribute_name, keys)
135
+ alias_mappings = bitwise_aliases[attribute_name]
136
+ attribute_values = bitwise_attributes[attribute_name]
137
+
138
+ Array(keys).uniq.map { |key| attribute_values[alias_mappings.fetch(key, key)] }
139
+ end
140
+ end
141
+
142
+ # Update bitwise attributes for bulk add/remove operations
143
+ def update_bitwise_attribute(attribute_name, keys, operation)
144
+ valid_values = send(:normalize_and_fetch_values, attribute_name, keys)
145
+ raise ArgumentError, "Invalid #{attribute_name}: #{keys}" if valid_values.include?(nil)
146
+
147
+ bitmask = valid_values.sum
148
+ self[attribute_name] = operation == :add ? (self[attribute_name] | bitmask) : (self[attribute_name] & ~bitmask)
149
+ end
150
+
151
+ def normalize_and_fetch_values(attribute_name, keys)
152
+ self.class.send(:normalize_and_fetch_values, attribute_name, keys)
153
+ end
154
+ end
155
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module BitwiseAttributes
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/concern"
4
+ require "active_model/type"
5
+
6
+ require_relative "bitwise_attributes/version"
7
+ require_relative "bitwise_attributes/active_record_extension"
8
+
9
+ module BitwiseAttributes
10
+ extend ActiveSupport::Concern
11
+
12
+ include ActiveRecordExtension
13
+ end
@@ -0,0 +1,4 @@
1
+ module BitwiseAttributes
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,103 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: bitwise_attributes
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Mehboob Ali
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2026-07-05 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activerecord
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: 6.1.7.3
20
+ - - "<"
21
+ - !ruby/object:Gem::Version
22
+ version: '9'
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - ">="
28
+ - !ruby/object:Gem::Version
29
+ version: 6.1.7.3
30
+ - - "<"
31
+ - !ruby/object:Gem::Version
32
+ version: '9'
33
+ - !ruby/object:Gem::Dependency
34
+ name: activesupport
35
+ requirement: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: 6.1.7.3
40
+ - - "<"
41
+ - !ruby/object:Gem::Version
42
+ version: '9'
43
+ type: :runtime
44
+ prerelease: false
45
+ version_requirements: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: 6.1.7.3
50
+ - - "<"
51
+ - !ruby/object:Gem::Version
52
+ version: '9'
53
+ description: BitwiseAttributes extends ActiveRecord models with a bitwise_attribute
54
+ DSL that packs multiple boolean flags into a single integer column, generating per-flag
55
+ getter/setter methods and query scopes automatically.
56
+ email:
57
+ - mehboob.ali@7vals.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".rspec"
63
+ - ".rubocop.yml"
64
+ - CHANGELOG.md
65
+ - CLAUDE.md
66
+ - CODE_OF_CONDUCT.md
67
+ - Gemfile
68
+ - Gemfile.lock
69
+ - LICENSE
70
+ - LICENSE.txt
71
+ - README.md
72
+ - Rakefile
73
+ - bitwise_attributes.gemspec
74
+ - lib/bitwise_attributes.rb
75
+ - lib/bitwise_attributes/active_record_extension.rb
76
+ - lib/bitwise_attributes/version.rb
77
+ - sig/bitwise_attributes.rbs
78
+ homepage: https://github.com/mehboobali98/bitwise_attributes
79
+ licenses:
80
+ - MIT
81
+ metadata:
82
+ homepage_uri: https://github.com/mehboobali98/bitwise_attributes
83
+ source_code_uri: https://github.com/mehboobali98/bitwise_attributes
84
+ post_install_message:
85
+ rdoc_options: []
86
+ require_paths:
87
+ - lib
88
+ required_ruby_version: !ruby/object:Gem::Requirement
89
+ requirements:
90
+ - - ">="
91
+ - !ruby/object:Gem::Version
92
+ version: 3.1.4
93
+ required_rubygems_version: !ruby/object:Gem::Requirement
94
+ requirements:
95
+ - - ">="
96
+ - !ruby/object:Gem::Version
97
+ version: '0'
98
+ requirements: []
99
+ rubygems_version: 3.3.26
100
+ signing_key:
101
+ specification_version: 4
102
+ summary: Store multiple boolean flags in a single integer column using bitwise operations.
103
+ test_files: []