Class: ListTool::Data

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/list_tool/data.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ Data

Returns a new instance of Data.

Raises:

  • (ArgumentError)


8
9
10
11
12
13
14
15
16
17
18
# File 'lib/list_tool/data.rb', line 8

def initialize(hash = {})
  raise ArgumentError, 'argument is not a hash' unless hash.respond_to?(:to_hash)

  hash['lists'] ||= []
  raise ArgumentError, 'incorrect data given' unless hash['lists'].respond_to?(:to_ary)

  @lists = []
  hash['lists'].each { |list_data| add_list(list_data) }

  set_default_list(hash['default']) if hash['default']
end

Instance Attribute Details

#default_listObject (readonly)

Returns the value of attribute default_list.



6
7
8
# File 'lib/list_tool/data.rb', line 6

def default_list
  @default_list
end

#listsObject (readonly)

Returns the value of attribute lists.



6
7
8
# File 'lib/list_tool/data.rb', line 6

def lists
  @lists
end

Instance Method Details

#add_list(data) ⇒ Object



24
25
26
27
28
# File 'lib/list_tool/data.rb', line 24

def add_list(data)
  list = List.new(data)
  @lists << list
  list
end

#clear_list(index) ⇒ Object



36
37
38
39
# File 'lib/list_tool/data.rb', line 36

def clear_list(index)
  return nil if @lists[index] == nil
  @lists[index].clear!
end

#delete_list(index) ⇒ Object



30
31
32
33
34
# File 'lib/list_tool/data.rb', line 30

def delete_list(index)
  list = @lists.delete_at(index)
  @default_list = nil if @default_list == list
  list
end

#eachObject



20
21
22
# File 'lib/list_tool/data.rb', line 20

def each
  @lists.each { |list| yield(list) }
end

#move_list(index, direction) ⇒ Object



52
53
54
55
56
57
58
59
60
61
# File 'lib/list_tool/data.rb', line 52

def move_list(index, direction)
  case direction
  when :up
    return unless (1...@lists.length).include?(index)
    @lists[index], @lists[index-1] = @lists[index-1], @lists[index]
  when :down
    return unless (0...(@lists.length-1)).include?(index)
    @lists[index], @lists[index+1] = @lists[index+1], @lists[index]
  end
end

#rename_list(index, name) ⇒ Object



41
42
43
44
# File 'lib/list_tool/data.rb', line 41

def rename_list(index, name)
  return nil if @lists[index] == nil
  @lists[index].rename(name)
end

#set_default_list(index) ⇒ Object

Raises:

  • (ArgumentError)


46
47
48
49
50
# File 'lib/list_tool/data.rb', line 46

def set_default_list(index)
  raise ArgumentError, 'argument is not an integer' unless index.respond_to?(:to_int)
  return nil if @lists[index] == nil
  @default_list = @lists[index]
end

#to_jsonObject



63
64
65
66
67
68
69
70
71
72
# File 'lib/list_tool/data.rb', line 63

def to_json
  json = "{"
  json += "\"default\":#{@lists.index(@default_list)}," if @default_list
  json += "\"lists\":["
  @lists.each do |list|
    json += list.to_json
    json += ',' unless list == @lists.last
  end
  json += ']}'
end