The :default
option can take a lambda as its value. Inside that lambda, self
will be the new instance you're creating. That means that you can (indirectly) call methods to supply defaults:
class Sport
include Mongoid::Document
field :rules, type: Hash, default: lambda { default_rules }
end
class Sport::Football < Sport
private
def default_rules
{ :offside => '', :penalty => '' }
end
end
class Sport::Boxing < Sport
private
def default_rules
{ :biting => 'not allowed except for ears' }
end
end
You don't have to make default_rules
private of course. You'll also want default_rules
in Sport
if you want to instantiate Sport
directly.
You could also use one of the callbacks to set the rules by hand:
class Sport
include Mongoid::Document
field :rules, type: Hash
after_initialize :set_default_rules, :if => :new_record? # Or one of the other callbacks.
end
and subclasses could say self.rules = ...
in their set_default_rules
implementations.