Search code examples
ruby-datamapper

Is there a way to make a DataMapper Enum type be zero based?


Using DataMapper Enum type for the first time, and I noticed the first value in the enum translates to a 1. I need this to be zero based to be backward compatiable with another ORM layer in a different application also reading this database.


Solution

  • You should be able to monkey-patch enum.rb in dm-types to support this. You will need to replace the initialize method with a slightly modified copy where @flag_map[i+1] is replaced with @flag_map[i]:

    module DataMapper
      class Property
        class Enum < Object
    
          def initialize(model, name, options = {})
            @flag_map = {}
    
            flags = options.fetch(:flags, self.class.flags)
            flags.each_with_index do |flag, i|
              @flag_map[i] = flag
            end
    
            if self.class.accepted_options.include?(:set) && !options.include?(:set)
              options[:set] = @flag_map.values_at(*@flag_map.keys.sort)
            end
    
            super
          end # end initialize
    
        end # end class Enum
      end # end class Property
    end # end module DataMapper