Sha256: fe6b346e759ebd58ad69cd0d43d2e1f1ae3223cda3db6442f3580c1fe71d289b

Contents?: true

Size: 1.67 KB

Versions: 7

Compression:

Stored size: 1.67 KB

Contents

module FlipFab
  class ContextualFeature
    attr_reader :feature, :context

    def initialize(feature, context)
      @feature = feature
      @context = context
      return unless overridden?

      @state = override
      persist
    end

    def as_json(options = {})
      {
        'feature' => feature.as_json(options)
      }
    end

    def enabled?
      state == :enabled
    end

    def disabled?
      !enabled?
    end

    def enable
      self.state = :enabled
    end

    def disable
      self.state = :disabled
    end

    def state=(value)
      raise "Invalid state provided: `#{value}`, possible states are :enabled, :disabled" unless %i[enabled disabled].include? value
      return if overridden?

      @state = value
      persist
    end

    def persist
      persistence_adapters.each { |adapter| adapter.write state }
    end

    private

    def persistence_adapters
      @persistence_adapters ||= feature.persistence_adapters.map { |adapter_class| adapter_class.new feature.name, context }
    end

    def state
      @state ||= state_in_context? ? state_from_context : default_state
    end

    def state_in_context?
      !first_adapter_with_state.nil?
    end

    def state_from_context
      first_adapter_with_state.read
    end

    def first_adapter_with_state
      persistence_adapters.detect { |adapter| !adapter.read.nil? }
    end

    def default_state
      feature.default
    end

    def override
      return unless context.respond_to? :params

      override = context.params[feature.name.to_s]
      return unless %w[enabled disabled].include? override

      override.to_sym
    end

    def overridden?
      !override.nil?
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
flip_fab-1.1.21 lib/flip_fab/contextual_feature.rb
flip_fab-1.1.20 lib/flip_fab/contextual_feature.rb
flip_fab-1.1.19 lib/flip_fab/contextual_feature.rb
flip_fab-1.1.18 lib/flip_fab/contextual_feature.rb
flip_fab-1.0.18 lib/flip_fab/contextual_feature.rb
flip_fab-1.0.17 lib/flip_fab/contextual_feature.rb
flip_fab-1.0.16 lib/flip_fab/contextual_feature.rb