Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

initial commit

  • Loading branch information...
commit 7dc601e7957681ed559191a479e639420a241c66 0 parents
@kenn authored
17 .gitignore
@@ -0,0 +1,17 @@
+*.gem
+*.rbc
+.bundle
+.config
+.yardoc
+Gemfile.lock
+InstalledFiles
+_yardoc
+coverage
+doc/
+lib/bundler/man
+pkg
+rdoc
+spec/reports
+test/tmp
+test/version_tmp
+tmp
1  .rspec
@@ -0,0 +1 @@
+--color
3  Gemfile
@@ -0,0 +1,3 @@
+source 'https://rubygems.org'
+
+gemspec
22 LICENSE.txt
@@ -0,0 +1,22 @@
+Copyright (c) 2012 Kenn Ejima
+
+MIT License
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
114 README.md
@@ -0,0 +1,114 @@
+# EnumAccessor - Simple enum fields for ActiveRecord
+
+EnumAccessor lets you define enum for attributes, and store them as integer-encoded values.
+
+Compatible with ActiveRecord 3 or later.
+
+## Usage
+
+Add this line to your application's Gemfile.
+
+```ruby
+gem 'enum_accessor'
+```
+
+Define:
+
+```ruby
+class User < ActiveRecord::Base
+ enum_accessor :gender, [ :female, :male ]
+end
+```
+
+Migration:
+
+```ruby
+create_table :users do |t|
+ t.column :gender, :integer, default: 0
+end
+```
+
+Now
+
+```ruby
+User.genders # => { :female => 0, :male => 1 }
+
+user = User.new
+user.gender # => :female
+user.gender_female? # => true
+user.gender_raw # => 0
+
+user.gender = :male
+user.gender_male? # => true
+user.gender_raw # => 1
+```
+
+## Manual coding
+
+There are times when it makes more sense to manually pick particular integers for the mapping.
+
+Just pass a hash with coded integer values.
+
+```ruby
+enum_accessor :status, ok: 200, bad_request: 400, not_found: 404, internal_server_error: 500, service_unavailable: 503
+```
+
+## Scoping query
+
+To retrieve internal integer values for query, use `User.genders`.
+
+```ruby
+User.where(gender: User.genders(:female))
+```
+
+## i18n
+
+EnumAccessor supports i18n just as ActiveModel does.
+
+Add the following lines to `config/locales/ja.yml`
+
+```yaml
+ja:
+ enum_accessor:
+ user:
+ gender:
+ female:
+ male:
+```
+
+and now `human_*` method returns a translated string. It defaults to English nicely as well.
+
+```ruby
+I18n.locale = :ja
+user.human_gender # => '女'
+
+I18n.locale = :en
+user.human_gender # => 'Female'
+```
+
+## Why enum keys are internally stored as strings rather than symbols?
+
+Because `params[:gender].to_sym` is dangerous. It could be a source of problems like memory leak, slow symbol table lookup, or even DoS attack. If a user sends random strings for the parameter, it generates unlimited number of symbols, which can never be garbage collected, and eventually causes `symbol table overflow (RuntimeError)`, eating up gigabytes of memory.
+
+For the same reason, `ActiveSupport::HashWithIndifferentAccess` (which is used for `params`) keeps hash keys as string internally.
+
+https://github.com/rails/rails/blob/master/activesupport/lib/active_support/hash_with_indifferent_access.rb
+
+## Other solutions
+
+There are tons of similar gems out there. Then why did I bother creating another one myself rather than sending pull requests to one of them? Because each one of them has incompatible design policies than EnumAccessor.
+
+* [simple_enum](https://github.com/lwe/simple_enum)
+ * Pretty close to EnumAccessor feature-wise but requires `*_cd` suffix for the database column, which makes AR scopes ugly.
+* [enum_field](https://github.com/jamesgolick/enum_field)
+ * Enum values are defined as top-level predicate methods, which could conflict with existing methods. Also you can't define multiple enums to the same model. In some use cases, predicate methods are not necessary and you just want to be on the safe side.
+* [enumerated_attribute](https://github.com/jeffp/enumerated_attribute)
+ * Top-level predicate methods. Many additional methods are coupled with a specific usage assumption.
+* [coded_options](https://github.com/jasondew/coded_options)
+ * No support for symbols. Verbose definitions.
+* [active_enum](https://github.com/adzap/active_enum)
+ * Syntax seems verbose.
+* [classy_enum](https://github.com/beerlington/classy_enum)
+ * As the name suggests, class-based enum. I wanted something lighter.
+
+Also, EnumAccessor has one of the simplest code base, so that you can easily hack on.
6 Rakefile
@@ -0,0 +1,6 @@
+require 'bundler/gem_tasks'
+
+# RSpec
+require 'rspec/core/rake_task'
+RSpec::Core::RakeTask.new(:spec)
+task :default => :spec
25 enum_accessor.gemspec
@@ -0,0 +1,25 @@
+# -*- encoding: utf-8 -*-
+lib = File.expand_path('../lib', __FILE__)
+$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
+require 'enum_accessor/version'
+
+Gem::Specification.new do |gem|
+ gem.name = 'enum_accessor'
+ gem.version = EnumAccessor::VERSION
+ gem.authors = ['Kenn Ejima']
+ gem.email = ['kenn.ejima@gmail.com']
+ gem.description = %q{Enum field support for ActiveModel with validations and i18n}
+ gem.summary = %q{Enum field support for ActiveModel with validations and i18n}
+ gem.homepage = ''
+
+ gem.files = `git ls-files`.split($/)
+ gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
+ gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
+ gem.require_paths = ['lib']
+
+ gem.add_runtime_dependency 'activesupport', '>= 3.0.0'
+
+ gem.add_development_dependency 'activerecord', '>= 3.0.0'
+ gem.add_development_dependency 'rspec'
+ gem.add_development_dependency 'sqlite3'
+end
107 lib/enum_accessor.rb
@@ -0,0 +1,107 @@
+require 'enum_accessor/version'
+require 'enum_accessor/railtie'
+require 'active_support'
+
+module EnumAccessor
+ extend ActiveSupport::Concern
+
+ module ClassMethods
+ # enum_accessor encapsulates a validates_inclusion_of and automatically gives you a
+ # few more goodies automatically.
+ #
+ # class Computer < ActiveRecord:Base
+ # enum_accessor :status, [ :on, :off ], validation_options: { message: "incorrect status" }
+ #
+ # # Optionally with a message to replace the default one
+ # # enum_accessor :status, [ :on, :off ]
+ #
+ # #...
+ # end
+ #
+ # This will give you a few things:
+ #
+ # - add a validates_inclusion_of with a simple error message ("invalid #{field}") or your custom message
+ # - define the following query methods, in the name of expressive code:
+ # - status_on?
+ # - status_off?
+ # - define the STATUSES constant, which contains the acceptable values
+ def enum_accessor(field, enums, options={})
+ # Normalize arguments
+ field = field.to_s
+ case enums
+ when Array
+ enums = Hash[enums.map.with_index{|v,i| [v.to_s, i] }]
+ when Hash
+ enums = Hash[enums.map{|k,v| [k.to_s, v] }]
+ else
+ raise ArgumentError.new('enum_accessor takes Array or Hash as the second argument')
+ end
+
+ const_name = field.pluralize.upcase
+ const_set(const_name, enums) unless const_defined?(const_name)
+ const = const_get(const_name)
+
+ symbolized_enums = Hash[enums.map{|k,v| [k.to_sym, v] }]
+
+ # Getter
+ define_method(field) do
+ const.key(read_attribute(field)).try(:to_sym)
+ end
+
+ # Setter
+ define_method("#{field}=") do |arg|
+ write_attribute field, const[arg.to_s]
+ end
+
+ # Raw-value getter
+ define_method("#{field}_raw") do
+ read_attribute field
+ end
+
+ # Raw-value setter
+ define_method("#{field}_raw=") do |arg|
+ write_attribute field, Integer(arg)
+ end
+
+ # Checker
+ symbolized_enums.keys.each do |key|
+ method_name = key.to_s.downcase.gsub(/[-\s]/, '_')
+ define_method("#{field}_#{method_name}?") do
+ self.send(field) == key
+ end
+ end
+
+ class_eval(<<-EOS, __FILE__, __LINE__ + 1)
+ def self.#{field.pluralize}(*args)
+ return #{symbolized_enums} if args.first.nil?
+ return #{symbolized_enums}[args.first.to_sym] if args.size == 1
+ args.map{|arg| #{symbolized_enums}[arg.to_sym] }
+ end
+ EOS
+
+ # Human-friendly view
+ define_method("human_#{field}") do
+ self.class.human_enum_accessor(field, self.send(field))
+ end
+
+ # Validation
+ unless options[:validate] == false
+ validates_inclusion_of field, { :in => symbolized_enums.keys }.merge(options[:validation_options] || {})
+ end
+ end
+
+ # Mimics ActiveModel::Translation.human_attribute_name
+ def human_enum_accessor(field, value, options = {})
+ defaults = lookup_ancestors.map do |klass|
+ :"#{self.i18n_scope}.enum_accessor.#{klass.model_name.i18n_key}.#{field}.#{value}"
+ end
+ defaults << :"enum_accessor.#{self.model_name.i18n_key}.#{field}.#{value}"
+ defaults << :"enum_accessor.#{field}.#{value}"
+ defaults << options.delete(:default) if options[:default]
+ defaults << value.to_s.humanize
+
+ options.reverse_merge! :count => 1, :default => defaults
+ I18n.translate(defaults.shift, options)
+ end
+ end
+end
11 lib/enum_accessor/railtie.rb
@@ -0,0 +1,11 @@
+module EnumAccessor
+ if defined? Rails::Railtie
+ class Railtie < Rails::Railtie
+ initializer 'enum_accessor.insert_into_active_record' do |app|
+ ActiveSupport.on_load :active_record do
+ include EnumAccessor
+ end
+ end
+ end
+ end
+end
3  lib/enum_accessor/version.rb
@@ -0,0 +1,3 @@
+module EnumAccessor
+ VERSION = '0.1.0'
+end
64 spec/enum_accessor_spec.rb
@@ -0,0 +1,64 @@
+# encoding: UTF-8
+
+require 'spec_helper'
+
+ActiveRecord::Base.connection.create_table :users, force: true do |t|
+ t.column :gender, :integer, default: 0
+end
+
+class User < ActiveRecord::Base
+ enum_accessor :gender, [ :female, :male ]
+end
+
+describe EnumAccessor do
+ before do
+ @user = User.new
+ end
+
+ it 'adds checker' do
+ @user.gender_female?.should == true
+ @user.gender_male?.should == false
+ end
+
+ it 'adds getter' do
+ @user.gender.should == :female
+ end
+
+ it 'adds setter' do
+ @user.gender = :male
+ @user.gender_male?.should == true
+ end
+
+ it 'adds raw value getter' do
+ @user.gender_raw.should == 0
+ end
+
+ it 'adds raw value setter' do
+ @user.gender_raw = 1
+ @user.gender_male?.should == true
+ end
+
+ it 'adds humanized getter' do
+ I18n.locale = :ja
+ @user.human_gender.should == ''
+
+ I18n.locale = :en
+ @user.human_gender.should == 'Female'
+ end
+
+ it 'defines internal constant' do
+ User::GENDERS.should == { "female" => 0, "male" => 1 }
+ end
+
+ it 'adds class methods' do
+ User.genders.should == { :female => 0, :male => 1 }
+ end
+
+ it 'adds validation' do
+ @user.gender = 'bogus'
+ @user.valid?.should be_false
+
+ @user.gender = 'male'
+ @user.valid?.should be_true
+ end
+end
6 spec/locales.yml
@@ -0,0 +1,6 @@
+ja:
+ enum_accessor:
+ user:
+ gender:
+ female:
+ male:
15 spec/spec_helper.rb
@@ -0,0 +1,15 @@
+require 'rubygems'
+require 'bundler/setup'
+
+require 'enum_accessor'
+
+RSpec.configure do |config|
+ require 'active_record'
+ ActiveRecord::Base.send(:include, EnumAccessor)
+
+ # Establish in-memory database connection
+ ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
+
+ # Load translation
+ I18n.load_path << File.join(File.dirname(__FILE__), 'locales.yml')
+end
Please sign in to comment.
Something went wrong with that request. Please try again.