Sha256: 8a477a6b0dc4a5b464763dc9624f7dce1773d99c9fda79976f1b676ef30f8456

Contents?: true

Size: 1.44 KB

Versions: 11

Compression:

Stored size: 1.44 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
              instance_variable_set("@#{key}".to_sym, value)
            else
              instance_variable_set("@#{rhs}".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

11 entries across 11 versions & 1 rubygems

Version Path
r10k-2.5.5 lib/r10k/util/setopts.rb
r10k-2.5.4 lib/r10k/util/setopts.rb
r10k-2.5.3 lib/r10k/util/setopts.rb
r10k-2.5.2 lib/r10k/util/setopts.rb
r10k-2.5.1 lib/r10k/util/setopts.rb
r10k-2.4.5 lib/r10k/util/setopts.rb
r10k-2.4.4 lib/r10k/util/setopts.rb
r10k-2.5.0 lib/r10k/util/setopts.rb
r10k-2.4.3 lib/r10k/util/setopts.rb
r10k-2.4.1 lib/r10k/util/setopts.rb
r10k-2.4.0 lib/r10k/util/setopts.rb