Jeeves v0.1.0 Jeeves.Named

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.[why?]. If a function wants to change the state, it must end with a call to the Jeeves.Common.update_state/2 function (which will have been imported into your module automatically).

    For this example, we’ll call the module NamedService.

  • Add the line use Jeeves.Named to the top of this module.

To consume the service:

  • Create an instance of the service with NamedJeeves.run(). 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 Jeeves.Named, state: %{}

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

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

Options

You can pass a keyword list to use Jeeves.Anonymous:

  • 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 Jeeves.Named, state: %{}, state_name: :store
    
    def get(name), do: store[name]
    def put(name, value) do
      update_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.

  • showcode: boolean

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