Class: ListTool::Lister

Inherits:
Object
  • Object
show all
Defined in:
lib/list_tool/lister.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeLister

Returns a new instance of Lister.



4
5
6
# File 'lib/list_tool/lister.rb', line 4

def initialize
  @data = ListerData.new
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/list_tool/lister.rb', line 55

def method_missing(method_name, *args, &block)
  if method_name =~ /_list$/
    receiver = @data
  elsif method_name =~ /_item$/
    if args[-1].is_a?(Hash) && args[-1].has_key?(:list)
      # then last argument is an options hash
      options = args.pop
      index = options[:list]
    end
    receiver = get_list(index)
    receiver || raise(ListNotFoundError, "list with given index doesn't exist")
  else
    super
  end

  receiver.send(method_name, *args, &block)
rescue NoMethodError => e
  raise NoMethodError, "undefined method '#{method_name.to_s}' for #{self.inspect}"
end

Class Method Details

.from_hash(hash) ⇒ Object



9
10
11
12
13
# File 'lib/list_tool/lister.rb', line 9

def from_hash(hash)
  lister = Lister.new
  lister.instance_variable_set(:@data, ListerData.new(hash))
  lister
end

.from_json(json) ⇒ Object



15
16
17
18
# File 'lib/list_tool/lister.rb', line 15

def from_json(json)
  data = JsonParser.parse(json)
  from_hash(data)
end

Instance Method Details

#default_listObject



46
47
48
49
50
51
52
53
# File 'lib/list_tool/lister.rb', line 46

def default_list
  if @data.default_list
    list = @data.default_list
    { name: list.name, items: list.items.map{|item| item.text} }
  else
    nil
  end
end

#inspectObject



21
22
23
# File 'lib/list_tool/lister.rb', line 21

def inspect
  "#<#{self.class}:0x#{self.__id__.to_s(16)}>"
end

#list(index = nil) ⇒ Object



39
40
41
42
43
44
# File 'lib/list_tool/lister.rb', line 39

def list(index=nil)
  list = get_list(index)
  return nil if list.nil?

  { name: list.name, items: list.items.map{|item| item.text} }
end

#listsObject



35
36
37
# File 'lib/list_tool/lister.rb', line 35

def lists
  Hash[*@data.map{|list| [list.name, list.items.count] }.flatten]
end

#load(filename) ⇒ Object



25
26
27
28
29
# File 'lib/list_tool/lister.rb', line 25

def load(filename)
  json = FileManager.load(filename)
  @data = ListerData.new( JsonParser.parse(json) )
  self
end

#save(filename) ⇒ Object



31
32
33
# File 'lib/list_tool/lister.rb', line 31

def save(filename)
  FileManager.save(filename, @data)
end