opus icon indicating copy to clipboard operation
opus copied to clipboard

Add an accessor pattern

Open sitch opened this issue 4 years ago • 2 comments

I find often times I'm just folding a map, and most of the code ends up just being getting a key out of the map and then passing it to some validation/execution function

Current behavior

defmodule MyOpus do
  use Opus.Pipeline
  
  check :valid_email?

  def valid_email?(%{email: email}) when is_binary(email) do
    MyValidator.valid_email?(email)
  end
end

Useful/Dry behavior

defmodule MyOpus do
  use Opus.Pipeline
  import MyValidator, only: [valid_email?: 1]
  
  # some accessor/getter/lens syntax
  check :valid_email?, in: :email
  # or
  check :valid_email?, get_in: [:email]
  # or
  check {:email, :valid_email?}
end

sitch avatar Dec 16 '20 22:12 sitch

Hi @sitch, thank you for using Opus.

Have you tried?

defmodule MyOpus do
  use Opus.Pipeline

  import MyValidator, only: [valid_email?: 1]

  check :valid_email?, with: &valid_email?(&1.email)
end

zorbash avatar Dec 17 '20 14:12 zorbash

Yes of course, but my general use case is:

  1. Pass initial context as a map
  2. Run a step
  3. if it returns {:ok, map} then merge it into the current context

So what ends up happening is:

  • Map.merge ceremony
  • :ok tuple ceremony
  • extracting key-values to pass to a function like that valid_email?

sitch avatar Jan 07 '21 18:01 sitch