Class: Labelized::LabelList

Inherits:
Array
  • Object
show all
Defined in:
lib/labelized/label_list.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ LabelList

Returns a new instance of LabelList.



10
11
12
# File 'lib/labelized/label_list.rb', line 10

def initialize(*args)
  add(*args)
end

Instance Attribute Details

#ownerObject

Returns the value of attribute owner.



8
9
10
# File 'lib/labelized/label_list.rb', line 8

def owner
  @owner
end

Class Method Details

.from(string) ⇒ Object

Returns a new LabelList using the given string.

LabelList.delimiter can be used to customize how labels in the string are delimited

Example:

LabelList.from("One , Two,  Three") # ["One", "Two", "Three"]


21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/labelized/label_list.rb', line 21

def self.from(string)
  glue   = delimiter.ends_with?(" ") ? delimiter : "#{delimiter} "
  string = string.join(glue) if string.respond_to?(:join)

  new.tap do |tag_list|
    string = string.to_s.dup

    # Parse the quoted labels
    string.gsub!(/(\A|#{delimiter})\s*"(.*?)"\s*(#{delimiter}\s*|\z)/) { tag_list << $2; $3 }
    string.gsub!(/(\A|#{delimiter})\s*'(.*?)'\s*(#{delimiter}\s*|\z)/) { tag_list << $2; $3 }

    tag_list.add(string.split(delimiter))
  end
end

Instance Method Details

#add(*names) ⇒ Object

Add labels to the list. Duplicate or blank labels will be ignored. Use the :parse option to add an unparsed label string.

Example:

list.add("Fun", "Happy")
list.add("Fun, Happy", :parse => true)


43
44
45
46
47
48
# File 'lib/labelized/label_list.rb', line 43

def add(*names)
  extract_and_apply_options!(names)
  concat(names)
  clean!
  self
end

#remove(*names) ⇒ Object

Remove specific labels from the list. Use the :parse option to add an unparsed label string.

Example:

list.remove("Sad", "Lonely")
list.remove("Sad, Lonely", :parse => true)


57
58
59
60
61
# File 'lib/labelized/label_list.rb', line 57

def remove(*names)
  extract_and_apply_options!(names)
  delete_if { |name| names.include?(name) }
  self
end

#to_sObject

Transform the list into a label string suitable for edting in a form. The labels are joined with LabelList.delimiter and quoted if necessary.

Example:

list = LabelList.new("Round", "Square,Cube")
list.to_s # 'Round, "Square,Cube"'


70
71
72
73
74
75
76
77
# File 'lib/labelized/label_list.rb', line 70

def to_s
  tags = frozen? ? self.dup : self
  tags.send(:clean!)

  tags.map do |name|
    name.include?(delimiter) ? "\"#{name}\"" : name
  end.join(delimiter.ends_with?(" ") ? delimiter : "#{delimiter} ")
end