问题
My two methods using Devise:
Method1
def self.find_first_by_auth_conditions(warden_conditions)
conditions = warden_conditions.dup
where(conditions).where(["lower(username) = :value OR lower(email)
= :value", {:value => signin.downcase }]).first
end
Method2
def self.find_for_database_authentication(warden_conditions)
conditions = warden_conditions.dup
login = conditions.delete(:signin)
where(conditions).where(["lower(username) = :value OR lower(email) =
:value", {:value => login.strip.downcase }]).first
end
My questions:
- What does this code perform/do?
login = conditions.delete(:signin) - Without the above code I get an error
undefined local variable or method signin
回答1:
The following answers question 1)—specifically A) and B) below. The following code is an example and does not mirror the actual methods or arguments generated by Devise:
Here: the Hash contains :signin key-value pair and other valid ActiveRecord's #where syntax
http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-where
devise_conditions = {:signin => "cool@gmail.com", :deleted => false, :role => 'basic'}
#=> {:signin=>"cool@gmail.com", :deleted => false, :role => 'basic'}
This duplicates original argument to prevent modification in order to use it in subsequent methods or queries http://ruby-doc.org/core-1.9.3/Object.html#method-i-dup
conditions = devise_conditions.dup
#=> {:signin=>"cool@gmail.com", :deleted => false, :role => 'basic'}
Here, the code: A) deletes the :signin key-pair from the Hash; and
B) assigns new variable signin with value of :signin key-pair from Hash
http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-delete
signin = conditions.delete(:signin)
#=> "cool@gmail.com"
The immediately above code could be rewritten to clarify both operations using additional "Element Reference" of Hash
http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-5B-5D
signin = conditions[:signin]
#=> "cool@gmail.com"
conditions.delete(:signin)
#=> "cool@gmail.com" # deleted value from Hash is returned
conditions
#=> {:deleted => false, :role => 'basic'}
The method's original argument has been preserved by using dup
devise_conditions
#=> {:signin=>"cool@gmail.com", :deleted => false, :role => 'basic'}
The following answers question 2):
Method1 does not create a variable signin. undefined local variable or method signin results from no signin variable being created when the code which creates it is removed.
Method2 creates a variable login which has the value from the original Hash named conditions with the key :signin.
回答2:
- This deletes
signinkey fromconditionshash and assigns its value tologinlocal variable.
回答3:
2.. I guess you mean that signin is not defined in find_first_by_auth_conditions? Then I also guess that signin is an attribute of warden_conditions so you can try: warden_conditions.signin.
来源:https://stackoverflow.com/questions/23061116/devise-find-first-by-auth-conditions-method-explanation