0

I have a class that gets initialized with an array of lambda functions. These functions then get called in another method:

class MyClass
  def initialize(funcs)
    @my_funcs = funcs
  end

  def call_funcs_with_arg(arg)
    @my_funcs.each {|f| f.call(arg) }
  end
end

Only certain type of functions are acceptable as input (they all need to follow the same signature). There are some 'built-in' functions but I also want to allow custom functions. I put my built-in functions into a module called MyFunctions. So the usage can be something like this:

custom_function = lambda {|arg| p arg}
func_caller = MyClass.new([MyFunctions::FUNC_1, MyFunctions::FUNC_2, custom_function])
func_caller.call_funcs_with_arg('hello')

I have some doubts about the way I structured this code. The part I'm not sure about is 1. whether a separate module is appropriate for these functions. Should they just live inside MyClass class? It feels like I'm bloating the class, as the list of the functions can grow quite a bit. But then if they live separately like this, it feels like I'm separating something pretty integral to the functionality of MyClass (it can function without MyFunctions module but usually you would want these built-in functions.

2. The secondary question is about using ruby lambdas. I picked this format somewhat arbitrary, but I could equally use actual methods or procs. Are there considerations of using one as opposed to another? At the moment my module looks like this.

module MyFunctions
  FUNC_1 = lambda { |j| p "not #{j}" }
  FUNC_2 = lambda { |j| p "definitely #{j}" }
  ALL_FUNCS = [FUNC_1, FUNC_2]
end

Finally, it's pretty common to use all functions from the module. At the moment I have a helper constant ALL_FUNCS that returns an array of all lambdas.The way I have it written however, means that everytime I add a new FUNC_* I need to add it to that array, which is a bit ugly. 3. Is there a way to get something like "all other constants" from that module? Something like:

ALL_FUNCS = all_constants_except_this_one

Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.