Mitch Dempsey
Mitch Dempsey

Reputation: 39939

How to setup default attributes in a ruby model

I have a model User and when I create one, I want to pragmatically setup some API keys and what not, specifically:
@user.apikey = Digest::MD5.hexdigest(BCrypt::Password.create("jibberish").to_s)

I want to be able to run User.create!(:email=>"[email protected]") and have it create a user with a randomly generated API key, and secret.

I currently am doing this in the controller, but when I tried to add a default user to the seeds.rb file, I am getting an SQL error (saying my apikey is null).

I tried overriding the save definition, but that seemed to cause problems when I updated the model, because it would override the values. I tried overriding the initialize definition, but that is returning a nil:NilClass and breaking things.

Is there a better way to do this?

Upvotes: 1

Views: 376

Answers (5)

theIV
theIV

Reputation: 25794

Have a look at ActiveRecord::Callbacks & in particular before_validation.

Upvotes: 1

Ju Nogueira
Ju Nogueira

Reputation: 8461

I believe this works... just put the method in your model.

def apikey=(value)  
  self[:apikey] = Digest::MD5.hexdigest(BCrypt::Password.create("jibberish").to_s)  
end

Upvotes: 0

Tadas T
Tadas T

Reputation: 2637

use callbacks and ||= ( = unless object is not nil ) :)

class User < ActiveRecord::Base
  before_create :add_apikey #or before_save

  private
  def add_apikey
    self.apikey ||= Digest::MD5.hexdigest(BCrypt::Password.create(self.password).to_s)
  end
end

but you should definitely take a look at devise, authlogic or clearance gems

Upvotes: 4

Schneems
Schneems

Reputation: 15898

class User
    def self.create_user_with_digest(:options = { })
        self.create(:options)
        self.apikey = Digest::MD5.hexdigest(BCrypt::Password.create("jibberish").to_s)
        self.save
        return self
    end
end

Then you can call User.create_user_with_digest(:name => "bob") and you'll get a digest created automatically and assigned to the user, You probably want to generate the api key with another library than MD5 such as SHA256 you should also probably put some user enterable field, a continuously increasing number (such as the current date-time) and a salt as well.

Hope this helps

Upvotes: 0

davidtbernal
davidtbernal

Reputation: 13694

What if, in your save definition, you check if the apikey is nil, and if so, you set it?

Upvotes: 1

Related Questions