|
|
|
|
|
by Locke
3682 days ago
|
|
As a thought exercise, suppose I have my User class and now I would like to write it as json. Do you think it would be strange if the established solution were this? class User < JSON::Base
Where by extending JSON::Base, I now have access to helpful methods like to_json?Instead we have JSON.dump(user). And, if I need to customize the way the User json is written, I can opt in by defining a method. Thanks to Ruby's open classes, I can make the definition of such methods optional, suppose a separate file includes something like: class User
def as_json
end
end
Requiring this file will bring in the extra json behavior without littering my actual user.rb with the details of how a User is written to json. Whether this is worthwhile or a bad idea is debatable, but I like that it is possible.Now imagine if persisting a model to the database were similarly flexible? What if we could do this? ActiveRecord.save(user)
Maybe it would be a good thing, maybe not.As it is, I've come to accept the ActiveRecord approach, but when I create a model that extends ActiveRecord::Base, I think of it, not as a User, but an ActiveRecordPersistedUser. Where it makes sense, I separate my BusinessModel's from my ActiveRecordPersistedBusinessModel's for clarity. |
|