feature_flag v0.1.5 FeatureFlag

FeatureFlag provides a macro that allows for conditional branching at the function level via configuration values.

In other words, you can change what a function does at runtime by setting/modifying a config value.

Use Case

The goal of this library was to provide an elegant and consistent mechanism for changing what a function does depending on a value that can easily be modified (i.e. a configuration value).

This could very easily be done in plain Elixir via a simple case statement:

defmodule MyApp do
  def math(x, y) do
    case Application.fetch_env!(:my_app, :math) do
      :add -> x + y
      :multiply -> x * y
      :subtract x - y
    end
  end
end

There's nothing wrong with this approach, and really no need to reach for anything else.

However, the same code can be rewritten as such using FeatureFlag

defmodule MyApp do

def math(x, y), feature_flag do
  :add -> x + y
  :multiply -> x * y
  :subtract x - y
end

end

When called, each case will attempt to match on the current value of Application.fetch_env!(:feature_flag, {MyApp, :math, 2}).

Beyond removing a marginal amount of code, FeatureFlag provides a consistent interface for defining functions with config-based branching.

Link to this section Summary

Functions

The function that gets called when use FeatureFlag gets called.

A custom version of def that will wrap the function in the approriate conditional logic.

The same as FeatureFlag.def/3, but for private functions.

Returns the current feature flag value for the given function.

Sets feature flag value for the given function.

Link to this section Functions

Link to this macro

__using__(_)

(macro)
__using__([]) :: Macro.t()

The function that gets called when use FeatureFlag gets called.

It simply imports the def/3 macro.

Link to this macro

def(head, arg2, expr)

(macro)
def(Macro.t(), Macro.t(), Macro.t()) :: Macro.t() | no_return()

A custom version of def that will wrap the function in the approriate conditional logic.

Note: You must call Use FeatureFlag in a module before using this macro.

Example

defmodule MyApp do
  def math(x, y), feature_flag do
    :add -> x + y
    :multiply -> x * y
    :subtract x - y
  end
end

To have this function perform the :multiply procedure, you'd set the feature flag config value like so:

config :feature_flag, :flags, %{{MyApp, :math, 2} => :multiply}

Or you can use FeatureFlag.set/2

FeatureFlag.set({MyApp, :math, 2}, :multiply)
Link to this macro

defp(head, arg2, expr)

(macro)
defp(Macro.t(), Macro.t(), Macro.t()) :: Macro.t() | no_return()

The same as FeatureFlag.def/3, but for private functions.

Link to this function

get(mfa)

get(mfa()) :: term()

Returns the current feature flag value for the given function.

Link to this function

set(mfa, value)

set(mfa(), term()) :: :ok

Sets feature flag value for the given function.