Class: Submarine

Inherits:
Object
  • Object
show all
Defined in:
lib/submarine/submarine.rb,
lib/submarine/exceptions.rb

Defined Under Namespace

Classes: Configuration, MissingAttributesError, MissingFormatKeyError

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*attrs) ⇒ Submarine

Constructs a new Submarine instance. Set instance variable and readers based on input hash.



6
7
8
9
10
11
12
13
14
15
16
# File 'lib/submarine/submarine.rb', line 6

def initialize *attrs
  raise MissingAttributesError unless attrs_provided?(attrs)
  raise MissingFormatKeyError unless attrs_includes_format_key?(attrs)

  attrs = attrs.first.merge(config.substitutions) # merge Configuration defaults

  attrs.each do |key, value|
    self.instance_variable_set("@#{key}", value) 
    self.class.class_eval{attr_reader key}
  end
end

Class Method Details

.configObject

Global Submarine configuration getter. Returns the current configuration options.

Example:

>> Submarine.config
=> #<Submarine::Configuration @format_key=:text, @left_delimiter="[[", @right_delimiter="]]", @substitutions={}>


46
47
48
# File 'lib/submarine/submarine.rb', line 46

def config
  @config ||= Configuration.new
end

.configure {|config| ... } ⇒ Object

Global Submarine configuration setter. The global default Submarine::Configuration options can be overwritten by passing a block to config and setting new options.

Example:

# config/initializers/submarine.rb  <-- if you're using Rails, say
Submarine.configure do |config|
  config.format_key = :copy
  config.left_delimiter = '<^'
  config.right_delimiter = '^>'
  config.substitutions = {company: 'Submarine Inc, Co'}
end

>> Submarine.config
=> #<Submarine::Configuration @format_key=:copy, @left_delimiter="<^", @right_delimiter="^>", @substitutions={company: 'Submarine Inc, Co'}>

Yields:



66
67
68
# File 'lib/submarine/submarine.rb', line 66

def configure
  yield config
end

Instance Method Details

#format!Object

Destructively format the Submarine instance. Returns the formatted string.

Example:

>> sub = Submarine.new(text: 'Hello, my name is [[name]].', name: 'Joe')
=> #<Submarine @text="Hello, my name is [[name]].", @name="Joe">
>> sub.format!
=> "Hello, my name is Joe."
>> sub
=> #<Submarine @text="Hello, my name is Joe.", @name="Joe">

And, obviously, one line makes it more succinct:

>> Submarine.new(text: 'Hello, my name is [[name]].', name: 'Joe').format!
=> "Hello, my name is Joe."


33
34
35
36
# File 'lib/submarine/submarine.rb', line 33

def format!
  substitutions.each{|s| sub_string.gsub!(match(s), replace(s))}
  sub_string
end