Sha256: 56fc410d2af039f30d5501974746023c3c1b279c2b367fc49577fc30a12ec28c

Contents?: true

Size: 821 Bytes

Versions: 1

Compression:

Stored size: 821 Bytes

Contents

# NOTE: https://blog.daveallie.com/clean-monkey-patching/

require 'active_support/core_ext/array'

module Ensurance
  module ArrayEnsure
    def self.prepended(base)
      base.singleton_class.prepend(ClassMethods)
    end

    module ClassMethods
      def ensure(thing)
        case thing.class.name
        when 'NilClass'
          nil
        when 'Hash'
          thing.to_a
        when 'String'
          begin
            JSON.parse(thing).to_a
          rescue JSON::ParserError
            thing.split(',')
          end
        else
          Array(thing)
        end
      end

      def ensure!(thing)
        result = self.ensure(thing)
        raise ArgumentError, "Cannot Array.ensure(#{thing || 'nil'})" unless result
        result
      end
    end
  end
end

::Array.prepend(Ensurance::ArrayEnsure)

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ensurance-0.1.13 lib/ensurance/array_ensure.rb