开发者

overload attributes to method with ruby/rails

开发者 https://www.devze.com 2023-03-08 08:23 出处:网络
I have an authentication method within my User model. I want to be able to call this method like that

I have an authentication method within my User model.

I want to be able to call this method like that

User.authenticate(:email => email@exmaple.com, :password => "123")

and

User.authenticate(:remember_token => "asdasds41")

what's the right way to do that?

I gave a glimpse in rails source (validates function) and I noticed that the function get *attrib开发者_运维技巧utes, but I didn't figure out what the * stands for and how to read the inner variables

Tnx for helping


The method you are speaking of is actually taking a hash of values. The keys within the hash (e.g. :remember_token, :email, and :password) act as named parameters and it does not matter where within the order they appear in the calling statement.

Also, the hash would normally need to be surrounded by braces (e.g. {...}), but in Ruby the last argument in a method does not require these braces.

The *attributes that you speak of is a way to pass a dynamic number of arguments to a method as through an array. The *attributes notation instructs Ruby to expand the attributes into a list of arguments.

The authenticate method you speak of would look something like this:

class User

  def self.authenticate(params)
    puts params[:email]
    puts params[:password]
    puts params[:remember_token]
  end

end

where you would obviously do something other than print out the parameters that you are receiving.

0

精彩评论

暂无评论...
验证码 换一张
取 消