Sha256: ac4762c761671b462812f46e024e0935bed6980d30337778e68f28dbde3ccad7

Contents?: true

Size: 985 Bytes

Versions: 4

Compression:

Stored size: 985 Bytes

Contents

# frozen_string_literal: true

module SwitchUser
  class UserLoader
    attr_reader :scope
    attr_accessor :id

    def self.prepare(*args)
      options = args.extract_options!

      if options[:scope_identifier]
        options[:scope_identifier] =~ /^(.*)_([^_]+)$/
        scope = Regexp.last_match(1)
        id = Regexp.last_match(2)
      else
        scope, id = args
      end
      new(scope, id)
    end

    def initialize(scope, id)
      self.scope = scope
      self.id = id
    end

    def user
      user_class.where(column_name => id).first
    end

    private

    def scope=(scope)
      if scope && SwitchUser.available_scopes.include?(scope.to_sym)
        @scope = scope
      else
        raise InvalidScope, "#{scope} is invalid and is not listed in SwitchUser#available_users"
      end
    end

    def user_class
      scope.classify.constantize
    end

    def column_name
      SwitchUser.available_users_identifiers[scope.to_sym]
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
switch_user-1.5.4 lib/switch_user/user_loader.rb
switch_user-1.5.3 lib/switch_user/user_loader.rb
switch_user-1.5.2 lib/switch_user/user_loader.rb
switch_user-1.5.1 lib/switch_user/user_loader.rb