Sha256: a5d452382242e281e79edc9fd4b11887e0b00b2b961432b817cc99b22c9efa54

Contents?: true

Size: 1022 Bytes

Versions: 1

Compression:

Stored size: 1022 Bytes

Contents

module Kashiwamochi
  class Sort
    DIRS = {:asc => 'asc', :desc => 'desc'}.freeze

    def initialize(key, dir = nil)
      self.key = key
      self.dir = dir
    end

    def key
      @key
    end

    def key=(value)
      @key = Sort.sanitize(value)
    end

    def dir
      @dir
    end

    def dir=(value)
      @dir = Sort.sanitize_dir(value)
    end

    def toggle!
      @dir = asc? ? DIRS[:desc] : DIRS[:asc]
      self
    end

    def toggle
      self.dup.toggle!
    end

    def asc?
      @dir == DIRS[:asc]
    end

    def desc?
      @dir == DIRS[:desc]
    end

    def valid?
      @key.present?
    end

    def to_query
      "#{key} #{dir}"
    end

    def inspect
      "#<Sort #{key}: #{dir}>"
    end

    def self.sanitize(value)
      value.to_s.strip
    end

    def self.sanitize_dir(dir)
      sanitize(dir).downcase != DIRS[:desc] ? DIRS[:asc] : DIRS[:desc]
    end

    def self.parse(value)
      key, dir = sanitize(value).split(/\s+/, 2)
      new(key, dir)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
kashiwamochi-0.2.3 lib/kashiwamochi/sort.rb