0

我希望任何人帮助改进这段代码。它目前有效,但对我来说总是很可疑。

def sms
    @message = Message.new
    decoded_to = CGI.unescape(params[:to])
    #@message.to = decoded_to.gsub(/[^\d]/,"")
    @message.to = CGI.unescape(params[:to]).strip.gsub("+","").gsub(/\s+/, "")
    @message.from =  CGI.unescape(params[:from])
    @message.message = CGI.unescape(params[:message]).strip
    @message.user_id = current_user.id
    @message.status = 'Queued'
    if @message.save
        MessageWorker.perform_async(@message.id, [""], current_user.id)
        render json: {status: "Success"} 
    else
        render json: {status: "Failed" }
    end
end

这是一个与另一个控制器使用的共享消息模型交互的 API 控制器。它严格用于 API 交互。

4

1 回答 1

1

分离出参数清理逻辑:

def sms
    @message = Message.new(clean_params.merge(user: current_user, status: 'Queued'))
    if @message.save
        MessageWorker.perform_async(@message.id, [""], current_user.id)
        render json: {status: "Success"} 
    else
        render json: {status: "Failed" }
    end
end

private

def clean_params
    cleaned_params = {}
    %i(to from message).each { |key| cleaned_params[key] = CGI.unescape(params[key]) }
    cleaned_params[:to].strip!.gsub!("+","").gsub!(/\s+/, "")
    cleaned_params[:message].strip!
    cleaned_params
end

未经测试,我希望没有错别字;)

于 2013-10-26T10:42:53.590 回答