Top Level Namespace

Defined Under Namespace

Modules: Morpheus Classes: Hash, NilClass

Constant Summary collapse

DEFAULT_TIME_FORMAT =
"%x %I:%M %p"

Instance Method Summary collapse

Instance Method Details

#display_appliance(name, url) ⇒ Object



155
156
157
# File 'lib/morpheus/formatters.rb', line 155

def display_appliance(name, url)
  "#{name} - #{url}"
end

#filter_data(data, include_fields = nil, exclude_fields = nil) ⇒ Object

filter_data filters Hash-like data to only the specified fields To specify fields of child objects, use a “.” Usage: filter_data(instance, [“id”, “name”, “plan.name”])



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/morpheus/formatters.rb', line 203

def filter_data(data, include_fields=nil, exclude_fields=nil)
  if !data
    return data
  elsif data.is_a?(Array)
    new_data = data.collect { |it| filter_data(it, include_fields, exclude_fields) }
    return new_data
  elsif data.is_a?(Hash)
    if include_fields
      #new_data = data.select {|k, v| include_fields.include?(k.to_s) || include_fields.include?(k.to_sym) }
      # allow extracting dot pathed fields, just like get_object_value
      my_data = {}
      include_fields.each do |field|
        if field.nil?
          next
        end
        field = field.to_s
        if field.empty?
          next
        end

        # supports "field as Label"
        field_key = field.strip
        field_label = field_key

        if field.index(/\s+as\s+/)
          field_key, field_label = field.split(/\s+as\s+/)
          if !field_label
            field_label = field_key
          end
        end

        if field.include?(".")
          #if field.index(/\s+as\s+/)
          if field_label != field_key
            # collapse to a value
            my_data[field_label] = get_object_value(data, field_key)
          else
            # keep the full object structure
            namespaces = field.split(".")
            cur_data = data
            cur_filtered_data = my_data
            namespaces.each_with_index do |ns, index|
              if index != namespaces.length - 1
                if cur_data && cur_data.respond_to?("key?")
                  cur_data = cur_data.key?(ns) ? cur_data[ns] : cur_data[ns.to_sym]
                else
                  cur_data = nil
                end
                cur_filtered_data[ns] ||= {}
                cur_filtered_data = cur_filtered_data[ns]
              else
                if cur_data && cur_data.respond_to?("key?")
                  cur_filtered_data[ns] = cur_data.key?(ns) ? cur_data[ns] : cur_data[ns.to_sym]
                else
                  cur_filtered_data[ns] = nil
                end
              end
            end
          end
        else
          #my_data[field] = data[field] || data[field.to_sym]
          my_data[field_label] = data.key?(field_key) ? data[field_key] : data[field_key.to_sym]
        end
      end
      return my_data
    elsif exclude_fields
      new_data = data.reject {|k, v| exclude_fields.include?(k.to_s) || exclude_fields.include?(k.to_sym) }
      return new_data
    end
  else
    return data # .clone
  end
end

#format_bytes(bytes, units = "B") ⇒ Object



277
278
279
280
281
282
283
284
285
286
287
# File 'lib/morpheus/formatters.rb', line 277

def format_bytes(bytes, units="B")
  out = ""
  if bytes
    if bytes < 1024 && units == "B"
      out = "#{bytes.to_i} B"
    else
      out = Filesize.from("#{bytes} #{units}").pretty.strip
    end
  end
  return out
end

#format_bytes_short(bytes) ⇒ Object

returns bytes in an abbreviated format eg. 3.1K instead of 3.10 KiB



291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'lib/morpheus/formatters.rb', line 291

def format_bytes_short(bytes)
  out = format_bytes(bytes)
  if out.include?(" ")
    val, units = out.split(" ")
    val = val.to_f
    # round to 0 or 1 decimal point
    if val % 1 == 0
      val = val.round(0).to_s
    else
      val = val.round(1).to_s
    end
    # K instead of KiB
    units = units[0].chr
    out = "#{val}#{units}"
  end
  return out
end

#format_date(dt, options = {}) ⇒ Object



57
58
59
# File 'lib/morpheus/formatters.rb', line 57

def format_date(dt, options={})
  format_dt(dt, options.merge({local: true}))
end

#format_dt(dt, options = {}) ⇒ Object



43
44
45
46
47
48
49
50
51
# File 'lib/morpheus/formatters.rb', line 43

def format_dt(dt, options={})
  dt = parse_time(dt)
  return "" if dt.nil?
  if options[:local]
    dt = dt.getlocal
  end
  format = options[:format] || DEFAULT_TIME_FORMAT
  return dt.strftime(format)
end

#format_dt_as_param(dt) ⇒ Object



65
66
67
68
# File 'lib/morpheus/formatters.rb', line 65

def format_dt_as_param(dt)
  dt = dt.getutc
  format_dt(dt, {format: "%Y-%m-%d %X"})
end

#format_duration(start_time, end_time = nil, format = "human") ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/morpheus/formatters.rb', line 70

def format_duration(start_time, end_time=nil, format="human")
  if !start_time
    return ""
  end
  start_time = parse_time(start_time)
  if end_time
    end_time = parse_time(end_time)
  else
    end_time = Time.now
  end
  seconds = (end_time - start_time).abs
  format_duration_seconds(seconds, format)
end

#format_duration_milliseconds(milliseconds, format = "human", ms_threshold = 1000) ⇒ Object



100
101
102
103
104
105
106
107
108
109
# File 'lib/morpheus/formatters.rb', line 100

