Component v0.2.2 Component.Strategy.Global View Source

Implement a singleton (global) named service.

Usage

To create the service:

  • Create a module that implements the API you want. This API will be expressed as a set of public functions. Each function will automatically receive the current state in a variable (by default named state). There is not need to declare this as a parameter. (see why) If a function wants to change the state, it must end with a call to the set_state/2 or set_state_and_return function (which will have been imported into your module automatically).

    For this example, we'll call the module GlobalService.

  • Add the line use Common.Strategy.Global to the top of this module.

To consume the service:

  • Create an instance of the service with GlobalService.create(). You can pass initial state to the service as an optional parameter. This call returns a handle to this service instance, but you shouldn't use it.

  • Call the API functions in the service.

Example

defmodule KV do
  using Common.Strategy.Global, initial_state: %{}

  def get(name), do: state[name]
  def put(name, value) do
    set_state(Map.put(state, name, value)) do
      value
    end
  end
end

KV.create(%{ name: "Elixir" })
KV.put(:type, "language")
KV.get(:name)    # => "Elixir"
KV.get(:type)    # => "language"

Options

You can pass a keyword list to use Component.Strategy.Global:

  • initial_state: value

  • state_name: atom

    The default name for the state variable is (unimaginatively) state. Use state_name to override this. For example, you could change the previous example to use store for the state with:

    defmodule KV do

    using Component.Strategy.Global,
          initial_state: %{},
          state_name:    :store
    
    def get(name), do: store[name]
    def put(name, value) do
      set_state(Map.put(store, name, value)) do
        value
      end
    end

    end

  • service_name: atom

    The default name for the service is the name of the module that defines it. Use service_name: to change this.

  • show_code: boolean

    If truthy, dump a representation of the generated code to STDOUT during compilation.

Link to this section Summary

Link to this section Functions

Link to this function

args_without_state(args, options) View Source

Link to this function

args_without_state_or_defaults(args, options) View Source