class User

Schema Information

Table name: users

id                              :integer          not null, primary key
name                            :string(255)
email                           :string(255)      not null
crypted_password                :string(255)
salt                            :string(255)
activation_state                :string(255)
activation_token                :string(255)
activation_token_expires_at     :datetime
reset_password_token            :string(255)
reset_password_token_expires_at :datetime
reset_password_email_sent_at    :datetime
remember_me_token               :string(255)
remember_me_token_expires_at    :datetime
created_at                      :datetime
updated_at                      :datetime
type                            :string(255)
admin                           :boolean          default(FALSE)
uuid                            :string(255)      default("")
availability_defaults           :text
response_time                   :text
searchable                      :boolean          default(FALSE)
last_name                       :string(255)
phone                           :string(255)
credits                         :integer          default(0)
balanced_student_uri           :string(255)
credits_booked                  :integer          default(0)
points                          :integer          default(0)
streak                          :integer          default(0)
level                           :integer          default(1)
exp_title                       :string(255)
minimum_level                   :integer          default(1)
balanced_api_id                 :text
is_featured                     :boolean          default(FALSE)
is_registration_completed       :boolean          default(FALSE)
is_manually_deactivated         :boolean          default(FALSE)
billing_address_1               :string(255)
billing_address_2               :string(255)
billing_city                    :string(255)
billing_state                   :string(255)
billing_zipcode                 :string(255)
shipping_address_1              :string(255)
shipping_address_2              :string(255)
shipping_city                   :string(255)
shipping_state                  :string(255)
shipping_zipcode                :string(255)
location                        :string(255)
experience                      :string(255)
summary                         :text
awards                          :string(255)
skills                          :string(255)
industry                        :string(255)
profile_step                    :integer
headline                        :string(255)
onboard_step                    :integer
pending_chat_with               :integer
cached_notification_count       :integer          default(0)
cached_message_count            :integer          default(0)
auth_token                      :string(255)
university_id                      :integer
level_changed                   :boolean
skills_count                    :integer          default(0)
courses_count                 :integer          default(0)
rate_in_cents                   :integer          default(2000)

Constants

PROFILE_QUESTION

Profile Questions

PROFILE_STEPS

Profile steps

USER_TYPES

Hash for user types.

Attributes

crop_circle_r[RW]

attribute accessors

crop_circle_x[RW]

attribute accessors

crop_circle_y[RW]

attribute accessors

current_password[RW]

attribute accessors

email_confirmation[RW]

attribute accessors

invitation_token[RW]

attribute accessors

update_searchable[RW]

attribute accessors

vote[RW]

attribute accessors

vote_scope[RW]

attribute accessors

Public Class Methods

activate_tutor() click to toggle source

To activate tutors

# File app/models/user.rb, line 444
  def self.activate_tutor
#     condition = "activation_state = 'pending' and is_tutor_onboard = 1"  #TEST-CONDITION
    condition = "activation_state = 'pending' and is_tutor_onboard = 1 and created_at <= '#{(Time.zone.now - 12.hours)}'"
    counter = 0
    puts "=> Activating tutor registered 12 hrs ago...\n\n"
    Tutor.find_each(:conditions => condition, :batch_size => 100) do |tutor|
      tutor.update_searchable = true
      tutor.searchable = true
      tutor.save
      tutor.activate!
      counter = counter + 1
      puts "=> #{tutor.name}(created_at:'#{tutor.created_at}') is activated and made searchable!\n\n"
    end
    puts "=> Total #{counter} tutor processed!"
  end
current() click to toggle source

Returns current user.

# File app/models/user.rb, line 109
def self.current
  Thread.current[:user]
end
current=(user) click to toggle source

Sets user as current user.

# File app/models/user.rb, line 114
def self.current=(user)
  Thread.current[:user] = user
end
next_step(step=nil) click to toggle source
# File app/models/user.rb, line 821
def self.next_step(step=nil)
  steps = User::PROFILE_STEPS.call
  (steps[steps.rindex(step) + 1] || 0) rescue 0
end
paginate(p = 1, per_page = 10, offset_delta = 0) click to toggle source
# File app/models/user.rb, line 806
def self.paginate(p = 1, per_page = 10, offset_delta = 0)
  page(p).per(per_page).padding(offset_delta.to_i)
end
profile_step_partial(step_name) click to toggle source
# File app/models/user.rb, line 810
def self.profile_step_partial(step_name)
  {
    Category.model_name.human(count: 0).downcase => 'categories',
    "#{Category.model_name.human(count: 0).downcase}-confirmation" => 'categories-confirmation',
    Subject.model_name.human(count: 0).downcase => 'subjects',
    "#{Subject.model_name.human(count: 0).downcase}-confirmation" => 'subjects-confirmation',
    Course.model_name.human(count: 0).downcase => 'courses',
    "#{Course.model_name.human(count: 0).downcase}-confirmation" => 'courses-confirmation'
  }[step_name] || step_name
end

Public Instance Methods

activate() click to toggle source

User to set activate state as active(i.e. it activates the user).

# File app/models/user.rb, line 395
def activate
  self[:activation_state] = 'active'
end
active?() click to toggle source

Retruns true if user's activation state is active

# File app/models/user.rb, line 478
def active?
  self.activation_state == "active"
end
add_user_to_group(object) click to toggle source

To add user to group.

# File app/models/user.rb, line 245
def add_user_to_group(object)
  group = object.group
  unless self.groups.where(groups: {id: group.id}).exists?
    group_membership = group.group_memberships.build(user_id: self.id)
    group_membership.singleton_class.after_commit {|gm| gm.group.trigger_pusher_group_event } #submit to BJ after commit for updating Group through pusher
    group_membership.save!
  end
end
admin?() click to toggle source

Checks whether the user is admin.

Calls superclass method
# File app/models/user.rb, line 537
def admin?
  super || super_admin?
end
approved_friend?(user) click to toggle source

Checks whether the user approved the specified user as friend.

# File app/models/user.rb, line 498
def approved_friend?(user)
  friends.exists?(id: user.id)
end
balance_amount() click to toggle source

Returns balanced amount of user.

# File app/models/user.rb, line 295
def balance_amount
  account_balance.try(:amount) || Money.new(0)
end
balanced_student() click to toggle source

To find/create balanced student

# File app/models/user.rb, line 754
def balanced_student
  if balanced_student_uri?
    Balanced::Student.find(balanced_student_uri)
  else
    student = Balanced::Student.new(:name => self.full_name, :email => self.email).save
    self.update_columns(balanced_student_uri: student.href)
    student
  end
end
build_notification_settings() click to toggle source

Build notification setting for all notification type for user.

# File app/models/user.rb, line 287
def build_notification_settings
  NotificationSetting::TYPES.each_with_index do |notification_type, index|
    notification_settings.build(notification_type: index) unless notification_settings.exists?(notification_type: index)
  end
  notification_settings.sort {|a, b| a.notification_type <=> b.notification_type}
end
calc_raw_score() click to toggle source

Calculate the raw score of user positive and negative review and update its level score based on it.

# File app/models/user.rb, line 617
  def calc_raw_score
    streak = self.streak
    hours = self.billed_hours
    positive_reviews = self.positive_reviews
    negative_reviews = self.negative_reviews
#    content = self.content_points
    if hours == 0 && streak == 0
#      score = hours + positive_reviews - (2 * negative_reviews) + (content/[negative_reviews - positive_reviews,2].max)
      score = hours + positive_reviews - (2 * negative_reviews)
    else
#      score = hours + positive_reviews - (2 * negative_reviews) + ((streak**2)/(0.5*(hours||1))) + (content/[negative_reviews - positive_reviews,2].max)
      score = hours + positive_reviews - (2 * negative_reviews) + ((streak**2)/(0.5*(hours||1)))
    end
    update_level score
  end
common_friends() click to toggle source

Returns the common friends of user added and current user.

# File app/models/user.rb, line 503
def common_friends
  pending_friends.union(direct_friends)
end
content_reward(reward) click to toggle source

Increment user points.

# File app/models/user.rb, line 605
def content_reward reward
  if self.type == "Student"
    reward_credits reward, self
  else
    reward_points reward, self
  end
end
conversations() click to toggle source

Return all chat conversations of the user

# File app/models/user.rb, line 742
def conversations
  group_conversations.union(chat_conversations)
end
create_session_reward() click to toggle source

Create reward for tutoring session.

# File app/models/user.rb, line 592
def create_session_reward
  if self.via_invite && !self.via_invite.tutoring_session_reward
    if self.via_invite.inviter.type = "Student"
      reward_credits 10, self.via_invite.inviter
    else
      reward_points 40
    end
    self.via_invite.tutoring_session_reward = true
    self.via_invite.save
  end
end
student?() click to toggle source

Returns true if user type is student

# File app/models/user.rb, line 483
def student?
  self.type == 'Student'
end
events() click to toggle source

Returns all events of user part of.

# File app/models/user.rb, line 737
def events
  Event.find_by_shared_to(self).uniq
end
tutor?() click to toggle source

Returns true if user type is tutor

# File app/models/user.rb, line 488
def tutor?
 self.type == 'Tutor'
end
tutor_with_interactions() click to toggle source

Returns all the tutor interacted with.

# File app/models/user.rb, line 361
def tutor_with_interactions
  Tutor.find_by_sql(<<-SQL
    SELECT DISTINCT u.*
    FROM users u
    Where u.id IN (
      SELECT DISTINCT(ts.tutor_id)
      FROM tutoring_sessions ts
      WHERE ts.user_id = #{self.id}
      UNION
      SELECT
        DISTINCT(CASE m.sender_id
          WHEN #{self.id} THEN m.receiver_id
          ELSE m.sender_id
        END)
      FROM messages m
      WHERE m.sender_id = #{self.id} OR m.receiver_id = #{self.id}
    ) AND type = 'Tutor'
  SQL
  )
end
friends() click to toggle source

Returns friends of current user.

# File app/models/user.rb, line 508
def friends
  direct_friends.union(inverse_friends)
end
full_name() click to toggle source

Returns full name of user(i.e. name followed by last name)

# File app/models/user.rb, line 680
def full_name
  [name, last_name].compact.join(" ").titleize
end
full_name_with_email() click to toggle source

Returns full name with email of user(i.e. full name followed by email)

# File app/models/user.rb, line 685
def full_name_with_email
  "#{full_name} <#{email}>"
end
generate_uuid() click to toggle source

Method to generate uuid.

# File app/models/user.rb, line 545
def generate_uuid
  if self.uuid.blank?
    self.uuid = UUID.new.generate.to_s
  end
end
has_balanced_account?() click to toggle source

Check whether user has credit card.

# File app/models/user.rb, line 560
def has_balanced_account?
  self.credit_card and self.credit_card.uri?
end
has_balanced_bank_account?() click to toggle source

checks whether the user has bank account.

# File app/models/user.rb, line 565
def has_balanced_bank_account?
  self.bank_account and self.bank_account.uri?
end
has_review_for?(other_user) click to toggle source

Checks whether the user has review for specified user.

# File app/models/user.rb, line 552
def has_review_for?(other_user)
  self.reviews_posted.where(for_user_id: other_user.id).exists?
end
image() click to toggle source

Returns image object of user.

# File app/models/user.rb, line 700
def image
  (self.profile_image || self.build_profile_image).image
end
image_url(style = :original) click to toggle source

Returns user image url.

# File app/models/user.rb, line 705
def image_url(style = :original)
  image.url(style)
end
is_common_user?() click to toggle source

Checks whether user is common user(i.e. tutor or student).

# File app/models/user.rb, line 493
def is_common_user?
  tutor? || student?
end
is_favorite_users?(user) click to toggle source

Checks whether user added as friend.

# File app/models/user.rb, line 421
def is_favorite_users?(user)
  friendships.exists?(friend_id: user.id) or inverse_friendships.exists?(user_id: user.id)
end
is_favorite_users_and_approved?(user) click to toggle source

Checks whether user added as friend and approved.

# File app/models/user.rb, line 426
def is_favorite_users_and_approved?(user)
  friendships.where('friend_id=? AND approved =?', user.id, true).exists?
end
make_admin!() click to toggle source

Update user as admin.

# File app/models/user.rb, line 522
def make_admin!
  self.update_attribute(:admin, true)
end
mark_favorite(user) click to toggle source

To add user as friend.

# File app/models/user.rb, line 403
def mark_favorite(user)
  unless is_favorite_users?(user)
    @friend_ship = friendships.build(friend_id: user.id)
    @friend_ship.save!
  end
end
maximum_rate_as_per_user_level() click to toggle source

Returns the maximum rate as per user level.

# File app/models/user.rb, line 654
def maximum_rate_as_per_user_level
  case self.user_level
    when 1
      return 2000
    when 2
      return 2500
    when 3
      return 3000
    when 4
      return 3500
    when 5
      return 4000
    else
      return 4500
  end
end
next_available_profile_step(step) click to toggle source

Returns next available profile step

# File app/models/user.rb, line 469
def next_available_profile_step(step)
  last_step = PROFILE_STEPS.call.size
  step = self.profile_step ? User::PROFILE_STEPS.call[self.profile_step] : 0
  current_step_index = User::PROFILE_STEPS.call.index(step)
  return 0 if current_step_index.nil?
  current_step_index.to_i + 1 > last_step ? nil : current_step_index.to_i + 1
end
next_profile_step(step = profile_step) click to toggle source

Returns next profile step

# File app/models/user.rb, line 461
def next_profile_step(step = profile_step)
  if tutor? and is_registration_completed?
    return nil if profile_step >= User::PROFILE_STEPS.call.rindex('my-rate') rescue nil
  end
  PROFILE_STEPS.call[next_available_profile_step(step)] rescue nil
end
notification_enabled_for?(name) click to toggle source

Checks whether the notification is enabled for specified user or not.

# File app/models/user.rb, line 278
def notification_enabled_for?(name)
  if notification_settings.exists?(notification_type: NotificationSetting::TYPES.index(name), enabled: false)
    false
  else
    true
  end
end
online?(recheck = false) click to toggle source

checks whether the user is online.

# File app/models/user.rb, line 233
  def online?(recheck = false)
    return @online if @online and !recheck
    @online = if ActsAsTenant.current_tenant.pusher_configuration.try(:enabled)
      ActsAsTenant.current_tenant.pusher_configuration.client.get("/channels/private-user-#{id}")[:occupied]
    else
      false
    end
#  rescue
#    false
  end
password_blank?() click to toggle source
# File app/models/user.rb, line 777
def password_blank?
  self.password.nil? || self.password.empty?
end
password_required?() click to toggle source
# File app/models/user.rb, line 781
def password_required?
  new_record?
end
prevent_non_active_login() click to toggle source
Calls superclass method
# File app/models/user.rb, line 797
def prevent_non_active_login
  if self.is_manually_deactivated?
    self.errors.add(:base, 'Your account is deactivated by site admin.')
    return false
  else
    super
  end
end
previous_confirmed_sessions() click to toggle source

Returns confirmed sessions of user.

# File app/models/user.rb, line 332
def previous_confirmed_sessions
  tutored_sessions.confirmed.previous.occured.not_reviewed.union(
    tutored_sessions.pending.video_sessions.occured.not_reviewed.valid_sessions.session_not_omitted
  )
end
raw_image(style = :original) click to toggle source

Returns raw image.

# File app/models/user.rb, line 710
def raw_image(style = :original)
  unless image.path
    File.read(File.join(Rails.root, "app/assets/images/users/#{style}.png"))
  else
    case image.options[:storage].to_s
      when 'filesystem'
        File.read(image.path(style))
      when 's3'
        open(image.url(style)).read
    end
  end
end
recent_chat_conversations() click to toggle source

Return recent chat conversations.

# File app/models/user.rb, line 747
def recent_chat_conversations
  ChatConversation.recent_for(self)
end
remove_user_from_group(object) click to toggle source

To remove the user to group.

# File app/models/user.rb, line 255
def remove_user_from_group(object)
  groups.destroy(object.group)
  object.group.trigger_pusher_group_event
end
reset_cached_message_count() click to toggle source

To reset the cached message count to 0.

# File app/models/user.rb, line 436
def reset_cached_message_count
  update_columns(cached_message_count: 0)
end
reset_cached_notification_count() click to toggle source

To reset the cached notification count to 0.

# File app/models/user.rb, line 431
def reset_cached_notification_count
  update_columns(cached_notification_count: 0)
end
revoke_admin!() click to toggle source

Update user set admin to false.

# File app/models/user.rb, line 527
def revoke_admin!
  self.update_attribute(:admin, false)
end
reward_credits(credits, user) click to toggle source

Used to increment the credit of specified user.

# File app/models/user.rb, line 573
def reward_credits credits, user
  user.increment!(:credits, credits)
end
reward_points(points, user) click to toggle source

Used to increment the point of specified user.

# File app/models/user.rb, line 578
def reward_points points, user
  user.increment!(:points, points)
end
signup_reward() click to toggle source

Set reward on signup.

# File app/models/user.rb, line 583
def signup_reward
  if self.type = "Student"
    reward_credits 2, self
  else
    reward_points 5, self
  end
end
super_admin?() click to toggle source

Checks whether the user is super admin.

# File app/models/user.rb, line 532
def super_admin?
  instance_of?(Admin)
end
total_balance() click to toggle source

Return total balance (i.e balance amount + withdrawable amount) of user.

# File app/models/user.rb, line 305
def total_balance
  balance_amount + withdrawable_amount
end
type_to_symbol() click to toggle source

Return the user type downcased, dasherized and symbolized ej: SuperUser -> :super_user

# File app/models/user.rb, line 514
def type_to_symbol
  ActiveModel::Naming.param_key(self)
end
unmark_favorite(user) click to toggle source

To remove user from friend list.

# File app/models/user.rb, line 411
def unmark_favorite(user)
  if is_favorite_users?(user)
   friend_ship = friendships.find_by(friend_id: user.id) || inverse_friendships.find_by(user_id: user.id)
   friend_ship.destroy
   notification = Notification.find_by(trackable_id: friend_ship.id)
   notification.destroy if notification
  end
end
update_invitation() click to toggle source

Used to update invitation.

# File app/models/user.rb, line 383
def update_invitation
  invite = if self.invitation_token.present?
    Invite.find_by(invite_token: self.invitation_token)
  else
    Invite.where(invitee_email: self.email).order(:accepted_at).first
  end
  if invite
    invite.update_columns(registered: true, invitee_id: self.id)
  end
end
update_level(score) click to toggle source

Update the level of user.

# File app/models/user.rb, line 634
def update_level score
  case score
  when 0..9
    self.user_level = 1
  when 10..19
    self.user_level = 2
  when 20..39
    self.user_level = 3
  when 40..69
    self.user_level = 4
  when 70..139
    self.user_level = 5
  else
    self.user_level = 6
  end
  self.level_changed = true
  self.save
end
upgrade!() click to toggle source

Upgrade user to tutor.

# File app/models/user.rb, line 310
def upgrade!
  update_columns(type: 'Tutor', is_registration_completed: false, searchable: false )
  Indexer.perform_async(:update, self.class.to_s, self.id)
end
user_level() click to toggle source

Returns user level.

# File app/models/user.rb, line 690
def user_level
  minimum_level > level ? minimum_level : level
end
user_level=(value) click to toggle source

Used to set the user level.

# File app/models/user.rb, line 695
def user_level=(value)
  self.level = (minimum_level > value) ? minimum_level : value
end
user_level_update_email() click to toggle source

Sends email to user when user level is updated.

# File app/models/user.rb, line 316
def user_level_update_email
  if previous_changes[:level]
    UserMailer.delay(queue: :mailer).user_level_updated_email(self, self.user_level, self.maximum_rate_as_per_user_level)
  end
end
user_course_ids=(ids) click to toggle source

Convert the comma separated subtade ids into array format.

Calls superclass method
# File app/models/user.rb, line 674
def user_course_ids=(ids)
  ids = ids.split(',') if ids.is_a?(String)
  super(ids)
end
users_with_interaction(query = nil, options = {}) click to toggle source

Returns all users to which user is related.

# File app/models/user.rb, line 724
def users_with_interaction(query = nil, options = {})
  except_user_ids = options[:except] ? options[:except].push(self.id) : [self.id]
  users = conversed_users
  users = users.union(tutor)
  users = users.union(group_users)
  users = users.union(self.tutored_users) if self.tutor?
  if query
    users = users.where("(LOWER(CONCAT(users.name, ' ', users.last_name)) LIKE :query)", query: "%#{query.try(:downcase)}%")
  end
  users.where.not(id: except_user_ids).uniq
end
valid_password?(pass) click to toggle source

Calls the configured encryption provider to compare the supplied password with the encrypted one.

# File app/models/user.rb, line 765
def valid_password?(pass)
  _crypted = self.send(sorcery_config.crypted_password_attribute_name)
  return _crypted == pass if sorcery_config.encryption_provider.nil?
  _salt = self.send(sorcery_config.salt_attribute_name) unless sorcery_config.salt_attribute_name.nil?
  sorcery_config.encryption_provider.matches?(_crypted, pass, _salt)
end
validate_categories?() click to toggle source
# File app/models/user.rb, line 785
def validate_categories?
  false
end
validate_email_domain() click to toggle source

Checks for valid email domain.

# File app/models/user.rb, line 323
def validate_email_domain
   unless Configurations::General.domain_list.blank?
     if self.email and !Configurations::General.domain_list.include?(self.email.split('@', 2).last)
    errors.add(:email, "Email domains allowed are \"#{Configurations::General.domain_list.join(', ')}\" only.")
    end
  end
end
validate_rate?() click to toggle source
# File app/models/user.rb, line 793
def validate_rate?
  self.profile_step == User::PROFILE_STEPS.call.rindex('my-rate') || changes.has_key?(:rate_in_cents) unless new_record?
end
validate_user_courses?() click to toggle source
# File app/models/user.rb, line 789
def validate_user_courses?
  self.profile_step == User::PROFILE_STEPS.call.rindex('courses_studying')
end
video_session_rooms() click to toggle source

Returns video session room for tutoring session related to user.

# File app/models/user.rb, line 356
def video_session_rooms
  VideoSessionRoom.where(tutoring_session_id: related_sessions.select('id'))
end
withdrawable_amount() click to toggle source

Returns withdrawable amount of user.

# File app/models/user.rb, line 300
def withdrawable_amount
  withdrawable_balance.try(:amount) || Money.new(0)
end