Last active
December 20, 2015 23:09
-
-
Save abhishek0/6210777 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
module Contactable | |
def self.set_contact(contact) | |
@contact = Contact.find_by_email(contact[:email]) | |
@contact = Contact.create!(contact) unless @contact.exists? | |
end | |
def self.get_contact | |
@contact | |
end | |
end | |
module Stampable | |
include Contactable | |
def self.included(base) | |
has_one :stamp, as: :stampable | |
after_create :create_stamp | |
end | |
def self.create_stamp(stamp) | |
self.destroy unless not @contact.nil? and @contact.valid? | |
stamp = Stamp.new(stamp) | |
stamp.contact = get_contact | |
stamp.stampable_id = self.id | |
stamp.stampable_type = self.class.table_name | |
self.destroy if not stamp.save | |
self.stamp = stamp | |
self.save | |
end | |
end |
This file contains hidden or 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 | |
include Stampable | |
validates :user_type,:locality,:city, presence: true | |
validates :username, uniquiness: true | |
has_secure_password | |
validates_presence_of :password, :on => :create | |
belongs_to :parent, class_name: 'User' | |
has_many :children, class_name: 'User', foreign_key: 'parent_id' | |
has_many :stamps | |
before_create :generate_access_token, :set_username_as_email | |
private | |
def generate_access_token | |
access_token = SecureRandom.hex | |
until User.find_by_access_token(access_token) == nil | |
access_token = SecureRandom.hex | |
end | |
self.access_token = access_token | |
end | |
def set_username_as_email | |
self.username = get_contact.email | |
end | |
end |
This file contains hidden or 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 'test_helper' | |
class UserTest < ActiveSupport::TestCase | |
test 'create user and try to save' do | |
u = User.new :user_type => 'admin', :locality => 'goregaon', :city => 'mumbai' | |
u.set_contact({first_name: 'Admin', last_name: 'admin', email: '[email protected]', contact_numbers: '1,2'}) | |
assert u.save | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment