Sha256: 348452a1b829dcab4af67d674b3fc14bfb8212061535df5bcd8f0c42b9d0a407

Contents?: true

Size: 1.29 KB

Versions: 2

Compression:

Stored size: 1.29 KB

Contents

# frozen_string_literal: true

module Rubanok
  module DSL
    # Adds `.map` method to Processor to define key-matching rules:
    #
    #   map :q do |q:|
    #    # this rule is activated iff "q" (or :q) param is present
    #    # the value is passed to the handler
    #   end
    module Mapping
      class Rule < Rubanok::Rule
        METHOD_PREFIX = "__map"

        private

        # prefix rule method name to avoid collisions
        def build_method_name
          "#{METHOD_PREFIX}#{super}"
        end
      end

      module ClassMethods
        def map(*fields, activate_on: fields, activate_always: false, ignore_empty_values: Rubanok.ignore_empty_values, filter_with: nil, &block)
          filter = filter_with

          if filter.is_a?(Symbol)
            respond_to?(filter) || raise(
              ArgumentError,
              "Unknown class method #{filter} for #{self}. " \
              "Make sure that a filter method is defined before the call to .map."
            )
            filter = method(filter)
          end

          rule = Rule.new(fields, activate_on: activate_on, activate_always: activate_always, ignore_empty_values: ignore_empty_values, filter_with: filter)

          define_method(rule.to_method_name, &block)

          add_rule rule
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rubanok-0.5.1 lib/rubanok/dsl/mapping.rb
rubanok-0.5.0 lib/rubanok/dsl/mapping.rb