Skip to content

Instantly share code, notes, and snippets.

@tmichel
Created March 5, 2015 13:42
Show Gist options
  • Select an option

  • Save tmichel/382290732fa8fb46e709 to your computer and use it in GitHub Desktop.

Select an option

Save tmichel/382290732fa8fb46e709 to your computer and use it in GitHub Desktop.
Read out enum values from Postgres with ActiveRecord
class PgEnum
attr_reader :type
def initialize(type)
@type = type.to_s
end
class << self
alias_method :for_type, :new
end
def values
@values ||= begin
q = "select unnest(enum_range(null::#{@type})) as value"
ActiveRecord::Base.connection.execute(q).values.flatten
end
rescue ActiveRecord::StatementInvalid => ex
Rails.logger.warn("#{@type} does not exists\n#{ex.backtrace}")
[]
end
end
require 'rails_helper'
describe PgEnum do
describe '#values' do
context 'with existing type' do
around(:example) do |ex|
ActiveRecord::Base.connection.execute("CREATE TYPE my_enum as ENUM ('apple', 'orange')")
ex.run
ActiveRecord::Base.connection.execute('DROP TYPE my_enum')
end
let(:enum) { PgEnum.for_type(:my_enum) }
it 'returns all values as an array' do
expect(enum.values).to eq(%w[apple orange])
end
end
it 'returns an empty array for non-existent types' do
enum = PgEnum.for_type(:non_existent)
expect(Rails.logger).to receive(:warn)
expect(enum.values).to eq([])
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment