Module: BitmaskEnum

Defined in:
lib/bitmask_enum.rb,
lib/bitmask_enum/errors.rb,
lib/bitmask_enum/options.rb,
lib/bitmask_enum/version.rb,
lib/bitmask_enum/attribute.rb,
lib/bitmask_enum/nil_handler.rb,
lib/bitmask_enum/eval_scripts.rb,
lib/bitmask_enum/conflict_checker.rb

Overview

Adds support for bitmask enum attributes to ActiveRecord models.

Defined Under Namespace

Modules: EvalScripts Classes: Attribute, BitmaskEnumInvalidError, BitmaskEnumMethodConflictError, ConflictChecker, NilHandler, Options

Constant Summary collapse

DEFAULT_BITMASK_ENUM_OPTIONS =
{
  flag_prefix: nil,
  flag_suffix: nil,
  nil_handling: :include,
  validate: true
}.freeze
NIL_HANDLING_OPTIONS =
[:include].freeze
VERSION =
'1.1.1'

Instance Method Summary collapse

Instance Method Details

#bitmask_enum(params) ⇒ Object

Defines a bitmask enum and constructs the magic methods and method overrides for handling it.

Parameters:

  • params (Hash)

    Hash with first key/value being the attribute name and an array of flags, the remaining keys being options.

    • ‘flag_prefix`: Symbol or string that prefixes all the created method names for flags joined with an underscore

    • ‘flag_suffix`: Symbol or string that suffixes all the created method names for flags joined with an underscore

    • ‘nil_handling`: Symbol or string signaling behaviour when handling nil attribute values. Options are:

      • ‘include`: Treat nil as 0 and include in queries, this is the default.

    • ‘validate`: Boolean to apply attribute validation. Attributes will validate that they are less than the number of flags squared (number of flags squared - 1 is the highest valid bitmask value). Defaults to `true`.

Raises:



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/bitmask_enum.rb', line 26

def bitmask_enum(params)
  validation_error = validate_params(params)
  raise BitmaskEnumInvalidError, validation_error if validation_error.present?

  attribute, flags = params.shift
  flags = flags.map(&:to_sym)
  options = params
  merged_options = DEFAULT_BITMASK_ENUM_OPTIONS.merge(options.symbolize_keys)

  Attribute.new(self, attribute, flags, merged_options, defined_bitmask_enum_methods).construct!
end