开发者

How to setup default attributes in a ruby model

开发者 https://www.devze.com 2022-12-31 02:05 出处:网络
I have a model User and when I create one, I want to pragmatically setup some API keys and what not, specifically:

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=>"something@test.com") 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?


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


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


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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消