cschenio
cschenio

Reputation: 107

Rails: Download by Mechanize custom filename

Now i'm trying to download an random-avatar for users while registering. So i get Mechanize and do this after research.

class RegistrationsController < Devise::RegistrationsController
def new
    super
end
def create
    agent = Mechanize.new
    agent.pluggable_parser.default = Mechanize::Download
    f = agent.get('http://avatar.3sd.me/100')
    f.save('public/images/avatar/it_should_be_user_id.png')
    super
end
def update
    super
end
end

But i cannot figure out how to save the file in the specific name according to the user id, how to do it?

Upvotes: 0

Views: 218

Answers (1)

gitcdn
gitcdn

Reputation: 485

I suggest you call super first in the create method, so the default setup of the devise controller happens before your code gets executed.

Inside the RegistrationsController class you can access the current user with the variable/method resource (instead of something like current_user). So your code would look like this:

class RegistrationsController < Devise::RegistrationsController
    def new
        super
    end
    def create
        super
        agent = Mechanize.new
        agent.pluggable_parser.default = Mechanize::Download
        f = agent.get('http://avatar.3sd.me/100')
        f.save("public/images/avatar/#{resource.id}.png")
    end
    def update
        super
    end
end

Upvotes: 1

Related Questions