Skip to content

Commit

Permalink
Merge pull request #182 from brainspec/issue-165
Browse files Browse the repository at this point in the history
Uses after_initialize callback to set default value in mongoid documents as well.
  • Loading branch information
nashby committed Mar 12, 2015
2 parents 2be0870 + 4453d54 commit 74b0a7d
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 4 deletions.
14 changes: 11 additions & 3 deletions lib/enumerize.rb
Expand Up @@ -13,6 +13,7 @@ module Enumerize
autoload :ModuleAttributes, 'enumerize/module_attributes'

autoload :ActiveRecordSupport, 'enumerize/activerecord'
autoload :MongoidSupport, 'enumerize/mongoid'

module Scope
autoload :ActiveRecord, 'enumerize/scope/activerecord'
Expand All @@ -27,9 +28,16 @@ def self.included(base)
def self.extended(base)
base.send :include, Enumerize::Base
base.extend Enumerize::Predicates
base.extend Enumerize::ActiveRecordSupport
base.extend Enumerize::Scope::ActiveRecord if defined?(::ActiveRecord::Base)
base.extend Enumerize::Scope::Mongoid if defined?(::Mongoid::Document)

if defined?(::ActiveRecord::Base)
base.extend Enumerize::ActiveRecordSupport
base.extend Enumerize::Scope::ActiveRecord
end

if defined?(::Mongoid::Document)
base.extend Enumerize::MongoidSupport
base.extend Enumerize::Scope::Mongoid
end

if defined?(::RailsAdmin)
require 'enumerize/integrations/rails_admin'
Expand Down
2 changes: 1 addition & 1 deletion lib/enumerize/activerecord.rb
Expand Up @@ -4,7 +4,7 @@ def enumerize(name, options={})
super

_enumerize_module.dependent_eval do
if defined?(::ActiveRecord::Base) && self < ::ActiveRecord::Base
if self < ::ActiveRecord::Base
include InstanceMethods

# Since Rails use `allocate` method on models and initializes them with `init_with` method.
Expand Down
13 changes: 13 additions & 0 deletions lib/enumerize/mongoid.rb
@@ -0,0 +1,13 @@
module Enumerize
module MongoidSupport
def enumerize(name, options={})
super

_enumerize_module.dependent_eval do
if self < ::Mongoid::Document
after_initialize :_set_default_value_for_enumerized_attributes
end
end
end
end
end
8 changes: 8 additions & 0 deletions test/mongoid_test.rb
Expand Up @@ -55,6 +55,14 @@ class MongoidUser
model.new.role.must_equal 'user'
end

it 'uses after_initialize callback to set default value' do
model.delete_all
model.create!(sex: 'male', role: nil)

user = model.where(sex: 'male').first
user.role.must_equal 'user'
end

it 'validates inclusion' do
user = model.new
user.role = 'wrong'
Expand Down

0 comments on commit 74b0a7d

Please sign in to comment.