This repository has been archived by the owner on Sep 18, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
module_methods.rb
125 lines (103 loc) · 3 KB
/
module_methods.rb
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
require 'redis'
module Likeable
mattr_accessor :facepile_default_limit
self.facepile_default_limit = 9
### Module Methods ###
# ------------------ #
class << self
def classes
(@classes||[]).flatten
end
def classes=(*args)
@classes = args
end
# Likeable.model("Highlight")
# ------------------------- #
# turns a string into a model
# "Highlight".constantize # => Highlight; "Hi1i6ht".constantize = #=> false
def model(target_model)
target_model.camelcase.constantize
rescue NameError => ex
return false
end
# Likeable.find_by_resource_id("highlight", 22)
# ---------------------------------------- #
# #<Highlight id: ... # if highlight 22 exists
# nil # if highlight 22 does not exist
def find_by_resource_id(resource_name, target_id)
target = Likeable.get_class_for_resource_name(resource_name)
if target.present?
Likeable.find_one(target, target_id)
else
false
end
end
# Likeable.get_class_for_resource_name('photo')
# ------------------------- #
# Returns the class for the resource name
def get_class_for_resource_name(resource_name)
self.model(resource_name)
end
def get_resource_name_for_class(klass)
klass
end
def redis
@redis ||= Redis.new
end
def redis=(redis)
@redis = redis
end
def after_like(&block)
@after_like = block if block.present?
@after_like ||= lambda {|like|}
@after_like
end
def find_many=(find_many)
@find_many = find_many
end
def find_many(klass, ids)
@find_many ||= lambda {|klass, ids| klass.where(:id => ids)}
@find_many.call(klass, ids)
end
def find_one(klass, id)
@find_one ||= lambda {|klass, ids| klass.where(:id => id).first}
@find_one.call(klass, id)
end
def find_one=(find_one)
@find_one = find_one
end
def user_class
begin
@user_class ||= ::User
rescue NameError
nil
end
end
def user_class=(klass)
raise ArgumentError, "Argument must be a class" unless klass.is_a?(Class)
@user_class = klass
end
# Likeable.setup do |like|
# like.redis = Redis.new(#...)
# like.find_one = lambda {|klass, id | klass.where(:id => id)}
# like.find_many = lambda {|klass, ids| klass.where(:id => ids)}
# like.classes = Spot, Comment
# end
def include_in_class(klass, include_item)
case
when defined?(Rails::Application)
Rails::Application.class_eval do
config.to_prepare do
klass.send :include, include_item
end
end
else
klass.send :include, include_item
end
end
def setup(&block)
yield self unless block.blank?
true
end
end
end