Sha256: cc6d645e8b154d252ada3e05c5de7137705ba8cbfecb452be8131f94ea5c8699

Contents?: true

Size: 1.48 KB

Versions: 4

Compression:

Stored size: 1.48 KB

Contents

# Enums are used to build a sets of enumerated values.
#
# Numeric and bitwise enums are provided, and include provisions for assigned
# values and the allowance of gaps.
#
#   enum %w(N1 N2 +2 N3 N4 =7 N5 N6 3 N7)
#
# gives N1 = 0, N2 = 1, N3 = 4, N4 = 5, N5 = 7, N6 = 8 and N7 = 3
#
#   enum_bitwise %w(B1 B2 +2 B3 B4 =7 B5 B6 3 B7)
#
# gives B1 = 1, B2 = 2, B3 = 16, B4 = 32, B5 = 128, B6 = 256 and B7 = 8
module Eymiha
  class Enum
  
    private

    def self.build(arguments = {})
      code = <<EOF
def #{arguments[:method]}(*args)
  offset = 0
  bias = 0
  args.flatten.each_with_index do |const,i|
    case const
    when /^\\+(\\d+)$/
      offset = $1.to_i
      bias += 1
    when /^(\\=)?(\\d+)$/
      offset = $2.to_i - i
    else
      class_eval %(#{arguments[:enum_type]})
    end
  end
end
EOF
      arguments[:object].class_eval(code)
    end

    numeric = '#{const} = #{i+offset-bias}'
    bitwise = '#{const} = #{2**(i+offset-bias)}'

    Enum.build({ :object => Object,
                 :method => "self.enum",
                 :enum_type => numeric })

    Enum.build({ :object => Object,
                 :method => "self.bitwise_enum",
                 :enum_type => bitwise })

    Enum.build({ :object => Module,
                 :method => "enum",
                 :enum_type => numeric })

    Enum.build({ :object => Module,
                 :method => "bitwise_enum",
                 :enum_type => bitwise })

  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
eymiha_util-1.0.0 lib/eymiha/util/enum.rb
eymiha_util-1.0.1 lib/eymiha/util/enum.rb
eymiha_util-1.0.2 lib/eymiha/util/enum.rb
eymiha_util-1.0.3 lib/eymiha/util/enum.rb