-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathhelpers.rb
More file actions
87 lines (70 loc) · 2.24 KB
/
helpers.rb
File metadata and controls
87 lines (70 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#this helpers file contains lots of helpful little methods
#to make our work with sinatra easier
helpers do
#this defines three helpers, that all test our environment:
#they're called 'development?', 'test?', and 'production?'
[:development, :production, :test].each do |environment|
define_method "#{environment.to_s}?" do
return settings.environment == environment.to_sym
end
end
#this method returns the logged_in hacker
def current_user
#let's look up the Hacker by the id in the session
return Hacker.first(:id => session[:hacker_id]) if session[:hacker_id]
#if we can't find them, just return nil
nil
end
#this method returns true if we're logged in, and false if we're not
def logged_in?
#pretty easy, just check the session
current_user != nil
end
#this helper checks if the current_user is admin, and redirects them if they're not
def admin_only!(opts = {:return => "/"})
#we need to be both logged_in and an admin for this to work
unless logged_in? && current_user.admin?
#if we're not, set an error message
flash[:error] = "Sorry, buddy"
#and get redirected
redirect opts[:return]
end
end
#this method makes sure that we're logged in
def require_login!(opts = {:return => "/"})
#if we're not
unless logged_in?
#set an error message
flash[:error] = "Sorry, buddy"
#and get redirected
redirect opts[:return]
end
end
#this method lets us use an api call as well as logging in
def require_login_or_api!(opts = {:return => "/"})
hacker = Hacker.authenticate(opts[:username], opts[:password])
if hacker
session[:hacker_id] = hacker.id
else
require_login!(opts)
end
end
#gives a gravatar url for an email
def gravatar_url_for email
require 'md5'
"http://www.gravatar.com/avatar/#{MD5::md5(email.downcase)}"
end
end
#this lets us require a whole directory of .rb files!
def require_directory dirname
#we glob every file, and loop through them
Dir.glob("#{File.expand_path(File.dirname(__FILE__))}/#{dirname}/*.rb").each do |f|
#and then require them!
require f
end
end
class String
def to_slug
self.gsub(/[^a-zA-Z _0-9]/, "").gsub(/\s/, "_").downcase
end
end