Created
March 5, 2015 13:42
-
-
Save tmichel/382290732fa8fb46e709 to your computer and use it in GitHub Desktop.
Read out enum values from Postgres with ActiveRecord
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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