Module: KnifeAttribute::Delete

Included in:
Environment::EnvironmentAttributeDelete, Node::NodeAttributeDelete, Role::RoleAttributeDelete
Defined in:
lib/knife-attribute/delete.rb

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



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
# File 'lib/knife-attribute/delete.rb', line 3

def self.included(base)
  base.class_eval do
    include KnifeAttribute::CommonOptions

    def run
      check_arguments

      if config[:attribute_type]
        delete_attribute(entity.send(attribute_type_map[config[:attribute_type].to_sym]))
      else
        delete_attribute(entity.send(attribute_type_map[default_attribute_type]))
      end
    end

    private
      def check_arguments
        if entity_name.nil?
          show_usage
          ui.fatal("You must specify a #{entity_type.to_s} name")
          exit 1
        end

        if attribute.nil?
          show_usage
          ui.fatal('You must specify an attribute')
          exit 1
        end

        check_type
      end

      def delete_attribute(target)
        path = attribute.split('.')
        key = path.pop

        if path.length == 0
          parent = target
        else
          parent = path.inject(target) { |obj, subkey| obj[subkey] || break }
        end

        result = false
        if parent and parent.has_key?(key)
          parent.delete(key)
          result = entity.save
        end

        if result
          ui.info("Successfully deleted #{entity_type.to_s} #{ui.color(entity_name, :cyan)} attribute #{ui.color(attribute, :green)}")
        else
          ui.fatal("Failed deleting #{entity_type.to_s} #{ui.color(entity_name, :magenta)} attribute #{ui.color(new_attribute, :magenta)}")
          exit 1
        end
      end
  end
end