Sha256: 854442cda5fca5daf25ab35624066f05dc48d54d4bcd8a6b6a643419de3c0e48

Contents?: true

Size: 1.59 KB

Versions: 32

Compression:

Stored size: 1.59 KB

Contents

module R10K
  module Util

    # Allow for easy setting of instance options based on a hash
    #
    # This emulates the behavior of Ruby 2.0 named arguments, but since r10k
    # supports Ruby 1.8.7+ we cannot use that functionality.
    module Setopts

      private

      # @param opts [Hash]
      # @param allowed [Hash<Symbol, Symbol>]
      #
      # @example
      #   opts = {:one => "one value"}
      #   allowed => {:one => :self}
      #   setopts(opts, allowed)
      #   @one # => "one value"
      #
      # @example
      #   opts = {:uno => "one value"}
      #   allowed => {:one => :one, :uno => :one}
      #   setopts(opts, allowed)
      #   @one # => "one value"
      #
      # @example
      #
      #   opts = {:trace => "something"}
      #   allowed = {:trace => nil}
      #   setopts(opts, allowed)
      #   @trace # => nil
      #
      def setopts(opts, allowed)
        opts.each_pair do |key, value|
          if allowed.key?(key)
            rhs = allowed[key]
            case rhs
            when NilClass, FalseClass
              # Ignore nil options
            when :self, TrueClass
              # tr here is because instance variables cannot have hyphens in their names.
              instance_variable_set("@#{key}".tr('-','_').to_sym, value)
            else
              # tr here same as previous
              instance_variable_set("@#{rhs}".tr('-','_').to_sym, value)
            end
          else
            raise ArgumentError, _("%{class_name} cannot handle option '%{key}'") % {class_name: self.class.name, key: key}
          end
        end
      end
    end
  end
end

Version data entries

32 entries across 32 versions & 1 rubygems

Version Path
r10k-3.8.0 lib/r10k/util/setopts.rb
r10k-3.7.0 lib/r10k/util/setopts.rb
r10k-3.6.0 lib/r10k/util/setopts.rb
r10k-2.6.9 lib/r10k/util/setopts.rb
r10k-3.5.2 lib/r10k/util/setopts.rb
r10k-3.5.1 lib/r10k/util/setopts.rb
r10k-3.5.0 lib/r10k/util/setopts.rb
r10k-3.4.1 lib/r10k/util/setopts.rb
r10k-2.6.8 lib/r10k/util/setopts.rb
r10k-3.4.0 lib/r10k/util/setopts.rb
r10k-3.3.3 lib/r10k/util/setopts.rb
r10k-3.2.3 lib/r10k/util/setopts.rb
r10k-2.6.7 lib/r10k/util/setopts.rb
r10k-3.3.2 lib/r10k/util/setopts.rb
r10k-3.3.1 lib/r10k/util/setopts.rb
r10k-3.2.1 lib/r10k/util/setopts.rb
r10k-3.0.4 lib/r10k/util/setopts.rb
r10k-2.6.6 lib/r10k/util/setopts.rb
r10k-3.3.0 lib/r10k/util/setopts.rb
r10k-3.2.0 lib/r10k/util/setopts.rb