pipe_into_anonymous_functions.ex (1409B)
1 defmodule Credo.Check.Readability.PipeIntoAnonymousFunctions do 2 use Credo.Check, 3 base_priority: :low, 4 explanations: [ 5 check: """ 6 Avoid piping into anonymous functions. 7 8 The code in this example ... 9 10 def my_fun(foo) do 11 foo 12 |> (fn i -> i * 2 end).() 13 |> my_other_fun() 14 end 15 16 ... should be refactored to define a private function: 17 18 def my_fun(foo) do 19 foo 20 |> times_2() 21 |> my_other_fun() 22 end 23 24 defp timex_2(i), do: i * 2 25 26 Like all `Readability` issues, this one is not a technical concern. 27 But you can improve the odds of others reading and liking your code by making 28 it easier to follow. 29 """ 30 ] 31 32 @impl true 33 def run(source_file, params \\ []) do 34 issue_meta = IssueMeta.for(source_file, params) 35 36 Credo.Code.prewalk(source_file, &traverse(&1, &2, issue_meta)) 37 end 38 39 defp traverse( 40 {:|>, meta, [_, {{:., _, [{:fn, _, _} | _]}, _, _}]} = ast, 41 issues, 42 issue_meta 43 ) do 44 {ast, [issue_for(issue_meta, meta[:line]) | issues]} 45 end 46 47 defp traverse(ast, issues, _) do 48 {ast, issues} 49 end 50 51 defp issue_for(issue_meta, line_no) do 52 format_issue( 53 issue_meta, 54 message: "Avoid piping into anonymous function calls", 55 trigger: "|>", 56 line_no: line_no 57 ) 58 end 59 end