Class: Alis::Store

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/alis/store.rb

Instance Method Summary collapse

Constructor Details

#initializeStore

Returns a new instance of Store.



8
9
10
11
12
13
# File 'lib/alis/store.rb', line 8

def initialize
  @store_file = Alis.store_file
  @data = FileTest.exists?(@store_file) ? YAML.load_file(@store_file) : {}
  @alias_cache = {}
  @cmd_cache = {}
end

Instance Method Details

#find_matched_alias(cmd, params_and_args) ⇒ Object



27
28
29
30
31
32
33
34
# File 'lib/alis/store.rb', line 27

def find_matched_alias(cmd, params_and_args)
  return nil unless @data[cmd]
  @data[cmd].keys.sort_by(&:size).reverse.each do |prms|
    first_params = params_and_args[0...(prms.size)]
    return get_alias(cmd, prms) if first_params == prms
  end
  nil
end

#get_alias(cmd, params) ⇒ Object



19
20
21
# File 'lib/alis/store.rb', line 19

def get_alias(cmd, params)
  @alias_cache[[cmd, params]] ||= fetch_alias(cmd, params)
end

#get_cmd(name) ⇒ Object



23
24
25
# File 'lib/alis/store.rb', line 23

def get_cmd(name)
  @cmd_cache[name] ||= fetch_cmd(name)
end

#has_cmd?(cmd) ⇒ Boolean

Returns:

  • (Boolean)


53
54
55
# File 'lib/alis/store.rb', line 53

def has_cmd?(cmd)
  !!@data[cmd]
end

#remove_alias(cmd, params) ⇒ Object



41
42
43
# File 'lib/alis/store.rb', line 41

def remove_alias(cmd, params)
  @data[cmd] && @data[cmd].delete(params)
end

#remove_allObject



49
50
51
# File 'lib/alis/store.rb', line 49

def remove_all
  @data = {}
end

#remove_cmd(cmd) ⇒ Object



45
46
47
# File 'lib/alis/store.rb', line 45

def remove_cmd(cmd)
  @data.delete(cmd)
end

#save!Object



15
16
17
# File 'lib/alis/store.rb', line 15

def save!
  File.open(@store_file, 'w'){ |f| YAML.dump(@data, f)}
end

#set_alias(cmd, params, exe, tail) ⇒ Object



36
37
38
39
# File 'lib/alis/store.rb', line 36

def set_alias(cmd, params, exe, tail)
  @data[cmd] ||= {}
  @data[cmd][params] = {:exe => exe, :tail => tail}
end

#to_sObject



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/alis/store.rb', line 58

def to_s
  cols  = [:alias, :exe, :tail]

  # alises to hash
  aliases = @data.map do |cmd, cmd_hash|
    cmd_hash.map do |params, opts| 
      aliaz = "#{cmd} #{params.join(' ')}"
      {:alias => aliaz, :exe => opts[:exe], :tail => opts[:tail]}
    end
  end.flatten

  # add headers
  aliases.unshift({:alias => "ALIAS", :exe => "EXECUTE", :tail => "TAIL"})
  width = cols.inject({}) do |h, col|

    h.merge({col => aliases.map{|a| a[col].size}.max})
  end

  aliases.map do |a|
    cols.map{|col| a[col].ljust(width[col]) }.join(" " * 5)
  end.join("\n")
end