Module: NaturalSortJp
- Defined in:
- lib/natural_sort_jp.rb,
lib/natural_sort_jp/element.rb,
lib/natural_sort_jp/version.rb
Defined Under Namespace
Classes: Element
Constant Summary collapse
- VERSION =
'0.4.3'
Class Method Summary collapse
- .convert(title) ⇒ Object
- .referenced_by_attribute(obj, attribute) ⇒ Object
- .sort(array, by: nil, desc: false) ⇒ Object
- .sort_by(array, attribute) ⇒ Object
Class Method Details
.convert(title) ⇒ Object
17 18 19 20 21 22 23 24 25 |
# File 'lib/natural_sort_jp.rb', line 17 def self.convert(title) elements = title.to_s.scan(/([^0-90-9]*)([0-90-9]*)/).flatten converted = [] elements.each do |t| next if t.empty? converted << Element.new(t) end converted end |
.referenced_by_attribute(obj, attribute) ⇒ Object
27 28 29 30 31 32 33 |
# File 'lib/natural_sort_jp.rb', line 27 def self.referenced_by_attribute(obj, attribute) if obj.class == Hash obj[attribute] else obj.send(attribute) end end |
.sort(array, by: nil, desc: false) ⇒ Object
7 8 9 10 11 |
# File 'lib/natural_sort_jp.rb', line 7 def self.sort(array, by: nil, desc: false) array = by ? self.sort_by(array, by) : array.sort_by { |x| convert(x) } return array.reverse if desc array end |
.sort_by(array, attribute) ⇒ Object
13 14 15 |
# File 'lib/natural_sort_jp.rb', line 13 def self.sort_by(array, attribute) array.sort_by { |obj| convert(referenced_by_attribute(obj, attribute)) } end |