Module Sass::Util
In: lib/sass/util/subset_map.rb
lib/sass/util/test.rb
lib/sass/util/cross_platform_random.rb
lib/sass/util/normalized_map.rb
lib/sass/util.rb

A module containing various useful functions. @comment

  rubocop:disable ModuleLength

Methods

Classes and Modules

Module Sass::Util::Test
Class Sass::Util::CrossPlatformRandom
Class Sass::Util::MultibyteStringScanner
Class Sass::Util::NormalizedMap
Class Sass::Util::SubsetMap

Constants

RUBY_VERSION_COMPONENTS = RUBY_VERSION.split(".").map {|s| s.to_i}   An array of ints representing the Ruby version number. @api public
RUBY_ENGINE = defined?(::RUBY_ENGINE) ? ::RUBY_ENGINE : "ruby"   The Ruby engine we‘re running under. Defaults to `"ruby"` if the top-level constant is undefined. @api public
CHARSET_REGEXP = /\A@charset "([^"]+)"/
UTF_8_BOM = bom.encode("UTF-8").force_encoding('BINARY')
UTF_16BE_BOM = bom.encode("UTF-16BE").force_encoding('BINARY')
UTF_16LE_BOM = bom.encode("UTF-16LE").force_encoding('BINARY')
VLQ_BASE_SHIFT = 5
VLQ_BASE = 1 << VLQ_BASE_SHIFT
VLQ_BASE_MASK = VLQ_BASE - 1
VLQ_CONTINUATION_BIT = VLQ_BASE
BASE64_DIGITS = ('A'..'Z').to_a + ('a'..'z').to_a + ('0'..'9').to_a + ['+', '/']
BASE64_DIGIT_MAP = begin map = {}

Public Instance methods

Throws a NotImplementedError for an abstract method.

@param obj [Object] `self` @raise [NotImplementedError]

Returns whether this environment is using ActionPack of a version greater than or equal to that specified.

@param version [String] The string version number to check against.

  Should be greater than or equal to Rails 3,
  because otherwise ActionPack::VERSION isn't autoloaded

@return [Boolean]

Returns whether this environment is using ActionPack version 3.0.0 or greater.

@return [Boolean]

Returns a sub-array of `minuend` containing only elements that are also in `subtrahend`. Ensures that the return value has the same order as `minuend`, even on Rubinius where that‘s not guaranteed by `Array#-`.

@param minuend [Array] @param subtrahend [Array] @return [Array]

Returns an ActionView::Template* class. In pre-3.0 versions of Rails, most of these classes were of the form `ActionView::TemplateFoo`, while afterwards they were of the form `ActionView;:Template::Foo`.

@param name [to_s] The name of the class to get.

  For example, `:Error` will return `ActionView::TemplateError`
  or `ActionView::Template::Error`.

Returns information about the caller of the previous method.

@param entry [String] An entry in the `caller` list, or a similarly formatted string @return [[String, Integer, (String, nil)]]

  An array containing the filename, line, and method name of the caller.
  The method name may be nil

Asserts that `value` falls within `range` (inclusive), leaving room for slight floating-point errors.

@param name [String] The name of the value. Used in the error message. @param range [Range] The allowed range of values. @param value [Numeric, Sass::Script::Value::Number] The value to check. @param unit [String] The unit of the value. Used in error reporting. @return [Numeric] `value` adjusted to fall within range, if it

  was outside by a floating-point margin.

Like {\check_encoding}, but also checks for a `@charset` declaration at the beginning of the file and uses that encoding if it exists.

Sass follows CSS‘s decoding rules.

@param str [String] The string of which to check the encoding @return [(String, Encoding)] The original string encoded as UTF-8,

  and the source encoding of the string (or `nil` under Ruby 1.8)

@raise [Encoding::UndefinedConversionError] if the source encoding

  cannot be converted to UTF-8

@raise [ArgumentError] if the document uses an unknown encoding with `@charset` @raise [Sass::SyntaxError] If the document declares an encoding that

  doesn't match its contents, or it doesn't declare an encoding and its
  contents are invalid in the native encoding.

Like `Pathname#cleanpath`, but normalizes Windows paths to always use backslash separators. Normally, `Pathname#cleanpath` actually does the reverse — it will convert backslashes to forward slashes, which can break `Pathname#relative_path_from`.

@param path [String, Pathname] @return [Pathname]

