Class: Infobar::Message

Inherits:
Object show all
Extended by:
Tins::Delegate
Defined in:
lib/infobar/message.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Message

Returns a new instance of Message.



119
120
121
122
123
# File 'lib/infobar/message.rb', line 119

def initialize(opts = {})
  @format = opts.delete(:format) or
    raise ArgumentError, 'format option required'
  @opts = opts.each_with_object({}) { |(k, v), h| h[k.to_s] = v }
end

Instance Attribute Details

#formatObject (readonly) Also known as: to_s

Returns the value of attribute format.



146
147
148
# File 'lib/infobar/message.rb', line 146

def format
  @format
end

#optsObject (readonly)

Returns the value of attribute opts.



125
126
127
# File 'lib/infobar/message.rb', line 125

def opts
  @opts
end

Class Method Details

.directive_default_optionsObject



22
23
24
# File 'lib/infobar/message.rb', line 22

def directive_default_options
  @directive_default_options ||= {}
end

.directivesObject



18
19
20
# File 'lib/infobar/message.rb', line 18

def directives
  @directives ||= {}
end

.register(directive, **opts, &block) ⇒ Object



10
11
12
13
14
15
16
# File 'lib/infobar/message.rb', line 10

def register(directive, **opts, &block)
  directives.key?(directive) and
    warn "Overwriting old directive #{directive}."
  directives[directive]                = block
  directive_default_options[directive] = opts
  self
end

Instance Method Details

#directive_default_optionsObject



131
132
133
# File 'lib/infobar/message.rb', line 131

def directive_default_options
  self.class.directive_default_options
end

#directivesObject



127
128
129
# File 'lib/infobar/message.rb', line 127

def directives
  self.class.directives
end

#opts_for(directive) ⇒ Object



135
136
137
# File 'lib/infobar/message.rb', line 135

def opts_for(directive)
  @opts.fetch(directive, directive_default_options[directive])
end

#to_hashObject



150
151
152
153
154
# File 'lib/infobar/message.rb', line 150

def to_hash
  {
    format: format,
  }.merge(@opts)
end

#to_strObject



139
140
141
142
143
144
# File 'lib/infobar/message.rb', line 139

def to_str
  keys = directives.keys.sort_by { |k| -k.size }
  @format.gsub(/(?<!%)(#{keys * ?|})/) do
    directives[$1].call($1, opts_for($1))
  end
end