hissssst / pathex

Fastest tool to access data in Elixir

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

feature request: Delete op that succeeds even if path isn't found

ltd opened this issue · comments

I'd love for delete(struct,path) to have an option to always return struct, even if path wasn't found in struct.

I'm not sure if it's a new call, or an optional third param to delete() or pop().

Have you tried something like

def maybe_delete(struct, path) do
  case Pathex.delete(struct, path) do
    {:ok, result} -> result
    :error -> struct
  end
end

?

yes, I can wrap it. It's a common enough pattern (for me anyway), that I'd love for it to be built in so I don't have to carry around my own pathex helper library. maybe_delete is a good name.

Check this out

defmacro maybe({operation, meta, [object | tail]}) do
  [object_var] = Macro.generate_unique_arguments(1, __CALLER__.context)
  call = {operation, meta, [object_var | tail]}
  quote do
    unquote(object_var) = unquote(object)
    case unquote(call) do
      {:ok, result} -> result
      :error -> unquote(object_var)
    end
  end
end

With this you can write something like

maybe delete(structure, path)

Or even

maybe over(structure, path, fn x -> x + 1 end)

But not maybe view(structure, path)...


But I don't think that it is a right way. I mean, adding a function is not a hard part, but there can be a huge amount of functions with a lot of flavours. I am already providing two of them: "exception" style and "either" style. For example, elixir's Map module provides only version of delete and I think that's okay for Pathex to provide the same functionality

And writing something like your own macro/higher-order function is not difficult and it doesn't sacrifice readability. And having 3 different functions for doing one thing is not a good design. I think the right way is to provide tools, not solutions.

So, I'd suggest for you to

  1. Create MyProject.PathexCommon and import it everyewhere you need it.
  2. Use maybe macro from above.
  3. Create your own MyProject.PathexExtension where you'll add ability to import your helpers and Pathex within one use
  4. Fork Pathex and add anything you like. I can answer any questions about adding a verb into Pathex, because gen function there is not trivial

By the way, I have a Pathex.HTML project in development and I am thinking about creating Pathex.Language (this is not a final version of the name) which will have extra lenses and verbs for general nested structures, perhaps I'll add this delete there

Just noting, that elixir Map.delete always returns the struct even if the key wasn't present. Although it's a breaking change, maybe delete could return {:error, struct}.

Again, pathex is great. It has generally made wrangling deeply nested structures more readable while reducing overall number of lines of code.