0

I'm trying to take a bunch of lambdas that do the same thing and DRY them up by breaking it out in to a method. The code in question is in a module / class and I've forgotten the correct way to do this :/

The docs show an example like this using a lambda -

module Mutations
  class MyMutation < BaseMutation
    argument :name, String, required: true, prepare: -> (value, ctx) { value.strip! }
  end
end

I've tried -

module Mutations
  class MyMutation < BaseMutation
    argument :name, String, required: true, prepare: :no_whitespace

    def no_whitespace(value)
      value.strip!
    end
  end
end

But get a method not found on class error.

I also tried moving it to it's own module or class -

module Mutations
  class MyMutation < BaseMutation
    argument :name, String, required: true, prepare: Testing::no_whitespace
  end

  class Testing
    def no_whitespace(value)
      value.strip!
    end
  end 
end

I know it's something silly but I can't find the right combinations to get this working and my brain has forgotten too much Ruby to remember what to google.

1 Answers1

1

You could try defining no_whitespace as a module method e.g.

class Testing
  # since the example shows 2 arguments you need to be able 
  # to accept both even if you only use 1
  def self.no_whitespace(value,*_)
    value.strip!
  end
end 

then use

class MyMutation < BaseMutation
  argument :name, String, required: true, prepare: Testing.method(:no_whitespace)
end

Testing.method(:no_whitespace) will return a Method which in most cases will act very much like a lambda.

However if

module Mutations
  class MyMutation < BaseMutation
    argument :name, String, required: true, prepare: :no_whitespace

    def no_whitespace(value)
      value.strip!
    end
  end
end

Is return a NoMethodError: undefined method no_whitespace' for MyMutation:Class then try defining that as a class instance method and see what happens:

def self.no_whitespace(value)
  value.strip!
end 
engineersmnky
  • 25,495
  • 2
  • 36
  • 52