def format_duration_milliseconds(milliseconds, format="human", ms_threshold=1000)
  out = ""
  milliseconds = milliseconds.abs.to_i
  if ms_threshold && ms_threshold > milliseconds
    out = "#{milliseconds}ms"
  else
    out = format_duration_seconds((milliseconds.to_f / 1000).floor, format)
  end
  out
end

#format_duration_seconds(seconds, format = "human") ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/morpheus/formatters.rb', line 84

def format_duration_seconds(seconds, format="human")
  seconds = seconds.abs
  out = ""
  # interval = Math.abs(interval)
  if format == "human"
    out = format_human_duration(seconds)
  elsif format
    interval_time = Time.mktime(0) + seconds
    out = interval_time.strftime(format)
  else
    interval_time = Time.mktime(0) + seconds
    out = interval_time.strftime("%H:%M:%S")
  end
  out
end

#format_human_duration(seconds) ⇒ Object

returns a human readable time duration

Parameters:

  • seconds
    • duration in seconds



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/morpheus/formatters.rb', line 113

def format_human_duration(seconds)
  out = ""
  #seconds = seconds.round
  days, hours, minutes = (seconds / (60*60*24)).floor, (seconds / (60*60)).floor, (seconds / (60)).floor
  if days > 365
    out << "#{days.floor} days"
  elsif days > 61
    out << "#{days.floor} days"
  elsif days > 31
    out << "#{days.floor} days"
  elsif days > 0
    if days.floor == 1
      out << "1 day"
    else
      out << "#{days.floor} days"
    end
  elsif hours > 1
    if hours == 1
      out << "1 hour"
    else
      out << "#{hours.floor} hours"
    end
  elsif minutes > 1
    if minutes == 1
      out << "1 minute"
    else
      out << "#{minutes.floor} minutes"
    end
  elsif seconds > 0 && seconds < 1
    ms = (seconds.to_f * 1000).to_i
    out << "#{ms}ms"
  else
    seconds = seconds.floor
    if seconds == 1
      out << "1 second"
    else
      out << "#{seconds} seconds"
    end
  end
  out
end

#format_local_date(dt, options = {}) ⇒ Object



61
62
63
# File 'lib/morpheus/formatters.rb', line 61

def format_local_date(dt, options={})
  format_dt(dt, {local: true, format: "%x"}.merge(options))
end

#format_local_dt(dt, options = {}) ⇒ Object



53
54
55
# File 'lib/morpheus/formatters.rb', line 53

def format_local_dt(dt, options={})
  format_dt(dt, {local: true}.merge(options))
end

#format_number(n, opts = {}) ⇒ Object



313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
# File 'lib/morpheus/formatters.rb', line 313

def format_number(n, opts={})
  delim = opts[:delimiter] || ','
  out = ""
  parts = n.to_s.split(".")
  whole_number = parts[0]
  decimal = parts[1] ? parts[1..-1].join('.') : nil
  i = 0
  whole_number.reverse.each_char do |c|
    out = (i > 0 && i % 3 == 0) ? "#{c}#{delim}#{out}" : "#{c}#{out}"
    i+= 1
  end
  if decimal
    out << "." + decimal
  end
  return out
end

#get_object_value(data, key) ⇒ Object

get_object_value returns a value within a Hash like object Usage: get_object_value(host, “plan.name”)



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/morpheus/formatters.rb', line 165

def get_object_value(data, key)
  value = nil
  if key.is_a?(Proc)
    return key.call(data)
  end
  key = key.to_s
  if key.include?(".")
    namespaces = key.split(".")
    value = data
    namespaces.each do |ns|
      if value.respond_to?("key?")
        if value.key?(ns.to_s)
          value = value[ns]
        elsif value.key?(ns.to_sym)
          value = value[ns.to_sym]
        else
          value = nil
        end
      else
        value = nil
      end
    end
  else
    # value = data.key?(key) ? data[key] : data[key.to_sym]
    if data.respond_to?("key?")
      if data.key?(key.to_s)
        value = data[key.to_s]
      elsif data.key?(key.to_sym)
        value = data[key.to_sym]
      end
    end
  end
  return value
end

#iso8601(dt) ⇒ Object



159
160
161
# File 'lib/morpheus/formatters.rb', line 159

def iso8601(dt)
  dt.instance_of(Time) ? dt.iso8601 : "#{dt}"
end

#no_colors(str) ⇒ Object



309
310
311
# File 'lib/morpheus/formatters.rb', line 309

def no_colors(str)
  str.to_s.gsub /\e\[\d+m/, ""
end

#parse_time(dt, format = nil) ⇒ Object

returns an instance of Time



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
# File 'lib/morpheus/formatters.rb', line 7

def parse_time(dt, format=nil)
  if dt.nil? || dt == '' || dt.to_i == 0
    return nil
  elsif dt.is_a?(Time)
    return dt
  elsif dt.is_a?(String)
    result = nil
    err = nil
    begin
      result = Time.parse(dt)
    rescue => e
      err = e
    end
    if !result
      format ||= DEFAULT_TIME_FORMAT
      if format
        begin
          result = Time.strptime(dt, format)
        rescue => e
          err = e
        end
      end
    end
    if result
      return result
    else
      raise "unable to parse time '#{dt}'. #{err}"
    end
    
  elsif dt.is_a?(Numeric)
    return Time.at(dt)
  else
    raise "bad argument type for parse_time() #{dt.class} #{dt.inspect}"
  end
end