简体   繁体   中英

Dynamic constant assignment when using REGEX inside rails ApplicationController?

I need to convert my base64 image string into an actual file and then upload into the server.

But it seems like when i tried to decode base64 file by using REGEX rails controller didn't allow me to do it.

This is my controller

def update_with_image
    user = current_user

    REGEXP = /\Adata:([-\w]+\/[-\w\+\.]+)?;base64,(.*)/m


    data_uri_parts = user_update_params[:profile_image].match(REGEXP) || []
    extension = MIME::Types[data_uri_parts[1]].first.preferred_extension
    file_name = "user_profile_image_#{user.id}.#{extension}"

    File.open(file_name, 'wb') do |file|
      file.write(Base64.decode64(data_uri_parts[2]))
    end

    uploader = PictureUploader.new
    uploader.store!(file_name)
    user_update_params[:profile_image] = uploader.url

    if user.update_attributes(user_update_params)
      # Handle a successful update.
      render json: user, status: 200 ,serializer: UserSerializer
    else
      render json: { errors: user.errors }, status: 422
    end
end

This is what i got from the server

"#<SyntaxError: /Sites/xxx/users_controller.rb:57: dynamic constant assignment↵    REGEXP = /\Adata:([-\w]+\/[-\w\+\.]+)?;base64,(.*)/m↵`            ^>"

So how can i fix this?

Thanks!

now i just passed the expression directly without using variable and it works fine. – user3403614

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM