Skip to content

Instantly share code, notes, and snippets.

@cmhobbs

cmhobbs/user.rb Secret

Last active April 23, 2016 01:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmhobbs/fd56a869088d722face3de4057fca696 to your computer and use it in GitHub Desktop.
Save cmhobbs/fd56a869088d722face3de4057fca696 to your computer and use it in GitHub Desktop.
require 'role_model'
class User < ActiveRecord::Base
include AutomakeOrganization
devise :invitable, :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable
ROLES = ['admin', 'facilitator', 'member'].freeze
def role?(base_role)
ROLES.index(base_role.to_s) <= ROLES.index(role)
end
acts_as_liker
attr_accessible :email, :password, :password_confirmation, :remember_me, :name, :passion_ids, :competency_ids
attr_accessible :provider, :uid, :location, :description, :image, :headline, :industry, :organization_id, :mute_notifications
attr_accessible :avatar, :avatar_cache, :updated_at, :instance_url, :refresh_token, :interest_ids, :licensed_date, :active_license
attr_encrypted :salesforce_id, :key => KEY['salesforce']
attr_encrypted :access_key, :key => KEY['salesforce']
attr_encrypted :uid, :key => KEY['salesforce']
devise :invitable, :omniauthable, :omniauth_providers => [:linkedin, :developer, :salesforce]
belongs_to :managed_organization, :class_name => "Organization"
belongs_to :organization
has_and_belongs_to_many :mentorship_circles, join_table: 'mentorship_circles_users'
has_and_belongs_to_many :opportunities, join_table: 'opportunities_users'
has_many :competencies_users
has_many :competencies, :through => :competencies_users
has_many :assessment_reports
has_many :best_practices
has_many :coupon_uses
has_many :assessment_purchases
has_many :single_user_license_purchases
has_many :user_license_purchases
has_many :opportunity_purchases
has_many :recommendations
has_many :users_interests
has_many :testimonials
has_many :interests, :through => :users_interests
has_many :pac_members
has_many :fast_content
has_many :comments
has_many :points
has_many :badges
has_many :recommendation_applications
has_many :opportunity_applications
has_many :mentor_action_plans
has_many :coach_action_plans
has_many :volunteer_action_plans
has_many :user_groups, :foreign_key => 'member_id'
has_many :inquiries
has_many :groups, :through => :user_groups
scope :receives_email, -> { where(:mute_notifications => false) }
validates_uniqueness_of :uid, :scope => :provider, :allow_nil => true
mount_uploader :avatar, AvatarUploader
after_create :email_new_user
before_create :activate_license
def incomplete_profile?
sign_in_count % 3 == 0
description == nil
organization_id == nil
interests.empty?
location == nil
name == nil
end
def all_opportunities
@opp = self.opportunities
@opp2 = Opportunity.joins(:opportunity_applications).where("opportunity_applications.user_id" => self.id)
@opp3 = @opp + @opp2
end
def all_groups
groups + [organization]
end
def unique_groups
all_groups.uniq
end
def related_groups_users
[].tap do |related_users|
all_groups.each do |group|
related_users << group.all_users.reject { |group_user| group_user == self }
end
end.flatten.uniq
end
def all_pacs
@pac = Pac.where(:owner_id => self.id)
@pac2 = Pac.joins(:pac_members).where("pac_members.member_id" => self.id)
@pac3 = @pac + @pac2
end
def email_new_user
Notifier.new_user_welcome_email(self).deliver
end
def activate_license
self.active_license = true
self.licensed_date = Time.now
end
def taken_assessment?
assessment_reports.length > 0
end
def to_linkedin_client
LinkedinClient.new(self)
end
def connections(options = {})
to_linkedin_client.connections(options.fetch(:start), 16)
end
def owned_recommendations
Recommendation.where(:user_id => self.id)
end
def owned_opportunities
Opportunity.where(:owner_id => self.id)
end
def opportunities_with_feedback
Opportunity.with_feedback.where(:owner_id => self.id)
end
def current_opportunities
now = Time.now
owned_opportunities.where('end_year IS NULL OR (end_year > :year) OR (end_year = :year AND end_month >= :month)', :year => now.year, :month => now.month)
end
def past_opportunities
now = Time.now
owned_opportunities.where('end_year < :year OR (end_year = :year AND end_month < :month)', :year => now.year, :month => now.month)
end
def active_recommendations
now = Time.now
owned_recommendations.where('end_year IS NULL OR (end_year > :year) OR (end_year = :year AND end_month >= :month)', :year => now.year, :month => now.month)
end
def deactive_recommendations
now = Time.now
owned_recommendations.where('end_year < :year OR (end_year = :year AND end_month < :month)', :year => now.year, :month => now.month)
end
def self.find_or_create_from_auth_hash(auth_hash, current_user = nil)
user = current_user ||
User.where(
:provider => auth_hash.provider,
:uid => auth_hash.uid).first ||
User.find_by_email(auth_hash.info.email) ||
User.import(auth_hash)
return [] if user.nil?
if auth_hash.provider == "salesforce"
user.uid = auth_hash.uid
user.provider = auth_hash.provider
user.access_key = auth_hash.credentials.token
user.instance_url = auth_hash.credentials.instance_url
user.salesforce_id = auth_hash.extra.user_id
elsif auth_hash.provider == "linkedin"
user.uid = auth_hash.uid
user.provider = auth_hash.provider
user.access_key = auth_hash.extra.access_token.token
user.access_secret = auth_hash.extra.access_token.secret
user.description = user.to_linkedin_client.client.profile(:fields => %w[summary]).summary unless (!user.description.nil? && user.description.length > 0)
end
user.name ||= auth_hash.info.name
if user.persisted?
user.save!
end
changeset = {}
auth_hash.info.each do |k,v|
if user[k] != v && selectable_attributes.include?(k)
changeset[k] = v
else
next
end
end
[user, changeset]
end
def self.import(auth_hash)
user = User.new(attributes_to_user_hash(auth_hash))
if auth_hash.provider == "linkedin"
response = Net::HTTP.get_response(URI(auth_hash.info.image))
avatar = Tempfile.new(auth_hash.uid.to_s)
File.open(avatar.path + ".png", 'wb') do |f|
f.write response.body
end
user.avatar = File.open(avatar.path + ".png")
avatar.unlink
end
user.save!
user
end
def self.attributes_to_user_hash(auth_hash)
attributes = {
'email' => auth_hash.info.email,
'password' => Devise.friendly_token[0,20]
}
['name', 'location', 'headline'].each do |key|
attributes[key] = auth_hash.info.public_send(key)
end
attributes
end
def self.selectable_attributes
['name', 'location', 'description', 'headline', 'industry'].freeze
end
def non_profit_admin?
managed_organization.try(:type) == 'NonProfit'
end
def company_admin?
managed_organization.try(:type) == 'Company'
end
def admin?
non_profit_admin? || company_admin?
end
def has_child?(child)
children = self.send(child.class.name.downcase.pluralize)
children.exists?(:id => child.id)
end
def self.to_csv
CSV.generate do |csv|
csv << column_names
all.each do |user|
csv << user.attributes.values_at(*column_names)
end
end
end
def award_badge(badge_type_id)
unless has_current_badge?(badge_type_id.to_i)
badge = badges.create(badge_type_id: badge_type_id, year: Time.now.year)
Notifier.delay.new_badge_email(self, badge)
BadgeWorker.perform_async(badge.id)
end
end
def has_current_badge?(badge_type_id)
badges_for_current_year.map(&:badge_type_id).include?(badge_type_id)
end
private
def badges_for_current_year
badges.where(year: Time.now.year)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment