DmitryTsepelev / store_model

Work with JSON-backed attributes as ActiveRecord-ish models
MIT License
1.04k stars 85 forks source link

Registering StoreModels as ActiveModel types #170

Open Morozzzko opened 3 months ago

Morozzzko commented 3 months ago

I'm trying to use StoreModel as a building block for composite types.

Let's imagine I'm trying to model Money. I'm not really doing that, but it's a nice domain

Here's what I would do:

class MoneyModel
  include StoreModel::Model

  attribute :cents, :integer
  attribute :currency_code, :string
end

The docs suggest that I use it like this:

attribute :amount, MoneyModel.to_type

However, I feel like it's not the way I'd like to use it, as I can register my custom types

So I add that line of code:

ActiveModel::Type.register(:money, MoneyModel.to_type)

Works well so far

However, when I try to run

attribute :amount, :money 

I get a

Failure/Error: attribute :amount, :money 

NoMethodError:
  undefined method `new' for an instance of StoreModel::Types::One

Which is pretty fair considering how it all is implemented, because we can't register an instance of a type

However, the way to_type is implemented, we can't really achieve that using current representation, and it feels like we should have some way to do it

DmitryTsepelev commented 3 months ago

Hey!

Sounds reasonable, I'd be happy to have such feature, but sounds like a huge job to be done to achieve that 🙂