Module: Ekylibre::Record::Acts::Protected::ClassMethods

Defined in:
lib/ekylibre/record/acts/protected.rb

Instance Method Summary collapse

Instance Method Details

#protect(options = {}, &block) ⇒ Object

Blocks update or destroy if necessary


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
# File 'lib/ekylibre/record/acts/protected.rb', line 19

def protect(options = {}, &block)
  options[:on] = [:update, :destroy] unless options[:on]
  code = ''.c
  for callback in [options[:on]].flatten
    method_name = "protected_on_#{callback}?".to_sym

    code << "before_#{callback} :raise_exception_unless_#{callback}able?\n"

    code << "def raise_exception_unless_#{callback}able?\n"
    code << "  unless self.#{callback}able?\n"
    if options[:"allow_#{callback}_on"]
      code << '  if self.changed.any? { |e| !' + options[:"allow_#{callback}_on"].to_s + ".include? e }\n"
    end
    code << "      raise RecordNot#{callback.to_s.camelcase}able.new('Record cannot be #{callback}d', self)\n"
    code << "  end\n" if options[:"allow_#{callback}_on"]
    code << "  end\n"
    code << "end\n"

    code << "def #{callback}able?\n"
    code << "  !#{method_name}\n"
    code << "end\n"

    define_method(method_name, &block) if block_given?
  end
  class_eval code
end

#secure(options = {}, &block) ⇒ Object

Blocks update or destroy if necessary If result is false, it stops intervention


48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/ekylibre/record/acts/protected.rb', line 48

def secure(options = {}, &block)
  options[:on] = [:update, :destroy] unless options[:on]
  code = ''.c
  for callback in [options[:on]].flatten
    method_name = "secured_on_#{callback}?".to_sym

    code << "before_#{callback} :secure_#{callback}ability!\n"

    code << "def secure_#{callback}ability!\n"
    code << "  unless self.#{callback}able?\n"
    code << "    raise RecordNot#{callback.to_s.camelcase}able.new('Record cannot be #{callback}d because it is secured', self)\n"
    code << "  end\n"
    code << "end\n"

    code << "def #{callback}able?\n"
    code << "  #{method_name}\n"
    code << "end\n"

    define_method(method_name, &block) if block_given?
  end
  class_eval code
end