Prints a deprecation warning for the caller method.

@param obj [Object] `self` @param message [String] A message describing what to do instead.

Prepare a value for a destructuring assignment (e.g. `a, b = val`). This works around a performance bug when using ActiveSupport, and only needs to be called when `val` is likely to be `nil` reasonably often.

See [this bug report](redmine.ruby-lang.org/issues/4917).

@param val [Object] @return [Object]

Like `String.downcase`, but only ever downcases ASCII letters.

A version of `Enumerable#enum_cons` that works in Ruby 1.8 and 1.9.

@param enum [Enumerable] The enumerable to get the enumerator for @param n [Integer] The size of each cons @return [Enumerator] The consed enumerator

A version of `Enumerable#enum_slice` that works in Ruby 1.8 and 1.9.

@param enum [Enumerable] The enumerable to get the enumerator for @param n [Integer] The size of each slice @return [Enumerator] The consed enumerator

A version of `Enumerable#enum_with_index` that works in Ruby 1.8 and 1.9.

@param enum [Enumerable] The enumerable to get the enumerator for @return [Enumerator] The with-index enumerator

Destructively removes all elements from an array that match a block, and returns the removed elements.

@param array [Array] The array from which to remove elements. @yield [el] Called for each element. @yieldparam el [*] The element to test. @yieldreturn [Boolean] Whether or not to extract the element. @return [Array] The extracted elements.

Extracts the non-string vlaues from an array containing both strings and non-strings. These values are replaced with escape sequences. This can be undone using \{inject_values}.

This is useful e.g. when we want to do string manipulation on an interpolated string.

The precise format of the resulting string is not guaranteed. However, it is guaranteed that newlines and whitespace won‘t be affected.

@param arr [Array] The array from which values are extracted. @return [(String, Array)] The resulting string, and an array of extracted values.

Converts `path` to a "file:" URI. This handles Windows paths correctly.

@param path [String, Pathname] @return [String]

Flattens the first level of nested arrays in `arrs`. Unlike `Array#flatten`, this orders the result by taking the first values from each array in order, then the second, and so on.

@param arrs [Array] The array to flatten. @return [Array] The flattened array.

Like `Dir.glob`, but works with backslash-separated paths on Windows.

@param path [String]

