diff --git a/Gemfile.lock b/Gemfile.lock index c6883bc..a1354c6 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -7,7 +7,13 @@ PATH GEM remote: https://rubygems.org/ specs: - activesupport (7.1.1) + activemodel (7.1.3.2) + activesupport (= 7.1.3.2) + activerecord (7.1.3.2) + activemodel (= 7.1.3.2) + activesupport (= 7.1.3.2) + timeout (>= 0.4.0) + activesupport (7.1.3.2) base64 bigdecimal concurrent-ruby (~> 1.0, >= 1.0.2) @@ -92,6 +98,7 @@ GEM sqlite3 (1.7.3) mini_portile2 (~> 2.8.0) thor (1.2.2) + timeout (0.4.1) tzinfo (2.0.6) concurrent-ruby (~> 1.0) unicode-display_width (2.5.0) @@ -100,6 +107,7 @@ PLATFORMS ruby DEPENDENCIES + activerecord appraisal bundler enumerate_it! diff --git a/enumerate_it.gemspec b/enumerate_it.gemspec index cefe114..cce98dd 100644 --- a/enumerate_it.gemspec +++ b/enumerate_it.gemspec @@ -22,6 +22,7 @@ Gem::Specification.new do |gem| gem.add_dependency 'activesupport', '>= 5.0.7.2' + gem.add_development_dependency 'activerecord' gem.add_development_dependency 'appraisal' gem.add_development_dependency 'bundler' gem.add_development_dependency 'pry' diff --git a/lib/enumerate_it/class_methods.rb b/lib/enumerate_it/class_methods.rb index b4e2460..dbb92f2 100644 --- a/lib/enumerate_it/class_methods.rb +++ b/lib/enumerate_it/class_methods.rb @@ -5,6 +5,7 @@ def has_enumeration_for(attribute, options = {}) define_enumeration_class(attribute, options) create_enumeration_humanize_method(options[:with], attribute) + create_enumeration_key_method(options[:with], attribute) store_enumeration(options[:with], attribute) handle_options(attribute, options) @@ -38,6 +39,16 @@ def create_enumeration_humanize_method(klass, attribute_name) end end + def create_enumeration_key_method(klass, attribute_name) + class_eval do + define_method "#{attribute_name}_key" do + value = public_send(attribute_name) + + value ? klass.key_for(value) : nil + end + end + end + def create_helper_methods(klass, attribute_name, helpers) prefix_name = "#{attribute_name}_" if helpers.is_a?(Hash) && helpers[:prefix] diff --git a/spec/enumerate_it_spec.rb b/spec/enumerate_it_spec.rb index 5c06356..e5b4146 100644 --- a/spec/enumerate_it_spec.rb +++ b/spec/enumerate_it_spec.rb @@ -28,6 +28,15 @@ def initialize(foobar) expect(target.foobar_humanize).to be_nil end + it 'creates the key method' do + expect(target.foobar_key).to eq(:value_2) + end + + it 'if the attribute is blank, the key method returns nil' do + target.foobar = nil + expect(target.foobar_key).to be_nil + end + it 'defaults to not creating helper methods' do expect(target).not_to respond_to(:value_1?) end