It occurs to me that you can override https://Class.new to do this and make a much cleaner API.
Any reason not to do this regularly? Feels weird to return `nil` from a constructor, but it would be darn handy a lot of times.
https://gist.github.com/davetron5000/1a6b394f4295f1b70062baab013d297f#file-new-rb
Any reason not to do this regularly? Feels weird to return `nil` from a constructor, but it would be darn handy a lot of times.
https://gist.github.com/davetron5000/1a6b394f4295f1b70062baab013d297f#file-new-rb
Comments
It’s also nice to map the `.to_proc` class method to `method(:coerce).to_proc`. It lets you do something like `array_of_values.map(&YourClass)`.
This is brilliant. I'm going to use this.
Another option would be to make `new` private in a hierarchy for which that is natural, and have only `MyRoot.from` in the root class.
That is logic one can define ad-hoc for a custom method that has a different name, it is custom, so you set the rules, but I think people would get confused if `new` did that.
Something implicit about the contract for new() is that I would expect a newly allocated object with a distinct object id even if the data wasn't necessarily deep copied.
But a new!() Or build() method that does the same thing seems good!
So... using that approach, you'd get:
Header[nil] -> nil
Header["something"] -> Header<"something">
Header[some_header] -> some_header
https://katafrakt.me/2015/05/15/when-you-call-object-new/
It does indeed feel a bit weird to return nil from that. I would expect some kind of an object always. But in principle I don't think the practice is bad.