Return self from model.readonly!

I was wondering if it would make sense to return self from the readonly! method of an ActiveRecord model? I found myself wanting to create a list of read only instances and it seemed unnecessarily verbose to do

model = Model.new(attrs)

model.readonly!

model

for each of them instead of just

Model.new(attrs).readonly!

I’ve got the super small patch prepared, but I wanted to run it by some folks before adding it to the rather large list of pull requests!

Thanks,

-David

Hi,

Maybe, can you use the method #tap?

model = Model.new(attrs).tap(&:readonly!)

Best regards.

Ah, thanks for the reminder about using tap!

I’m still curious, though, if it would be a better API to return self or if there is a reason/precedent not to. I thought maybe command query separation was the reason, but it seems like enabling a fluent syntax by returning self is a good exception to that principle. For example, the bang methods on String return the string if successful, which is very convenient.

It’s not a big deal, obviously, as tap works fine, but I’m just curious. Thanks so much for taking the time to respond!

-David

Agreed it’s a super minor issue, but I personally like David’s proposal. It seems like ruby’s Object#freeze is a strong analog and precedent for returning the mutated object and enabling a fluent interface. It doesn’t look like there was an explicit decision behind the current behavior, it’s just the natural result of the current one-line implementation.

-john

Thanks for chiming in, John. Do you think it’s worth submitting my small PR at this point, or would it be better to try to get more input here first?

-David

I like the proposal too. I’d say submit the small PR and then you’ll get discussion on it and a decision anyway (particularly as you’ve already prepared it)