Last active
December 28, 2015 14:19
-
-
Save enricostano/7513773 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApiKey < ActiveRecord::Base | |
after_initialize do | |
:generate_access_token unless access_token? | |
end | |
belongs_to :user | |
validates :access_token, :user, | |
presence: true | |
validates :access_token, | |
uniqueness: true | |
private | |
def generate_access_token | |
begin | |
self.access_token = SecureRandom.hex | |
end while self.class.exists?(access_token: access_token) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'spec_helper' | |
describe ApiKey do | |
describe "Validations" do | |
it "should have valid factory" do | |
expect(FactoryGirl.build(:api_key)).to be_valid | |
end | |
it { should validate_presence_of(:access_token) } | |
it { should validate_presence_of(:user) } | |
it { FactoryGirl.create :api_key | |
should validate_uniqueness_of(:access_token) } | |
end | |
describe "Associations" do | |
it { should belong_to(:user) } | |
end | |
it "generates access token before validation" do | |
allow(SecureRandom).to receive(:hex).and_return 'foobar' | |
api_key = FactoryGirl.build :api_key | |
expect{ api_key.valid? }.to change{ api_key.access_token}.to 'foobar' | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User < ActiveRecord::Base | |
has_secure_password | |
has_one :profile, | |
as: :profilable | |
has_many :waiting_list_memberships, | |
dependent: :destroy | |
has_many :users_unit_memberships, | |
dependent: :destroy | |
has_many :users_units, | |
through: :users_unit_memberships | |
has_many :groups, | |
through: :users_units | |
has_many :waiting_groups, | |
through: :waiting_list_memberships, | |
source: :group | |
has_many :api_keys, | |
dependent: :destroy | |
validates :name, | |
presence: true | |
validates :email, | |
presence: true, | |
uniqueness: true | |
def session_api_key | |
api_keys.first_or_create | |
end | |
end |
cupakromer
commented
Nov 17, 2013
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment