Skip to content

Commit

Permalink
Added check_model! method
Browse files Browse the repository at this point in the history
  • Loading branch information
Rodrigo Flores committed Feb 22, 2012
1 parent e3df7f0 commit 9667a38
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
13 changes: 13 additions & 0 deletions lib/devise/models.rb
@@ -1,5 +1,8 @@
module Devise
module Models
class MissingAttribute < StandardError
end

# Creates configuration values for Devise and for the given module.
#
# Devise::Models.config(Devise::Authenticatable, :stretches, 10)
Expand Down Expand Up @@ -39,6 +42,16 @@ def #{accessor}=(value)
end
end

def self.check_fields!(klass)
klass.devise_modules.each do |mod|
instance = klass.new

const_get(mod.to_s.classify)::ModuleMethods.required_fields.each do |field|
raise Devise::Models::MissingAttribute unless instance.respond_to?(field)
end
end
end

# Include the chosen devise modules in your model:
#
# devise :database_authenticatable, :confirmable, :recoverable
Expand Down
8 changes: 8 additions & 0 deletions lib/devise/models/database_authenticatable.rb
Expand Up @@ -27,6 +27,14 @@ module DatabaseAuthenticatable
attr_accessor :password_confirmation
end

module ModuleMethods
extend self

def required_fields
[:encrypted_password, :email]
end
end

# Generates password encryption based on the given value.
def password=(new_password)
@password = new_password
Expand Down
36 changes: 36 additions & 0 deletions test/models_test.rb
Expand Up @@ -107,3 +107,39 @@ def assert_include_modules(klass, *modules)
Admin.create!
end
end

class CheckFieldsTest < ActiveSupport::TestCase
test 'checks if the class respond_to the required fields' do
Player = Class.new do
extend Devise::Models

def self.before_validation(x)
end

devise :database_authenticatable

attr_accessor :encrypted_password, :email
end

assert_nothing_raised Devise::Models::MissingAttribute do
Devise::Models.check_fields!(Player)
end
end

test 'raises Devise::Models::MissingAtrribute if the class doesn\'t respond_to one of the attributes' do
Clown = Class.new do
extend Devise::Models

def self.before_validation(instance)
end

devise :database_authenticatable

attr_accessor :encrypted_password
end

assert_raise Devise::Models::MissingAttribute do
Devise::Models.check_fields!(Clown)
end
end
end

0 comments on commit 9667a38

Please sign in to comment.