改进这段代码。工作,但看起来很可疑

时间:2013-10-26 10:28:06

标签: ruby-on-rails ruby

我希望任何人都能帮助改进这段代码。它目前有效,但总是让我怀疑。

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交互。

1 个答案:

答案 0 :(得分: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

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