Module: Consul::Power::ClassMethods
Constant Summary
collapse
- THREAD_KEY =
:'Power.current'
Instance Method Summary
collapse
#for_model, #for_record, #include_model!, #include_model?, #include_record!, #include_record?
Instance Method Details
#current ⇒ Object
83
84
85
|
# File 'lib/consul/power.rb', line 83
def current
Thread.current[THREAD_KEY]
end
|
#current=(power) ⇒ Object
87
88
89
|
# File 'lib/consul/power.rb', line 87
def current=(power)
Thread.current[THREAD_KEY] = power
end
|
#define_power(name, &block) ⇒ Object
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
|
# File 'lib/consul/power.rb', line 113
def define_power(name, &block)
name = name.to_s
if name.ends_with?('?')
name_without_suffix = name.chop
define_query_and_bang_methods(name_without_suffix, &block)
else
define_method(name, &block)
define_query_and_bang_methods(name) { |*args| default_include_power?(name, *args) }
begin
singular = singularize_power_name(name)
define_query_and_bang_methods(singular) { |*args| default_include_object?(name, *args) }
rescue Consul::PowerNotSingularizable
end
ids_method = power_ids_name(name)
define_method(ids_method) { |*args| default_power_ids(name, *args) }
memoize ids_method
end
name
end
|
#define_query_and_bang_methods(name, &query) ⇒ Object
106
107
108
109
110
111
|
# File 'lib/consul/power.rb', line 106
def define_query_and_bang_methods(name, &query)
query_method = "#{name}?"
bang_method = "#{name}!"
define_method(query_method, &query)
define_method(bang_method) { |*args| send(query_method, *args) or powerless!(name, *args) }
end
|
#power(*names, &block) ⇒ Object
71
72
73
74
75
|
# File 'lib/consul/power.rb', line 71
def power(*names, &block)
names.each do |name|
define_power(name, &block)
end
end
|
#power_ids_name(name) ⇒ Object
77
78
79
|
# File 'lib/consul/power.rb', line 77
def power_ids_name(name)
"#{name.to_s.singularize}_ids"
end
|
#singularize_power_name(name) ⇒ Object
135
136
137
138
139
140
141
142
143
|
# File 'lib/consul/power.rb', line 135
def singularize_power_name(name)
name = name.to_s
singularized = name.singularize
if singularized == name
raise Consul::PowerNotSingularizable, "Power name can not have an singular form: #{name}"
else
singularized
end
end
|
#with_power(inner_power, &block) ⇒ Object
91
92
93
94
95
96
97
98
99
100
|
# File 'lib/consul/power.rb', line 91
def with_power(inner_power, &block)
unless inner_power.is_a?(self) || inner_power.nil?
inner_power = new(inner_power)
end
old_power = current
self.current = inner_power
block.call
ensure
self.current = old_power
end
|
#without_power(&block) ⇒ Object
102
103
104
|
# File 'lib/consul/power.rb', line 102
def without_power(&block)
with_power(nil, &block)
end
|