File: setup_env.rb

package info (click to toggle)
ruby-flipper 0.13.0-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 4,824 kB
  • sloc: ruby: 13,183; sh: 54; makefile: 14
file content (45 lines) | stat: -rw-r--r-- 1,270 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
module Flipper
  module Middleware
    class SetupEnv
      # Public: Initializes an instance of the SetupEnv middleware. Allows for
      # lazy initialization of the flipper instance being set in the env by
      # providing a block.
      #
      # app - The app this middleware is included in.
      # flipper_or_block - The Flipper::DSL instance or a block that yields a
      #                    Flipper::DSL instance to use for all operations.
      #
      # Examples
      #
      #   flipper = Flipper.new(...)
      #
      #   # using with a normal flipper instance
      #   use Flipper::Middleware::SetupEnv, flipper
      #
      #   # using with a block that yields a flipper instance
      #   use Flipper::Middleware::SetupEnv, lambda { Flipper.new(...) }
      #
      def initialize(app, flipper_or_block, options = {})
        @app = app
        @env_key = options.fetch(:env_key, 'flipper')

        if flipper_or_block.respond_to?(:call)
          @flipper_block = flipper_or_block
        else
          @flipper = flipper_or_block
        end
      end

      def call(env)
        env[@env_key] ||= flipper
        @app.call(env)
      end

      private

      def flipper
        @flipper ||= @flipper_block.call
      end
    end
  end
end