diff --git a/Gemfile.lock b/Gemfile.lock index ef29911..caeebd2 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: . specs: - enumbler (0.6.3) + enumbler (0.6.4) activerecord (>= 5.2.3, < 6.1) activesupport (>= 5.2.3, < 6.1) diff --git a/lib/enumbler/enabler.rb b/lib/enumbler/enabler.rb index 9f77fb0..285be49 100644 --- a/lib/enumbler/enabler.rb +++ b/lib/enumbler/enabler.rb @@ -58,12 +58,14 @@ module ClassMethods # @param **attributes [Hash] optional: additional attributes and values that # will be saved to the database for this enumble record def enumble(enum, id, label: nil, **attributes) + raise_error_if_model_does_not_support_attributes(attributes) + + id = validate_id_is_numeric(enum, id) + @enumbles ||= Enumbler::Collection.new @enumbled_model = self @enumbler_label_column_name ||= :label - raise_error_if_model_does_not_support_attributes(attributes) - enumble = Enumble.new(enum, id, label: label, label_column_name: @enumbler_label_column_name, **attributes) if @enumbles.include?(enumble) @@ -313,6 +315,15 @@ def define_dynamic_methods_and_constants_for_enumbled_model(enumble) end end + # I accidentally forgot to provide an id one time and it was confusing as + # the last argument became the hash of options. This should help. + def validate_id_is_numeric(enum, id) + Integer(id) + rescue ArgumentError, TypeError + raise Enumbler::Error, + "You must provide a numeric primary key, like: `enumble :#{enum}, 1 `" + end + def raise_error_if_model_does_not_support_attributes(attributes) return if attributes.blank? diff --git a/lib/enumbler/version.rb b/lib/enumbler/version.rb index cdb0300..558772f 100644 --- a/lib/enumbler/version.rb +++ b/lib/enumbler/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Enumbler - VERSION = '0.6.3' + VERSION = '0.6.4' end diff --git a/spec/enumbler_spec.rb b/spec/enumbler_spec.rb index 1e3b96c..704eb75 100644 --- a/spec/enumbler_spec.rb +++ b/spec/enumbler_spec.rb @@ -81,6 +81,9 @@ class ModelWithoutTable < ApplicationRecord it 'raises an error when the same enumble is added twice' do expect { Color.enumble(:white, 1) }.to raise_error(Enumbler::Error, /twice/) end + it 'raises an error when no numeric id is passed as the second argument' do + expect { Color.enumble(:white, label: 'error') }.to raise_error(Enumbler::Error, /numeric/) + end it 'creates the constants' do expect(Color::BLACK).to eq 1 expect(Color::WHITE).to eq 2