在 RailsCast 219 ,提供以下代码用于创建一个类,用于从表单来回传输数据,但没有任何 ActiveRecord 持久性:
class Message
include ActiveModel::Validations
attr_accessor :name, :email, :content
validates_presence_of :name
validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
validates_length_of :content, :maximum => 500
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
end
我是 Ruby 新手,但 send("#{name}=", value)
似乎是对攻击者的邀请
将任意值分配给任意字段。这是一个问题吗?一些评论者问similar questions ,但没有任何反应。
最佳答案
send
是动态调用方法的常见方式(当您事先不知道要调用什么时)。
如果您担心安全性,那么您绝对应该进行一些验证。这是一个简单的限制检查:
def initialize(attributes = {})
attributes.each do |name, value|
if [:name, :email, :content].include?(name)
send("#{name}=", value)
end
end
end
关于ruby-on-rails - ActiveModel:send() 的危险使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11228795/