Module: Consul::Power::ClassMethods

Includes:
DynamicAccess::ClassMethods
Defined in:
lib/consul/power.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from DynamicAccess::ClassMethods

#for_model, #for_record, #include_model!, #include_model?, #include_record!, #include_record?

Instance Attribute Details

#currentObject

Returns the value of attribute current.



79
80
81
# File 'lib/consul/power.rb', line 79

def current
  @current
end

Instance Method Details

#context_count_name(name) ⇒ Object



71
72
73
# File 'lib/consul/power.rb', line 71

def context_count_name(name)
  "#{name}_context_count"
end

#define_power(name, &block) ⇒ Object



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/consul/power.rb', line 103

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) }
    if name.singularize != name
      define_query_and_bang_methods(name.singularize) { |*args| default_include_object?(name, *args) }
    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



96
97
98
99
100
101
# File 'lib/consul/power.rb', line 96

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



65
66
67
68
69
# File 'lib/consul/power.rb', line 65

def power(*names, &block)
  names.each do |name|
    define_power(name, &block)
  end
end

#power_ids_name(name) ⇒ Object



75
76
77
# File 'lib/consul/power.rb', line 75

def power_ids_name(name)
  "#{name.to_s.singularize}_ids"
end

#with_power(inner_power, &block) ⇒ Object



81
82
83
84
85
86
87
88
89
90
# File 'lib/consul/power.rb', line 81

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



92
93
94
# File 'lib/consul/power.rb', line 92

def without_power(&block)
  with_power(nil, &block)
end