如何使用`send`函数传递参数

时间:2013-02-16 03:50:13

标签: ruby

我在Rails 3.2应用程序中使用cancan,并且在abilities.rb分类中为每个角色的能力提供了一种方法

#ability.rb

def initialize(user)
  user_or_admin ||= User.new

  user.roles.each do |role| 
    send(role.name)
  end
end

def role_name_a

end

def role_name_b

end

其中一些方法需要访问用户记录,如何使用send函数传递它?

e.g。我想做像

这样的事情

send(role.name)(user)

然后

def role_name_a(user)

但这不起作用。感谢任何想法。

2 个答案:

答案 0 :(得分:2)

参数是send的第二个参数。第一个参数是方法名称作为符号。

send :"#{role.name}", user

你应该尝试查看Ruby的文档来解决这个问题。语言记录良好。

http://ruby-doc.org/core-1.9.3/Object.html#method-i-send

答案 1 :(得分:0)

我不确定这是否是最佳做法,但它是康康文档中的内容。

def initialize(user)
  @user = user || User.new

  user.roles.each do |role| 
    send(role.name)
  end
end

def role_name_a
  can :manage, User, id: @user.id
end

def role_name_b

end
相关问题