vp-heimdall 0.1.1

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: afa14f68e897944a552060844aa714985c5b7da3985bdd312a89b2cf2613af2d
4
+ data.tar.gz: 352e939bc7428fba6151e32bb62a1130fac385e012a36d1da1a972e77dc214df
5
+ SHA512:
6
+ metadata.gz: b7ce20618dd28fa3d784115aa64f0580250eff38461c935a6d6ac8e2084e5f9ac56fb7d1905077326c10e055e85b049588491ade6701549d1103540acb2c9577
7
+ data.tar.gz: 50be617513919573038a056399decae6bfa00041f78edd9afc75f12998e1c44503b7508b6160f71f8f64183c0db78cb23e8e5caf3ea4e7468bcd418a5118b8b2
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,22 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.0
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
14
+
15
+ Metrics/MethodLength:
16
+ Max: 15
17
+
18
+ Metrics/AbcSize:
19
+ Max: 10
20
+
21
+ Metrics/BlockLength:
22
+ Max: 100
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-01-06
4
+
5
+ - Initial release
@@ -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 hari@volopay.co. 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/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 hari-prasad-01
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,117 @@
1
+ # Heimdall
2
+
3
+ Heimdall is a simple feature gate library that provides a mechanism to control access to features in your application. It uses a tree structure to represent feature flags and allows you to build and manage feature trees from templates. The library also includes access control checks to ensure that only authorized users can access certain features.
4
+
5
+ ## Features
6
+
7
+ - Define and manage feature flags using a tree structure.
8
+ - Build feature trees from JSON templates.
9
+ - Perform access control checks based on feature flags.
10
+
11
+ ## Installation
12
+
13
+ Add this line to your application's Gemfile:
14
+
15
+ ```ruby
16
+ gem 'heimdall'
17
+ ```
18
+
19
+ And then execute:
20
+
21
+ ```bash
22
+ bundle install
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ ```ruby
28
+ rails generate heimdall:install <NameOfClass> --prefix=[feature|feature_template] --type=[all|model|controller|migration] --path=<path of the controller>
29
+ ```
30
+
31
+ 1) To install feature artifacts
32
+
33
+ ```ruby
34
+ rails generate heimdall:install Feature --prefix=feature --type=all
35
+ ```
36
+
37
+ 2) To install feature Template artifacts
38
+
39
+ ```ruby
40
+ rails generate heimdall:install FeatureTemplate --prefix=feature_template --type=all
41
+ ```
42
+
43
+ 3) add Heimdall in your application controller
44
+
45
+ ```ruby
46
+ class ApplicationController < ActionController::API
47
+ include Heimdall
48
+ end
49
+ ```
50
+
51
+ `Note: It is recommended to install templates in public schema if you are using multi-tenancy.`
52
+
53
+ ### Some of the good practices
54
+
55
+ 1. keep feature name as `snake_case` and `singular` form. if a feature is sub-feature like google_login of user then it should be `user.google_login`.
56
+ eg:
57
+
58
+ ```ruby
59
+ feature_names:[`profile_enabled`, `user.security.google_login_enabled`]
60
+ ```
61
+
62
+ 2. those features can we checked or accessed via
63
+
64
+ ```ruby
65
+ Feature.user_security_google_login_enabled?
66
+ ```
67
+
68
+ 3. if you want to check feature on controller. then you can create something like runes
69
+
70
+ eg: we need to have `UsersRune` for `UsersController`
71
+
72
+ if controller structure is considered to be this
73
+
74
+ ```ruby
75
+ class UsersController < ApplicationController
76
+ before_action only: [:google_login_link] do
77
+ worthy? params[:action] #, UsersRune (optional rune class name if used unconventionally)
78
+ end
79
+
80
+ # some code
81
+ def google_login_link
82
+ # generate_login_url
83
+ end
84
+ end
85
+ ```
86
+
87
+ then rune structure should be
88
+
89
+ ```ruby
90
+ class UsersRune
91
+ def google_login_link?
92
+ Feature.user_security_google_login_enabled?
93
+ end
94
+ end
95
+ ```
96
+
97
+ 4. It can be directly used in serializer/jobs
98
+
99
+ 5. To maintain `Singe Responsibility Principle`, it is recommended to use runes for controllers and jobs. Try not to use in business logic like either in model or service functions.
100
+
101
+ ## Development
102
+
103
+ 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.
104
+
105
+ 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).
106
+
107
+ ## Contributing
108
+
109
+ Bug reports and pull requests are welcome on GitHub at <https://github.com/volopay/heimdall>. 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/volopay/heimdall/blob/master/CODE_OF_CONDUCT.md).
110
+
111
+ ## License
112
+
113
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
114
+
115
+ ## Code of Conduct
116
+
117
+ Everyone interacting in the Heimdall project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/heimdall/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/heimdall.gemspec ADDED
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/heimdall/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "vp-heimdall"
7
+ spec.version = Heimdall::VERSION
8
+ spec.authors = ["hari-prasad-01"]
9
+ spec.email = ["hari@volopay.co"]
10
+
11
+ spec.summary = "Write a short summary, because RubyGems requires one."
12
+ spec.description = "Write a longer description or delete this line."
13
+ spec.homepage = "https://github.com/volopay/heimdall"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 3.0.0"
16
+
17
+ # spec.metadata["allowed_push_host"] = "https://volopay.com"
18
+
19
+ spec.metadata["homepage_uri"] = spec.homepage
20
+ spec.metadata["source_code_uri"] = "https://github.com/volopay/heimdall"
21
+ spec.metadata["changelog_uri"] = "https://github.com/Volopay/Heimdall/CHANGELOG.md"
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(__dir__) do
26
+ `git ls-files -z`.split("\x0").reject do |f|
27
+ (File.expand_path(f) == __FILE__) ||
28
+ f.start_with?(*%w[bin/ test/ spec/ features/ .git appveyor Gemfile])
29
+ end
30
+ end
31
+ spec.bindir = "exe"
32
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
33
+ spec.require_paths = ["lib"]
34
+
35
+ # Uncomment to register a new dependency of your gem
36
+ # spec.add_dependency "example-gem", "~> 1.0"
37
+
38
+ # For more information and examples about making a new gem, check out our
39
+ # guide at: https://bundler.io/guides/creating_gem.html
40
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Access Denied Exception
4
+ #
5
+ # This exception is raised when a user tries to access a resource they don't have permission to access.
6
+ #
7
+ class AccessDeniedError < StandardError
8
+ def initialize(options = {}) # rubocop:disable Metrics/AbcSize
9
+ message = options[:message]
10
+ query = options[:query].to_s.gsub(/[^\w]*/, '')
11
+ klass = options[:klass].to_s
12
+
13
+ # message = "Access Denied to access #{query} from #{klass}" if message.nil? && query.present? && klass.present? && (Rails.env.development? || Rails.env.test?)
14
+ message ||= "Access Denied"
15
+
16
+ super(message)
17
+ end
18
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators"
4
+ require "rails/generators/migration"
5
+ require_relative "migration_helper"
6
+ require "active_record"
7
+ require "rails/generators/active_record"
8
+ require "rails/generators/active_record/model/model_generator"
9
+
10
+ module Heimdall
11
+ module Generators
12
+ # https://guides.rubyonrails.org/generators.html
13
+ class InstallGenerator < Rails::Generators::NamedBase
14
+ include Rails::Generators::Migration
15
+ include Heimdall::Generators::MigrationHelper
16
+ extend Heimdall::Generators::MigrationHelper
17
+
18
+ source_root File.expand_path("templates", __dir__)
19
+
20
+ class_option :type, type: :string, default: "all",
21
+ desc: "Type of files to generate (model/migration/controller/all)"
22
+
23
+ class_option :prefix, type: :string, default: "feature",
24
+ desc: "Prefix for table and model names -- [feature, feature_template]"
25
+
26
+ class_option :path, type: :string, default: "",
27
+ desc: "Path to the controller file"
28
+
29
+ argument :attributes, type: :array, default: [], banner: "field:type field:type"
30
+
31
+ def generate_files
32
+ case options[:type].downcase
33
+ when "model"
34
+ create_model_file
35
+ when "migration"
36
+ create_migration_file
37
+ when "controller"
38
+ create_controller_file
39
+ when "route"
40
+ add_routes
41
+ else
42
+ create_model_file
43
+ create_migration_file
44
+ create_controller_file
45
+ end
46
+ end
47
+
48
+ private
49
+
50
+ def create_model_file
51
+ template "models/#{options[:prefix]}_model.rb.tt", File.join("app/models", class_path, "#{file_name}.rb")
52
+ end
53
+
54
+ def create_migration_file
55
+ migration_file_name = "create_#{file_name.pluralize}"
56
+ migration_template "migrations/#{migration_file_name}.erb", "db/migrate/#{migration_file_name}_table.rb"
57
+ end
58
+
59
+ def create_controller_file
60
+ template "controllers/#{options[:prefix]}_controller.rb.tt", File.join("app/controllers", options[:path], class_path, "#{file_name.pluralize}_controller.rb")
61
+ end
62
+
63
+ def add_routes
64
+ route "resources #{file_name.pluralize.to_sym}"
65
+ end
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Heimdall
4
+ module Generators
5
+ # methods used by all generators
6
+ module MigrationHelper
7
+ def migration_parent
8
+ "ActiveRecord::Migration[#{ActiveRecord::Migration.current_version}]"
9
+ end
10
+
11
+ def next_migration_number(dirname)
12
+ next_migration_number = current_migration_number(dirname) + 1
13
+ if timestamped_migrations?
14
+ [Time.now.utc.strftime("%Y%m%d%H%M%S"), "%.14d" % next_migration_number].max
15
+ else
16
+ "%.3d" % next_migration_number
17
+ end
18
+ end
19
+
20
+ private
21
+
22
+ def timestamped_migrations?
23
+ ::ActiveRecord.timestamped_migrations
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ # this is a sample controller. Feel free to modify and add your own methods
4
+ # NOTE: this controller is not protected by any authentication and it is not tested
5
+ # it is meant to be a template
6
+ # add routes of your own
7
+
8
+ class <%= class_name.pluralize %>Controller < ApplicationController
9
+ # GET current tree for the template given
10
+ def index
11
+ root = FeatureTree.build(template, flags)
12
+
13
+ return render json: root.as_json, status: :ok
14
+ end
15
+
16
+ # PUT update template
17
+ def update
18
+ FeatureTree.update(template, flags, *update_params)
19
+
20
+ return render json: 'flag got update successfully', status: :ok
21
+ end
22
+
23
+ private
24
+
25
+ def template
26
+ @template = <%= class_name %>Template.find(params[:template_id])
27
+ end
28
+
29
+ def flags
30
+ @flags = <%= class_name %>.current_config_json
31
+ end
32
+
33
+ def update_params
34
+ params.permit(*<%= class_name %>::UPDATE_ARGS)
35
+ end
36
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ # this is a sample controller. Feel free to modify and add your own methods
4
+ # NOTE: this controller is not protected by any authentication and it is not tested
5
+ # it is meant to be a template
6
+ # add routes of your own
7
+ class <%= class_name.pluralize %>Controller < ApplicationController
8
+ # POST create node in the template
9
+ def add_node
10
+ root = FeatureTree.add_node(root: template.tree, **add_node_params)
11
+ template.update!(config: root.as_json)
12
+
13
+ return render json: { message: 'Node added successfully' }, status: :ok
14
+ end
15
+
16
+ # DELETE delete a node from template
17
+ def delete_node
18
+ FeatureTree.remove_node(root: template.tree, key: params[:key])
19
+ template.update!(config: template.tree.as_json)
20
+
21
+ return render json: { message: 'Node deleted successfully' }, status: :ok
22
+ end
23
+
24
+ # POST create template
25
+ def create
26
+ @template = <%= class_name %>.new(create_params)
27
+
28
+ return render json: { message: 'Template created successfully' }, status: :ok if @template.save
29
+ end
30
+
31
+ # DELETE delete template
32
+ def destroy
33
+ template.destroy
34
+ return render json: { message: 'Template deleted successfully' }, status: :ok
35
+ end
36
+
37
+ # PUT update template
38
+ def update
39
+ template.update!(create_params)
40
+ return render json: { message: 'Template updated successfully' }, status: :ok
41
+ end
42
+
43
+ private
44
+
45
+ def add_node_params
46
+ params.permit(:key, :parent_key, :child_key)
47
+ end
48
+
49
+ def template
50
+ @template = <%= class_name %>.find(params[:id])
51
+ end
52
+
53
+ def create_params
54
+ params.permit(:name, :description, :active, config: [:key, :children])
55
+ end
56
+ end
@@ -0,0 +1,12 @@
1
+ class Create<%= class_name.pluralize %>Table < <%= migration_parent %>
2
+ def change
3
+ create_table :<%= file_name.pluralize %> do |t|
4
+ t.string :name, null: false
5
+ t.text :description
6
+ t.jsonb :config, default: {}
7
+ t.boolean :active, default: false
8
+
9
+ t.timestamps
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,19 @@
1
+ class Create<%= class_name.pluralize %>Table < <%= migration_parent %>
2
+ def change
3
+ create_table :<%= file_name.pluralize %> do |t|
4
+ t.string :key, null: false # uniq identifier for each flag
5
+ t.string :name, null: false # human readable name
6
+ t.string :value, null: false # value of the flag
7
+ t.string :description # brief description of the flag for internal purposes
8
+ t.string :options, array: true, default: [] # list of possible values for the flag
9
+ t.string :tags, array: true, default: [] # list of tags for the flag
10
+ t.timestamps
11
+
12
+ # add custom columns here
13
+ # t.boolean :customization, default: false
14
+ end
15
+
16
+ # adding unique index to key column for validation/ bulk upsert(constraint)
17
+ add_index :<%= file_name.pluralize %>, :key, unique: true
18
+ end
19
+ end
@@ -0,0 +1,42 @@
1
+ class <%= class_name %> < ActiveRecord::Base
2
+ UPDATE_ARGS = %i[value options tags]
3
+
4
+ class << self
5
+ # return current client flag config in json format
6
+ def current_config_json
7
+ flags = {}
8
+ <%= class_name %>.all.map do |feature|
9
+ flags[feature.key] = feature
10
+ end
11
+
12
+ flags
13
+ end
14
+
15
+ # return current client flag config in json format with key as camelized symboll
16
+ def feature_map
17
+ # need to cache it
18
+ feature_map = current_config_json.map { |k, v| [k.gsub('.', '_').to_sym, v] }
19
+ feature_map.to_h
20
+ end
21
+
22
+ def respond_to_missing?(meth, include_private = false)
23
+ if Feature.pluck(:key).map { |u| u.gsub('.', '_') }.include? meth.to_s.gsub('?', '').to_sym
24
+ meth = meth.to_s.gsub('?', '').to_sym
25
+ feature = Feature.find_by(key: meth)
26
+ feature.present? && feature.value
27
+ else
28
+ super
29
+ end
30
+ end
31
+
32
+ def method_missing(meth, *args, &block)
33
+ key = meth.to_s.gsub('?', '').to_sym
34
+
35
+ feature = feature_map[key]
36
+
37
+ super if feature.nil?
38
+
39
+ feature.present? && feature.value
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,18 @@
1
+ class <%= class_name %> < ActiveRecord::Base
2
+
3
+ # validations
4
+ validates :name, :config, presence: true
5
+
6
+ # scopes
7
+ scope :active, -> { where(active: true) }
8
+
9
+ # this method return the tree object for the template's config
10
+ def tree
11
+ FeatureTree.parse_template(self.config)
12
+ end
13
+
14
+ # archive the template
15
+ def archive!
16
+ update!(active: false)
17
+ end
18
+ end
@@ -0,0 +1,29 @@
1
+ module Heimdall
2
+ module RuneFinder
3
+ #
4
+ # rune_class
5
+ # This method will fetch the rune class for the given controller.
6
+ # note: for this it should be named same the controller.
7
+ # eg: ```
8
+ # UsersController --> UsersRune
9
+ # ```
10
+ # @param [string] klass - class of the controller/ rune
11
+ #
12
+ # @return [Class] - class of the Rune
13
+ #
14
+ def rune_class(klass)
15
+ klass ||= "#{fetch_controller}Rune"
16
+ klass = klass.is_a?(String) ? klass.safe_constantize : klass
17
+
18
+ raise "Couldn't find rune class" if klass.nil?
19
+
20
+ klass
21
+ end
22
+
23
+ private
24
+
25
+ def fetch_controller
26
+ self.class.name.split('::').last.gsub('Controller', '')
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Heimdall
4
+ VERSION = "0.1.1"
5
+ end
data/lib/heimdall.rb ADDED
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "heimdall/version"
4
+ require_relative "tree/feature_tree"
5
+ require_relative "errors/access_denied_error"
6
+ require_relative "heimdall/rune_finder"
7
+
8
+ # Heimdall is a simple feature gate library.
9
+ #
10
+ # Heimdall provides a mechanism to control access to features in your application.
11
+ # It uses a tree structure to represent feature flags and allows you to build and manage
12
+ # feature trees from templates. The library also includes access control checks to ensure
13
+ # that only authorized users can access certain features.
14
+ #
15
+ # ## Features
16
+ #
17
+ # - Define and manage feature flags using a tree structure.
18
+ # - Build feature trees from JSON templates.
19
+ # - Perform access control checks based on feature flags.
20
+ #
21
+ # ## Usage
22
+ #
23
+ # ```ruby
24
+ # # Define a policy class
25
+ # class MyPolicy
26
+ # def some_feature?
27
+ # # logic to check access
28
+ # end
29
+ # end
30
+ #
31
+ # # Check access to a feature
32
+ # Heimdall.check_access?(query: :some_feature?, klass: MyPolicy)
33
+ # ```
34
+ module Heimdall
35
+ include Heimdall::RuneFinder
36
+
37
+ class Error < StandardError; end
38
+
39
+ class << self
40
+
41
+ def worthy?(query:, klass:)
42
+ policy = klass.new
43
+ raise AccessDeniedError.new({ query: query, klass: klass }) unless policy.public_send(query)
44
+
45
+ true
46
+ end
47
+ end
48
+
49
+ protected
50
+
51
+ #
52
+ # worthy?
53
+ #
54
+ # @param [string] query - name of the function to check
55
+ # @param [string] klass - name of the class to check
56
+ #
57
+ # @return [boolean] - true if the query is worthy, otherwise throws AccessDeniedError
58
+ def worthy?(query, klass=nil)
59
+ query = "#{query}?"
60
+ klass = rune_class(klass)
61
+
62
+ Heimdall.worthy?(query: query, klass: klass)
63
+ end
64
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "tree"
4
+
5
+ # FeatureTree is a tree structure that represents the feature flags
6
+ # It is used to build the feature tree from the feature flag template
7
+ class FeatureTree < Tree
8
+ attr_accessor :id, :key, :name, :value, :options, :editable_by_admin, :editable_by_user, :tags, :children
9
+
10
+ class << self
11
+ #
12
+ # Build the tree with the given template
13
+ #
14
+ # @param [Tree] FeatureTemplate tree - config of feature template
15
+ # @param [json] flags - current flags from db
16
+ # @param [Proc] block(node) - block to execute
17
+ #
18
+ # @return [Tree] node - root of the tree
19
+ def build(template, flags, &block) # rubocop:disable Metrics/AbcSize,Lint/UnusedMethodArgument
20
+ traverse(template) do |node|
21
+ yield node if block_given?
22
+
23
+ node.id = flags[node.key].id
24
+ node.key = flags[node.key].key
25
+ node.value = flags[node.key].value
26
+ node.name = flags[node.key].name
27
+ node.options = flags[node.key].options
28
+ node.tags = flags[node.key].tags
29
+ end
30
+
31
+ template
32
+ end
33
+
34
+ #
35
+ # update the node/feature table
36
+ #
37
+ # @param [Tree] FeatureTemplate tree - config of feature template
38
+ # @param [json] flags - current flags from db
39
+ # @param [key] key - key from which the update should happen
40
+ # @param [update_args] update_args - key-value pairs to be updated
41
+ #
42
+ # @return nil
43
+ #
44
+ def update(template, flags, key:, update_args: {})
45
+ head = find(template, key)
46
+
47
+ raise TypeError, "Feature flag not found" unless head
48
+
49
+ traverse(head) do |node|
50
+ flags[node.key].update(**update_args)
51
+ end
52
+ end
53
+ end
54
+ end
data/lib/tree/tree.rb ADDED
@@ -0,0 +1,124 @@
1
+ # frozen_string_literal: true
2
+
3
+ # ## Tree
4
+ #
5
+ # A simple Tree node Abstract class.
6
+ # it has a key and a list of children
7
+ #
8
+ #
9
+ # ##### Purpose
10
+ #
11
+ # methods to traverse and find nodes
12
+ #
13
+ # ##### Example
14
+ #
15
+ # ```ruby
16
+ # node = Tree.new(1, children: [Tree.new(2), Tree.new(3)])
17
+ # node.key # => 1
18
+ # node.children # => [Tree.new(2), Tree.new(3)]
19
+ # ```
20
+ class Tree
21
+ attr_accessor :key, :children
22
+
23
+ def initialize(key, children: [])
24
+ @key = key
25
+ @children = children
26
+ end
27
+
28
+ class << self
29
+ # Traverse the tree and yield each node
30
+ # optional block to perform an action on each node
31
+ #
32
+ # @param [Tree] node - node of a Tree
33
+ # @param [Proc] &block - proc to execute client logic
34
+ #
35
+ # @return nil
36
+ def traverse(node, &block)
37
+ return nil unless node
38
+
39
+ yield node if block_given?
40
+
41
+ node.children&.map do |child|
42
+ traverse(child, &block)
43
+ end
44
+ end
45
+
46
+ # Find the node by key
47
+ #
48
+ # @param [Tree] node - root node
49
+ # @param [string] key - key to find the node
50
+ #
51
+ # @return [Tree] node - node with the key
52
+ #
53
+ def find(node, key, &block)
54
+ return nil unless node
55
+
56
+ return node if node.key == key
57
+
58
+ yield(node) if block_given?
59
+
60
+ node.children&.map do |child|
61
+ result = find(child, key, &block)
62
+ return result if result
63
+ end
64
+
65
+ nil
66
+ end
67
+
68
+ # add node to the tree
69
+ #
70
+ # @param [Tree] root - template's root node
71
+ # @param [string] key - key for the new node
72
+ # @param [string] parent_key - key for its parent node
73
+ # @param [string] children - key for its child node
74
+ #
75
+ # @return root - updated root node
76
+ def add_node(root:, key:, parent_key:, child_key: nil) # rubocop:disable Metrics/AbcSize
77
+ parent = find(root, parent_key)
78
+ child = find(root, child_key) if child_key
79
+ parent.children = parent.children&.delete_if { |c| c.key == child_key } if child_key
80
+ new_node = Tree.new(key, children: [child] || [])
81
+ parent.children ||= []
82
+ parent.children << new_node
83
+ root
84
+ end
85
+
86
+ #
87
+ # Remove node from the templates's root node
88
+ #
89
+ # @param [Tree] root - template's root node
90
+ # @param [string] key - key for the new node
91
+ #
92
+ # @return root - updated root node
93
+ #
94
+ def remove_node(root:, key:)
95
+ raise TypeError, 'Cannot delete root node' if root.key == key
96
+
97
+ node_to_delete = find(root, key)
98
+ raise TypeError, 'Cannot find the node to delete' unless node_to_delete
99
+
100
+ parent = parent(root, key)
101
+
102
+ parent.children.delete_if { |child| child.key == key }
103
+ root
104
+ end
105
+
106
+
107
+ def parse_template(json)
108
+ return nil unless json
109
+ children = json["children"]&.map do |child|
110
+ parse_template(child)
111
+ end
112
+
113
+ self.new(json["key"], children: children)
114
+ end
115
+
116
+ private
117
+
118
+ def parent(root, key)
119
+ return find(root, key) do |node|
120
+ return node if node&.children&.select{ |u| u.key == key }.present?
121
+ end
122
+ end
123
+ end
124
+ end
@@ -0,0 +1,4 @@
1
+ module Heimdall
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,69 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: vp-heimdall
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - hari-prasad-01
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2025-01-20 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Write a longer description or delete this line.
14
+ email:
15
+ - hari@volopay.co
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - ".rspec"
21
+ - ".rubocop.yml"
22
+ - CHANGELOG.md
23
+ - CODE_OF_CONDUCT.md
24
+ - LICENSE.txt
25
+ - README.md
26
+ - Rakefile
27
+ - heimdall.gemspec
28
+ - lib/errors/access_denied_error.rb
29
+ - lib/generators/heimdall/install_generator.rb
30
+ - lib/generators/heimdall/migration_helper.rb
31
+ - lib/generators/heimdall/templates/controllers/feature_controller.rb.tt
32
+ - lib/generators/heimdall/templates/controllers/feature_template_controller.rb.tt
33
+ - lib/generators/heimdall/templates/migrations/create_feature_templates.erb
34
+ - lib/generators/heimdall/templates/migrations/create_features.erb
35
+ - lib/generators/heimdall/templates/models/feature_model.rb.tt
36
+ - lib/generators/heimdall/templates/models/feature_template_model.rb.tt
37
+ - lib/heimdall.rb
38
+ - lib/heimdall/rune_finder.rb
39
+ - lib/heimdall/version.rb
40
+ - lib/tree/feature_tree.rb
41
+ - lib/tree/tree.rb
42
+ - sig/gate_keeper.rbs
43
+ homepage: https://github.com/volopay/heimdall
44
+ licenses:
45
+ - MIT
46
+ metadata:
47
+ homepage_uri: https://github.com/volopay/heimdall
48
+ source_code_uri: https://github.com/volopay/heimdall
49
+ changelog_uri: https://github.com/Volopay/Heimdall/CHANGELOG.md
50
+ post_install_message:
51
+ rdoc_options: []
52
+ require_paths:
53
+ - lib
54
+ required_ruby_version: !ruby/object:Gem::Requirement
55
+ requirements:
56
+ - - ">="
57
+ - !ruby/object:Gem::Version
58
+ version: 3.0.0
59
+ required_rubygems_version: !ruby/object:Gem::Requirement
60
+ requirements:
61
+ - - ">="
62
+ - !ruby/object:Gem::Version
63
+ version: '0'
64
+ requirements: []
65
+ rubygems_version: 3.5.6
66
+ signing_key:
67
+ specification_version: 4
68
+ summary: Write a short summary, because RubyGems requires one.
69
+ test_files: []