Class: AttributedString

Inherits:
Object
  • Object
show all
Defined in:
lib/attributed_string.rb,
lib/attributed_string/version.rb,
lib/attributed_string/attribute.rb

Defined Under Namespace

Classes: Attribute

Constant Summary collapse

VERSION =
"0.1.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(string, attributes = []) ⇒ AttributedString

Returns a new instance of AttributedString.



8
9
10
11
# File 'lib/attributed_string.rb', line 8

def initialize(string, attributes = [])
  @string     = string
  @attributes = attributes
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



6
7
8
# File 'lib/attributed_string.rb', line 6

def attributes
  @attributes
end

#stringObject (readonly)

Returns the value of attribute string.



6
7
8
# File 'lib/attributed_string.rb', line 6

def string
  @string
end

Instance Method Details

#<<(attributed_string) ⇒ Object



13
14
15
16
# File 'lib/attributed_string.rb', line 13

def <<(attributed_string)
  @string << attributed_string.string
  @attributes += attributed_string.attributes
end

#fixObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/attributed_string.rb', line 28

def fix
  # Group into identical data structures
  grouped_attributes = @attributes.group_by { |a| a.data }.values

  # Sort each group into order
  grouped_attributes.each do |group|
    group.sort_by! { |a| a.range.begin }
  end

  # Merge attributes in identical groups together
  merged_attributes = grouped_attributes.map do |group|
    group.inject([]) do |attrs, a|
      if !attrs.empty? && attributes_overlap?(attrs.last, a)
        attrs[0...-1] + [merge_attributes(attrs.last, a)]
      else
        attrs + [a]
      end
    end
  end

  @attributes = merged_attributes.flatten
end

#lengthObject



24
25
26
# File 'lib/attributed_string.rb', line 24

def length
  @string.length
end

#prepend(attributed_string) ⇒ Object



18
19
20
21
22
# File 'lib/attributed_string.rb', line 18

def prepend(attributed_string)
  @string.prepend(attributed_string.string)
  move_attributes(attributed_string.length)
  @attributes += attributed_string.attributes
end