Sha256: 60abd3a0b8b0db7cf1db06979c48a6dd6288db696a7e698530da9813a5447c4e

Contents?: true

Size: 1.6 KB

Versions: 73

Compression:

Stored size: 1.6 KB

Contents

require 'delegate'
require 'protobuf/enum'

##
# Adding extension to Numeric until
# we can get people to stop calling #value
# on EnumValue
class Numeric
  unless method_defined?(:value)
    def value
      self
    end
  end
end

module Protobuf
  class EnumValue < SimpleDelegator

    attr_reader :parent_class, :name

    ##
    # Constructor
    #
    def initialize(parent_class, name, value)
      @parent_class = parent_class
      @name = name
      @value = value
      super(@value)
    end

    # Overriding the class so ActiveRecord/Arel visitor will visit the enum as a Fixnum
    def class
      Fixnum
    end

    def inspect
      "\#<Protobuf::EnumValue #{@parent_class}::#{@name}=#{@value}>"
    end

    def to_i
      @value
    end

    def to_int
      @value.to_int
    end

    def to_s(format = :value_string)
      case format
      when :value_string then
        self.to_i.to_s
      when :name then
        name.to_s
      else
        self.to_i.to_s
      end
    end

    # Re-implement `try` in order to fix the problem where
    # the underlying fixnum doesn't respond to all methods (e.g. name or value).
    # If we respond to the first argument, `__send__` the args. Otherwise,
    # delegate the `try` call to the underlying vlaue fixnum.
    #
    def try(*args, &block)
      case
      when args.empty? && block_given?
        yield self
      when respond_to?(args.first)
        __send__(*args, &block)
      else
        @value.try(*args, &block)
      end
    end

    def value
      @value
    end

    ##
    # Instance Aliases
    #
    alias_method :to_hash_value, :to_i
  end
end

Version data entries

73 entries across 73 versions & 1 rubygems

Version Path
protobuf-2.8.13 lib/protobuf/enum_value.rb
protobuf-2.8.12 lib/protobuf/enum_value.rb
protobuf-2.8.11 lib/protobuf/enum_value.rb
protobuf-2.8.10 lib/protobuf/enum_value.rb
protobuf-2.8.9 lib/protobuf/enum_value.rb
protobuf-2.8.8 lib/protobuf/enum_value.rb
protobuf-2.8.7 lib/protobuf/enum_value.rb
protobuf-2.8.6 lib/protobuf/enum_value.rb
protobuf-2.7.12 lib/protobuf/enum_value.rb
protobuf-2.8.5 lib/protobuf/enum_value.rb
protobuf-2.8.4 lib/protobuf/enum_value.rb
protobuf-2.8.3 lib/protobuf/enum_value.rb
protobuf-2.8.2 lib/protobuf/enum_value.rb
protobuf-2.8.1 lib/protobuf/enum_value.rb
protobuf-2.8.0 lib/protobuf/enum_value.rb
protobuf-2.8.0.beta9-java lib/protobuf/enum_value.rb
protobuf-2.8.0.beta9 lib/protobuf/enum_value.rb
protobuf-2.8.0.beta8-java lib/protobuf/enum_value.rb
protobuf-2.8.0.beta8 lib/protobuf/enum_value.rb
protobuf-2.8.0.beta6-java lib/protobuf/enum_value.rb