Performs the equivalent of `enum.group_by.to_a`, but with a guaranteed order. Unlike {Util#hash_to_a}, the resulting order isn‘t sorted key order; instead, it‘s the same order as `group_by` has under Ruby 1.9 (key appearance order).

@param enum [Enumerable] @return [Array<[Object, Array]>] An array of pairs.

Checks to see if a class has a given method. For example:

    Sass::Util.has?(:public_instance_method, String, :gsub) #=> true

Method collections like `Class#instance_methods` return strings in Ruby 1.8 and symbols in Ruby 1.9 and on, so this handles checking for them in a compatible way.

@param attr [to_s] The (singular) name of the method-collection method

  (e.g. `:instance_methods`, `:private_methods`)

@param klass [Module] The class to check the methods of which to check @param method [String, Symbol] The name of the method do check for @return [Boolean] Whether or not the given collection has the given method

Converts a Hash to an Array. This is usually identical to `Hash#to_a`, with the following exceptions:

  • In Ruby 1.8, `Hash#to_a` is not deterministically ordered, but this is.
  • In Ruby 1.9 when running tests, this is ordered in the same way it would be under Ruby 1.8 (sorted key order rather than insertion order).

@param hash [Hash] @return [Array]

Undoes \{extract_values} by transforming a string with escape sequences into an array of strings and non-string values.

@param str [String] The string with escape sequences. @param values [Array] The array of values to inject. @return [Array] The array of strings and values.

Like `Object#inspect`, but preserves non-ASCII characters rather than escaping them under Ruby 1.9.2. This is necessary so that the precompiled Haml template can be `encode`d into `@options[:encoding]` before being evaluated.

@param obj {Object} @return {String}

Intersperses a value in an enumerable, as would be done with `Array#join` but without concatenating the array together afterwards.

@param enum [Enumerable] @param val @return [Array]

Whether or not this is running on IronRuby.

@return [Boolean]

Wehter or not this is running under JRuby 1.6 or lower.

Whether or not this is running on JRuby.

@return [Boolean]

Returns an array of ints representing the JRuby version number.

@return [Array<Integer>]

Escapes certain characters so that the result can be used as the JSON string value. Returns the original string if no escaping is necessary.

@param s [String] The string to be escaped @return [String] The escaped string

Converts the argument into a valid JSON value.

@param v [Integer, String, Array, Boolean, nil] @return [String]

Computes a single longest common subsequence for `x` and `y`. If there are more than one longest common subsequences, the one returned is that which starts first in `x`.

@param x [Array] @param y [Array] @yield [a, b] An optional block to use in place of a check for equality

  between elements of `x` and `y`.

@yieldreturn [Object, nil] If the two values register as equal,

  this will return the value to use in the LCS array.

@return [Array] The LCS

Returns whether this environment is using Listen version 2.0.0 or greater.

@return [Boolean]

Whether or not this is running under MacRuby.

@return [Boolean]

Maps the key-value pairs of a hash according to a block.

@example

  map_hash({:foo => "bar", :baz => "bang"}) {|k, v| [k.to_s, v.to_sym]}
    #=> {"foo" => :bar, "baz" => :bang}

@param hash [Hash] The hash to map @yield [key, value] A block in which the key-value pairs are transformed @yieldparam [key] The hash key @yieldparam [value] The hash value @yieldreturn [(Object, Object)] The new value for the `[key, value]` pair @return [Hash] The mapped hash @see map_keys @see map_vals

Maps the keys in a hash according to a block.

@example

  map_keys({:foo => "bar", :baz => "bang"}) {|k| k.to_s}
    #=> {"foo" => "bar", "baz" => "bang"}

@param hash [Hash] The hash to map @yield [key] A block in which the keys are transformed @yieldparam key [Object] The key that should be mapped @yieldreturn [Object] The new value for the key @return [Hash] The mapped hash @see map_vals @see map_hash

Maps the values in a hash according to a block.

@example

  map_values({:foo => "bar", :baz => "bang"}) {|v| v.to_sym}
    #=> {:foo => :bar, :baz => :bang}

@param hash [Hash] The hash to map @yield [value] A block in which the values are transformed @yieldparam value [Object] The value that should be mapped @yieldreturn [Object] The new value for the value @return [Hash] The mapped hash @see map_keys @see map_hash

Returns the maximum of `val1` and `val2`. We use this over \{Array.max} to avoid unnecessary garbage collection.

Concatenates all strings that are adjacent in an array, while leaving other elements as they are.

@example

  merge_adjacent_strings([1, "foo", "bar", 2, "baz"])
    #=> [1, "foobar", 2, "baz"]

@param arr [Array] @return [Array] The enumerable with strings merged

Returns the minimum of `val1` and `val2`. We use this over \{Array.min} to avoid unnecessary garbage collection.

Returns the ASCII code of the given character.

@param c [String] All characters but the first are ignored. @return [Integer] The ASCII code of `c`.

Converts a hash or a list of pairs into an order-preserving hash.

On Ruby 1.8.7, this uses the orderedhash gem to simulate an order-preserving hash. On Ruby 1.9 and up, it just uses the native Hash class, since that preserves the order itself.

@overload ordered_hash(hash)

  @param hash [Hash] a normal hash to convert to an ordered hash
  @return [Hash]

@overload ordered_hash(*pairs)

  @example
    ordered_hash([:foo, "bar"], [:baz, "bang"])
      #=> {:foo => "bar", :baz => "bang"}
    ordered_hash #=> {}
  @param pairs [Array<(Object, Object)>] the list of key/value pairs for
    the hash.
  @return [Hash]

Like `Pathname.new`, but normalizes Windows paths to always use backslash separators.

`Pathname#relative_path_from` can break if the two pathnames aren‘t consistent in their slash style.

@param path [String] @return [Pathname]

Return an array of all possible paths through the given arrays.

@param arrs [Array<Array>] @return [Array<Arrays>]

@example

  paths([[1, 2], [3, 4], [5]]) #=>
    # [[1, 3, 5],
    #  [2, 3, 5],
    #  [1, 4, 5],
    #  [2, 4, 5]]

Computes the powerset of the given array. This is the set of all subsets of the array.

@example

  powerset([1, 2, 3]) #=>
    Set[Set[], Set[1], Set[2], Set[3], Set[1, 2], Set[2, 3], Set[1, 3], Set[1, 2, 3]]

@param arr [Enumerable] @return [Set<Set>] The subsets of `arr`

Returns the environment of the Rails application, if this is running in a Rails context. Returns `nil` if no such environment is defined.

@return [String, nil]

Returns the root of the Rails application, if this is running in a Rails context. Returns `nil` if no such root is defined.

@return [String, nil]

Whether or not this is running on Rubinius.

@return [Boolean]

Returns `path` with all symlinks resolved.

@param path [String, Pathname] @return [Pathname]

Returns `path` relative to `from`.

This is like `Pathname#relative_path_from` except it accepts both strings and pathnames, it handles Windows path separators correctly, and it throws an error rather than crashing if the paths use different encodings (github.com/ruby/ruby/pull/713).

@param path [String, Pathname] @param from [String, Pathname] @return [Pathname?]

Non-destructively replaces all occurrences of a subsequence in an array with another subsequence.

@example

  replace_subseq([1, 2, 3, 4, 5], [2, 3], [:a, :b])
    #=> [1, :a, :b, 4, 5]

@param arr [Array] The array whose subsequences will be replaced. @param subseq [Array] The subsequence to find and replace. @param replacement [Array] The sequence that `subseq` will be replaced with. @return [Array] `arr` with `subseq` replaced with `replacement`.

Restricts a number to falling within a given range. Returns the number if it falls within the range, or the closest value in the range if it doesn‘t.

@param value [Numeric] @param range [Range<Numeric>] @return [Numeric]

Retries a filesystem operation if it fails on Windows. Windows has weird and flaky locking rules that can cause operations to fail.

@yield [] The filesystem operation.

Like [Fixnum.round], but leaves rooms for slight floating-point differences.

@param value [Numeric] @return [Numeric]

Whether or not this is running under a Ruby version under 2.0.

@return [Boolean]

Whether or not this is running under Ruby 1.8 or lower.

Note that IronRuby counts as Ruby 1.8, because it doesn‘t support the Ruby 1.9 encoding API.

@return [Boolean]

Whether or not this is running under Ruby 1.9.2 exactly.

@return [Boolean]

Whether or not this is running under Ruby 2.4 or higher.

@return [Boolean]

The same as `Kernel#warn`, but is silenced by \{silence_sass_warnings}.

@param msg [String]

Returns the path of a file relative to the Sass root directory.

@param file [String] The filename relative to the Sass root @return [String] The filename relative to the the working directory

Silences all Sass warnings within a block.

@yield A block in which no Sass warnings will be printed

Silence all output to STDERR within a block.

@yield A block in which no output will be printed to STDERR

Builds a sourcemap file name given the generated CSS file name.

@param css [String] The generated CSS file name. @return [String] The source map file name.

Destructively strips whitespace from the beginning and end of the first and last elements, respectively, in the array (if those elements are strings).

@param arr [Array] @return [Array] `arr`

Returns whether or not `seq1` is a subsequence of `seq2`. That is, whether or not `seq2` contains every element in `seq1` in the same order (and possibly more elements besides).

@param seq1 [Array] @param seq2 [Array] @return [Boolean]

Substitutes a sub-array of one array with another sub-array.

@param ary [Array] The array in which to make the substitution @param from [Array] The sequence of elements to replace with `to` @param to [Array] The sequence of elements to replace `from` with

Converts an array of `[key, value]` pairs to a hash.

@example

  to_hash([[:foo, "bar"], [:baz, "bang"]])
    #=> {:foo => "bar", :baz => "bang"}

@param arr [Array<(Object, Object)>] An array of pairs @return [Hash] A hash

Returns a string description of the character that caused an `Encoding::UndefinedConversionError`.

@param e [Encoding::UndefinedConversionError] @return [String]

Like `String.upcase`, but only ever upcases ASCII letters.

Returns whether one version string represents the same or a more recent version than another.

@param v1 [String] A version string. @param v2 [String] Another version string. @return [Boolean]

Returns whether one version string represents a more recent version than another.

@param v1 [String] A version string. @param v2 [String] Another version string. @return [Boolean]

Whether or not this is running on Windows.

@return [Boolean]

Allows modifications to be performed on the string form of an array containing both strings and non-strings.

@param arr [Array] The array from which values are extracted. @yield [str] A block in which string manipulation can be done to the array. @yieldparam str [String] The string form of `arr`. @yieldreturn [String] The modified string. @return [Array] The modified, interpolated array.

[Validate]