how to use ruby classes in trailblazer?

It is very easy to just try this out, because Ruby will literally tell you what you need to do.

You say you want to able to write MyModule::Class.(*params), so you simply do exactly that:

MyModule::Class.(*params)

And Ruby tells you what you are missing:

NoMethodError (undefined method `call' for MyModule::Class:Class)

So, as you can see, Ruby tells us that we are missing a method named call in the singleton class of MyModule::Class, so let’s just define that method:

module MyModule
  def Class.call(*params)
    puts "Method `#{__callee__}` called with params #{params.inspect}"
  end
end

MyModule::Class.(1, 'two', :three, [[], [], [], []], { five: :six })
# Method `call` called with params [1, "two", :three, [[], [], [], []], {:five=>:six}]

So, the secret sauce here is that foo.(bar, baz) is syntactic sugar for foo.call(bar, baz).

For the second example, we can do the exact same thing:

MyModule::Class(*params)

And again:

NoMethodError (undefined method `Class' for MyModule:Module)

So, in this case, Ruby is telling us that we need a method named Class on the singleton class of MyModule.

You are simply calling a method named Class on the object MyModule. It is, in fact, exactly the same as if you had written MyModule.Class(*params).

def MyModule.Class(*params)
  puts "Method `#{__callee__}` called with params #{params.inspect}"
end

MyModule::Class(1, 'two', :three, [[], [], [], []], { five: :six })
# Method Class called with params [1, "two", :three, [[], [], [], []], {:five=>:six}]

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top