2017-03-25 5 views
0

Ich habe mein eigenes Steckermodul:Erstellen fast exakt die gleichen 2-Stecker, aber etwas anders

defmodule Module1 do 

    def init(opts) do 
    opts 
    end 

    def call(conn, _opts) do 
    # if some_condition1 
    # something 
    end 

    # other stuff 
end 

Und in router.ex

pipeline :pipeline1 do 
    plug(Module1) 
    end 

    scope "/scope", MyApp, as: :scope1 do 
    pipe_through([:browser, :pipeline1]) 
    # ....... 

Jetzt möchte ich eine zweite Pipeline und Umfang schaffen mit dem gleichen Modul Module1:

pipeline :pipeline2 do 
    plug(Module1) 
    end 

    scope "/scope2", MyApp, as: :scope2 do 
    pipe_through([:browser, :pipeline2]) 
    # ....... 

Allerdings, wenn ich ein zweites Modul erstellen, wäre der Unterschied nur in diesem:

def call(conn, _opts) do 
    # if some_condition1 and some_condition2 
    # something 
    end 

Das heißt, ich habe nur hinzugefügt „some_condition2“, und alles andere bleibt gleich.

Nun, wie kann ich das tun? Muss ich genau das gleiche Modul Module2 wie Module1 erstellen und nur leicht "Call" ändern? Dies führt zur Code-Duplizierung.

Antwort

7

Dies ist, was die opts in Plug gemeint ist. Sie können es von Ihrem plug Anruf übergeben und dann verwenden, innen call:

pipeline :pipeline1 do 
    plug Module1, check_both: false 
end 

pipeline :pipeline2 do 
    plug Module1, check_both: true 
end 
defmodule Module1 do 
    def init(opts), do: opts 

    def call(conn, opts) do 
    if opts[:check_both] do 
     # if some_condition1 and some_condition2 do something... 
    else 
     # if some_condition1 do something... 
    end 
    end 
end 

Jetzt in pipeline1, opts[:check_both] falsch sein, und in pipeline2, wird es wahr sein.


Ich bin hier, um eine Keyword-Liste vorbei, aber man kann alles passieren, auch nur einen einzigen true oder false ob das genug ist (das sollte ein wenig schneller sein als Schlüsselwort als auch Listen). Sie können auch eine Vorverarbeitung mit opts in init/1 durchführen. Im Moment gibt es nur den Anfangswert zurück.

Verwandte Themen