Ist es möglich, eine Mongoid field
zu deserialize als Struct
statt Hash
zu konfigurieren? (with defaults)Mongoid Feld Hash als Struct
Mein Anwendungsfall: ein Unternehmen mit einem Abonnement-Plan als Hash in meinem Modell gespeichert.
Früher als Hash
class Company
include Mongoid::Document
field :subscription, type: Hash, default: {
ends_at: 0,
quantity: 0,
started_at: 0,
cancelled: false,
}
Ich wünschte, ich Company.first.subscription[:ends_at]
schreiben nicht haben, würde ich eher Company.subscription.ends_at
schreiben
ich so etwas wie die folgende dachte würde besser funktionieren
class Company
include Mongoid::Document
field :subscription_plan, type: Struct, default: Struct.new(
:ends_at, :quantity, :started_at, :cancelled
) do
def initialize(
ends_at: nil,
quantity: 0,
starts_at: nil,
cancelled: false
); super end
end
end
Es wäre noch besser, wenn der Plan in einer Klasse
definiert werden könnteclass SubscriptionPlan < Struct.new(
ends_at, :quantity, :starts_at, :cancelled
) do
def initialize(
ends_at: nil,
quantity: 0,
starts_at: nil,
cancelled: false
); super; end
end
class Company
field :subscription_plan, type: SubscriptionPlan, default: SubscriptionPlan.new
end
Wie kann ich es funktionieren lassen?
Haben Sie meine Antwort versucht? –