Class: Ditty::User

Inherits:
Sequel::Model
  • Object
show all
Includes:
Base
Defined in:
lib/ditty/models/user.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Base

#for_json

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_sym, *arguments, &block) ⇒ Object



25
26
27
28
29
30
31
# File 'lib/ditty/models/user.rb', line 25

def method_missing(method_sym, *arguments, &block)
  if respond_to_missing?(method_sym)
    role?(method_sym[0..-2])
  else
    super
  end
end

Class Method Details

.anonymous_userObject



72
73
74
75
# File 'lib/ditty/models/user.rb', line 72

def anonymous_user
  role = ::Ditty::Role.find_or_create(name: 'anonymous')
  ::Ditty::User.where(roles: role).first
end

.create_anonymous_user(email = '[email protected]') ⇒ Object



77
78
79
80
81
82
83
# File 'lib/ditty/models/user.rb', line 77

def create_anonymous_user(email = '[email protected]')
  return if anonymous_user

  user = ::Ditty::User.find_or_create(email: email)
  user.remove_role ::Ditty::Role.find_or_create(name: 'user')
  user.add_role ::Ditty::Role.find_or_create(name: 'anonymous') unless user.role?('anonymous')
end

Instance Method Details

#after_createObject

Add the basic roles and identity



52
53
54
55
# File 'lib/ditty/models/user.rb', line 52

def after_create
  super
  check_roles
end

#check_rolesObject



57
58
59
60
61
62
# File 'lib/ditty/models/user.rb', line 57

def check_roles
  return if roles_dataset.first(name: 'anonymous')
  return if roles_dataset.first(name: 'user')

  add_role Role.find_or_create(name: 'user')
end

#gravatarObject



37
38
39
40
# File 'lib/ditty/models/user.rb', line 37

def gravatar
  hash = Digest::MD5.hexdigest(email.downcase)
  "https://www.gravatar.com/avatar/#{hash}"
end

#respond_to_missing?(name, _include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


33
34
35
# File 'lib/ditty/models/user.rb', line 33

def respond_to_missing?(name, _include_private = false)
  name[-1] == '?'
end

#role?(check) ⇒ Boolean

Returns:

  • (Boolean)


18
19
20
21
22
23
# File 'lib/ditty/models/user.rb', line 18

def role?(check)
  @roles ||= Hash.new do |h, k|
    h[k] = !roles_dataset.first(name: k).nil?
  end
  @roles[check]
end

#usernameObject



64
65
66
67
68
69
# File 'lib/ditty/models/user.rb', line 64

def username
  identity = identity_dataset.first
  return identity.username if identity

  email
end

#validateObject



42
43
44
45
46
47
48
49
# File 'lib/ditty/models/user.rb', line 42

def validate
  super
  validates_presence :email
  return if email.blank?

  validates_unique :email
  validates_format(/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :email)
end