Sha256: 7d403e990c5dd154997ff89feb41b996baaf4b98a60864967819de9671e48d49

Contents?: true

Size: 1016 Bytes

Versions: 6

Compression:

Stored size: 1016 Bytes

Contents

module ActiveRecord
  module PGEnum
    module Helper
      def self.included(klass)
        klass.extend ClassMethods
      end

      module ClassMethods
        # Declare an enum attribute where the values map to strings enforced by PostgreSQL's
        # enumerated types.
        #
        #   class Conversation < ActiveRecord::Base
        #     include ActiveRecord::PGEnum::Helper
        #
        #     pg_enum status: %i[active archived]
        #   end
        #
        # This is merely a wrapper over traditional enum syntax so that you can define
        # string-based enums with an array of values.
        def pg_enum(definitions)
          values = definitions.values.map do |value|
            if value.is_a? Array
              keys   = value.map(&:to_sym)
              values = value.map(&:to_s)

              Hash[keys.zip(values)]
            else
              value
            end
          end

          enum Hash[definitions.keys.zip(values)]
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
activerecord-pg_enum-0.3.0 lib/active_record/pg_enum/helper.rb
activerecord-pg_enum-0.2.1 lib/active_record/pg_enum/helper.rb
activerecord-pg_enum-0.2.0 lib/active_record/pg_enum/helper.rb
activerecord-pg_enum-0.1.1 lib/active_record/pg_enum/helper.rb
activerecord-pg_enum-0.1.0 lib/active_record/pg_enum/helper.rb
activerecord-pg_enum-0.0.1 lib/active_record/pg_enum/helper.rb