Default constructors

I use classes for parameter serialization. Is it possible to automatically generate an constructor that accepts all instance variables as arguments?

class RequestParameters
  include JSON::Serializable
  property username : String
  property password : String

  # do I have to write this for every class?
  def initialize(@username, @password)
  end
end
1 Like

Could you not put the contructor in a module and include the module?

Or use a macro to generate the constructor?

1 Like

See GitHub - kostya/auto_initialize: Generate initialize methods for classes and structs

6 Likes

Thanks. This is what I was looking for.

There is a built in helper for this

require "json"

record(RequestParameters,
  username : String,
  password : String
 ) do
  include JSON::Serializable
end

params = RequestParameters.new("user", "pass")
params.to_json

Very little documentation on it, but I use it all the time

# you can also define defaults
record RequestParameters,
  username : String = "admin",
  password : String = "password"

RequestParameters.new
RequestParameters.new "username"
5 Likes

Worth pointing out that the main catch with using record is it creates a struct, so the resulting object would lack any setters and would be passed by value. I.e. great option for representing a request body/response, but not as great if you want to pass it around while mutating it.

4 Likes