granite icon indicating copy to clipboard operation
granite copied to clipboard

Setters are not being called in `new`

Open drujensen opened this issue 4 years ago • 3 comments

When calling new with a list of params, it should call the setters for a column so you can override the default behavior.

drujensen avatar Feb 16 '20 03:02 drujensen

Related to #370. This wouldn't be an issue if we stopped creating initializers behind the scenes. Also for whatever its worth, I don't think Granite ever worked like that, as the old cast_to_field method was setting the ivars directly as well.

class User < Granite::Base
  def initialize(params : Hash(String, String?))
    password = params["password"]
    @email = params["email"]
  end
end

Blacksmoke16 avatar Feb 16 '20 03:02 Blacksmoke16

Yeah, I agree. We should treat params as a serializer, similar to json, yaml, or xml. In Amber, we could initialize the object using Class.from_params method.

Question: should serializers call the setter method?

drujensen avatar Feb 16 '20 21:02 drujensen

Or treat it more like DB::ResultSet and overload #new for HTTP::Params or something like that.

It would be doable to make it configurable. The serializer we use at work (in PHP) allows you to control the access method; whether it should use reflection or public methods. We could do something similar as I can see the pros and cons of each approach.

Blacksmoke16 avatar Feb 17 '20 04:02 Blacksmoke16