Git Product home page Git Product logo

enumerated_attribute's Introduction

enumerated_attribute

Easily code enumerations for your models and expose them as

drop-down lists with the enum_select helper, or use any of enumerated_attribute features to simplify coding enumerations in any Ruby object.

Resources

Development

Source

  • git://github.com/jeffp/enumerated_attribute.git

Install

  • sudo gem install enumerated_attribute

Notice

  • Rails 3 … dynamic finders working… should be rails3 ready. We are completing form tests.

  • Rails 2.3.8 breaks find_or_create_by_… and find_or_initialize_by_… methods. Write me if you gotta have it… otherwise happy Rails3.

  • Write cleaner code … implement state patterns for your enumerated attributes (enumerated_state)

How to submit an Issue

If something needs fixed, please submit issues to this Github project in the Issues tab and provide a series of FAILING RSPEC tests that I can drop into the current RSpec test framework and run with little to no coersing. Thanks.

Contributors

  • Lailson Bandeira - Rails 3 updates

Description

Typically, in Ruby, enumerated attributes are implemented with strings, symbols or constants. Often the developer is burdened with repeatedly defining common methods in support of each attribute. enumerated_attribute provides a DRY implementation for enumerations in Rails.

Repetitive code such as initializers, accessors, predicate and enumeration methods are automatically generated along with the following features:

  • ActiveRecord integration

  • ActionView form helpers

  • Scaffold generator integration

  • Definable enumeration labels

  • Enum helper methods

  • Dynamic predicate methods

  • Initialization

  • State pattern support (enumerated_state)

Setup

For a Ruby application, install the gem and require it

require 'enumerated_attribute'

or for a rails application configure the gem in the config block of the config/environment.rb file

config.gem "enumerated_attribute"

and run the gem install rake task

rake gems:install

Rails Example

Here’s an example of enumerated_attribute features in a Rails application:

In the migration, declare your enumeration attributes with enum

create_table :users, :force=>true do |t|
  t.string :first_name
  t.enum :gender
  t.enum :degree
  ...
end

Define the enumerations in your models with enum_attr

class User < ActiveRecord::Base
  enum_attr :gender, %w(male female)
  enum_attr :degree, %w(^none high_school college graduate)
end

Expose the enumeration in your forms with enum_select

<% form_for :user do |f| %>
  <%= f.label :user %> <%= f.text_field :first_name %><br/>
  <%= f.label :gender %> <%= f.enum_select :gender %><br/>
  <%= f.label :degree %> <%= f.enum_select :degree %><br/>
  <%= submit_tag 'save' %>
<% end %>

or generate a scaffold with one of your favorite scaffold generators. Currently supports most scaffold generators including scaffold, wizardly_scaffold, nifty_scaffold, rspec_scaffold, and haml_scaffold. See the section ‘Generating Scaffolds’ below.

The select options text can be customized. See ‘Customizing Labels’ in the Integration section.

Ruby Example

Here’s an example of enumerated_attribute features in a Ruby application:

require 'enumerated_attribute'

class Tractor
  enum_attr :gear, %w(reverse ^neutral first second over_drive)

end

t = Tractor.new
t.gear                            # => :neutral
t.neutral?                        # => true
t.gear_next                       # => :first
t.not_neutral?                    # => true
t.gear_previous                   # => :neutral
t.gear = :second                  # => :second
t.gear_is_not_in_first?           # => true

An explanation of the above features and their usage follows.

Usage

Defining the Attribute

Defining an enumerated attribute is as simple as this:

require 'enumerated_attribute'

class Tractor
  enumerated_attribute :gear, %w(reverse neutral first second over_drive)

  def initialize
    @gear = :neutral
  end
end

Notice the plugin enumerated_attribute is required at the top of the code.

The require line must be added at least once at some point in the code.

It is not included in subsequent examples.

The above code uses enumerated_attribute to define an attribute named ‘gear’ with five enumeration values.

In general, enumerated_attribute takes three parameters: the name of the attribute, an array of enumeration values (either symbols or strings), and an optional hash of options (not shown above). The complete form of enumerated_attribute looks like this:

enumerated_attribute :name, array_of_enumerations, hash_of_options

Defining the attribute :gear has done a number things.

It has generated an instance variable ‘@gear’, read/write accessors for the attribute and support methods for the enumeration, such as incrementor and decrementor methods. These methods are demonstrated below using the Tractor class above:

Tractor.instance_methods(false)
# =>["gear", "gear=", "gears", "gear_next", "gear_previous", ...

t = Tractor.new
t.gear                            # => :neutral
t.gear = :reverse                 # => :reverse
t.gear                            # => :reverse
t.gear = :third
# => ArgumentError: 'third' is not an enumerated value for gear attribute

t.gears                           # => [:reverse, :neutral, :first, :second, :over_drive]
t.gear_next                       # => :neutral
t.gear_previous                   # => :reverse
t.gear_previous                   # => :over_drive

The plugin has defined gear and gear= accessors for the attribute. They can be used to set the attribute to one of the defined enumeration values. Attempting to set the attribute to something besides a defined enumeration value raises an ArgumentError.

gear_next and gear_previous are incrementors and decrementors of the attribute.

The increment order is based on the order of the enumeration values in the attribute definition. Both the incrementor and decrementor will wrap when reaching the boundary elements of the enumeration array. For example:

t.gear = :second
t.gear_next                       # => :over_drive
t.gear_next                       # => :reverse

Dynamically-Generating Predicates Methods

Predicate methods are methods that query the state of the attribute, for instance, gear_is_neutral? is a predicate method that returns ‘true’ if the gear attribute is in the :neutral state.

By default, predicate methods are not predefined, instead, they are dynamically generated.

The plugin will evaluate and respond to methods adhering to a format that it can associate with an attribute name and one of the attribute’s enumeration values.

enumerated_attribute recognizes predicate methods of the following format:

{attribute name}_{anything}_{enumeration value}?

The predicate method must satisfy three requirements: it must begin with the name of the attribute, it must end with a question mark, and the question mark must be preceded with a valid enumeration value (all connected by underscores without colons).

So we can write the following two predicate methods without any prior definition and the plugin will recognize, define and respond to them as demonstrated here:

t.gear= :neutral
t.gear_is_in_neutral?             # => true
t.gear_is_in_reverse?             # => false

The ‘is_in’ part of the methods above is merely semantic but enhances readability. The contents of the {anything} portion is completely at the discretion of the developer. However, there is one twist.

The evaluation of a predicate method can be negated by including ‘not’ in the the middle {anything} section, such as here:

t.gear_is_not_in_neutral?         # => false
t.gear_is_not_in_reverse?         # => true

Basically, the shortest acceptable form of a predicate method is:

t.gear_neutral?                   # => true
t.gear_not_neutral?               # => false

Abbreviating Predicate Methods

In the case that an enumeration value is associated with only one attribute, the attribute name can be left out of the predicate method name. The plugin will infer the attribute from the enum value in the method name. The abbreviate format can be written like this:

{anything}{_}{enumeration value}?

And results in the following possibilities:

t.gear = :neutral
t.neutral?                        # => true
t.is_neutral?                     # => true
t.not_neutral?                    # => false
t.is_not_neutral?                 # => false

Calling the abbreviated form of the method containing an enumeration value belonging to two or more attributes throws an AmbiguousMethod error.

Initializing Attributes

The plugin provides a few ways to eliminate setting the initial value of the attribute in the initialize method. Two ways are demonstrated here:

class Tractor
  enum_attr :gear, %w(reverse ^neutral first second third)
  enum_attr :front_light, %w(off low high), :init=>:off
end

t = Tractor.new
t.gear                            # => :neutral
t.front_light                     # => :off

Note enumerated_attribute can be abbreviated to enum_attr. The abbreviated form will be used in subsequent examples.

The first and simplest way involves designating the initial value by prepending a carot ‘^’ to one of the enumeration values in the definition.

The plugin recognizes that the gear attribute is to be initialized to :neutral.

Alternatively, the :init option can be used to indicate the initial value of the attribute.

Setting Attributes to nil

By default, the attribute setter allows nils unless the :nil option is set to false. When :nil is set to false, the attribute may initialize to nil, but may not be set to nil thereafter.

class Tractor 
  enum_attr :plow, %w(up down), :nil=>false
end

t = Tractor.new
t.plow                            # => nil
t.plow_nil?                       # => true
t.plow = :up                      # => :up
t.plow_is_nil?                    # => false
t.plow_is_not_nil?                # => true
t.plow = nil                      # => raises error

Regardless of the :nil option setting, the plugin can dynamically recognize and define predicate methods for testing ‘nil’ values. The setter methods also treat empty strings (or ”) as nil values.

Changing Method Names

The plugin provides options for changing the method names of the enumeration accessor, incrementor and decrementor (ie, gears, gear_next, gear_previous):

class Tractor
  enum_attr :lights, %w(^off low high), :plural=>:lights_values, 
      :inc=>'lights_inc', :dec=>'lights_dec'
end

t = Tractor.new
t.lights_values                   # => [:off, :low, :high]
t.lights_inc                      # => :low
t.lights_dec                      # => :off

By default, the plugin uses the plural of the attribute for the accessor method name of the enumeration values. The pluralization uses a simple algorithm which does not support irregular forms. In the case of ‘lights’ as an attribute, the default pluralization does not work, so the accessor can be changed using the :plural option. Likewise, the decrementor and incrementor have options :decrementor and :incrementor, or :inc and :dec, for changing their method names.

Defining Other Methods

In the case that other methods are required to support the attribute, the plugin provides a short-hand for defining these methods in the enumerated_attribute block.

class Tractor
  enum_attr :gear, %w(reverse ^neutral first second over_drive) do
    parked? :neutral
    driving? [:first, :second, :over_drive]
  end
end

t = Tractor.new
t.parked?                         # => true
t.driving?                        # => false

Two predicate methods are defined for the ‘gear’ attribute in the above example using the plugin’s short-hand.

The first method, parked?, defines a method which evaluates the code {@gear == :neutral}. The second method, driving?, evaluates to true if the attribute is set to one of the enumeration values defined in the array [:first, :second, :over_drive].

The same short-hand can be used to define methods where the attribute ‘is not’ equal to the indicated value or ‘is not’ included in the array of values.

class Tractor
  enum_attr :gear, %w(reverse ^neutral first second over_drive) do
    not_parked? is_not :neutral
    not_driving? is_not [:first, :second, :over_drive]
  end
end

Defining Other Methods With Blocks

For predicate methods requiring fancier logic, a block can be used to define the method body.

class Tractor
  enum_attr :gear, %w(reverse ^neutral first second over_drive) do
    parked? :neutral
    driving? [:first, :second, :over_drive]
  end
  enum_attr :plow, %w(^up down), :plural=>:plow_values do
    plowing? { self.gear_is_in_first? && @plow == :down }
  end
end

Here, a method plowing? is true if the gear attribute equates to :first and the plow attribute is set to :down. There is no short-hand for the block. The code must be complete and evaluate in the context of the instance.

Method definitions are not limited to predicate methods. Other methods can be defined to manipulate the attributes. Here, two methods are defined acting as bounded incrementor and decrementor of the gear attribute.

class Tractor
  enum_attr :gear, %w(reverse ^neutral first second over_drive) do
    parked? :neutral
    driving? [:first, :second, :over_drive]
    upshift { self.gear_is_in_over_drive? ? self.gear : self.gear_next }
    downshift { self.driving? ? self.gear_previous : self.gear }      
  end
end

t = Tractor.new
t.gear                            # => :neutral
10.times { t.upshift }
t.gear                            # => :over_drive
10.times { t.downshift }
t.gear                            # => :neutral

Methods upshift and downshift use the automatically generated incrementor and decrementor as well as a couple predicate methods. upshift increments the gear attribute until it reaches over_drive and does not allow a wrap around. downshift decrements until the attribute reaches neutral.

Integration

ActiveRecord integration

The plugin can be used with ActiveRecord. Enumerated attributes may be declared on column attributes or as independent enumerations. Declaring an enumerated attribute on a column attribute will enforce the enumeration using symbols. The enumerated column attribute must be declared as a STRING in the database schema.

The enumerated attribute will be stored as a string but retrieved in code as a symbol. The enumeration functionality is consistent across integrations.

require 'enumerated_attribute'
require 'active_record'

class Order < ActiveRecord::Base	
  enum_attr :status, %w(^hold, processing, delayed, shipped)
  enum_attr :billing_status, 
    %w(^unauthorized, authorized, auth_failed, captured, capture_failed, closed)
end

o = Order.new
o.status                          # => :hold
o.billing_status                  # => :unauthorized
o.save!

o = Order.new(:invoice=>'43556334-W84', :status=>:processing, :billing=>:authorized)
o.save!
o.status                          # => :processing
o.invoice                         # => "43556334-W84"

Labels

Each enumeration value has a corresponding text label. The defaults are made up from the enumeration symbols. For the Tractor class example:

t=Tractor.new
t.enums(:gear)                    # => [:reverse, :neutral, :first, :second, :over_drive]
t.enums(:gear).labels             # => ['Reverse', 'Neutral', 'First', 'Second', 'Over drive']

The +enums(:attribute)+ method provides information about the attribute’s enumerations. It is the same as the plural form of the attribute name. There are several kinds of information available from the enums method.

t=Tractor.new
e = t.enums(:plow)                # => [:up, :down]
e.labels                          # => ['Up', 'Down']
e.hash                            # => {:up=>'Up', :down=>'Down'}
e.select_options                  # => [['Up', 'up'], ['Down', 'down']]
e.label(:up)                      # => 'Up'

Customizing Labels

Labels can be customized as shown here:

class User < ActiveRecord::Base
  enum_attr :contact_options, %w(none phone email mail) do
    label :none=>'Please do not contact me'
    label :phone=>'I would like a representative to call me'
    label :email=>'I would like information via email'
    label :mail=>'I would like information mailed to me'
  end
end

Likewise, the labels can be provided on the same line

class Tractor
  enum_attr :gear, %w(reverse ^neutral first second over_drive) do
    labels :first=>'1st Gear', :second=>'2nd Gear', :over_drive=>'Over Drive'
  end
end

View Helpers

There are two enum_select helpers, one for use with form_for and one for use without it. An example for form_for was given in the examples at the beginning. Here’s an example with the form_tag and a @user object.

<% form_tag :action=>:register do %>
  <%= label_tag 'First name' %>: <%= text_field :user, :first_name %><br/>
  <%= label_tag 'Gender' %>: <%= enum_select :user, :gender %><br/>
  <%= label_tag 'Degree' %>: <%= enum_select :user, :degree %><br/>
  ...
  <%= submit_tag 'Register' %>
<% end %>

Generating Scaffolds

You can generate views with enumerations using your favorite scaffold generator. Currently supports most scaffold generators including scaffold, wizardly_scaffold, nifty_scaffold, rspec_scaffold and haml_scaffold. For most scaffolds there are two steps. First, generate the scaffold views and migrations using the ‘enum’ type for enumerations

./script/generate scaffold contractor name:string gender:enum age:integer status:enum

Second, do not forget to add the enum_attr macro to the generated model and migrate the database

class Contractor < ActiveRecord::Base
  enum_attr :gender, %w(male female)
  enum_attr :status, %w(available unavailable)
end

Formtastic integration

You can display the select input in a Formtastic form with a little monkey patching. First, extend Formtastic with an initializer:

require 'formtastic'

module Formtastic #:nodoc:
  module Inputs #:nodoc:
    class EnumInput < SelectInput #:nodoc:
      def to_html
        unless options[:collection]
          enum = @object.enums(method.to_sym)
          choices = enum ? enum.select_options : []
          options[:collection] = choices
        end
        if (value = @object.__send__(method.to_sym))
          options[:selected] ||= value.to_s
        else
          options[:include_blank] ||= true
        end
        super
      end
    end
  end
end

Then specify the input type as enum in the forms:

form.input :gear, :as => :enum

Implementation Notes

New and Method_missing methods

The plugin chains both the ‘new’ and the ‘method_missing’ methods. Any ‘new’ and ‘method_missing’ implementations in the same class declaring an enumerated_attribute should come before the declaration; otherwise, the ‘new’ and ‘method_missing’ implementations must chain in order to avoid overwriting the plugin’s methods. The best approach is shown here:

class Soup
  def self.new(*args)
    ...
  end

  private
  def method_missing(methId, *args, &blk)
    ...
  end

  enum_attr temp:, %w(cold warm hot boiling)
end

ActiveRecord

ActiveRecord’s write_attribute and read_attribute methods do not support symbols for enumerated attributes.

Testing

The plugin uses jeweler, RSpec, and Webrat for testing. Make sure you have these gems installed:

gem install rspec webrat jeweler

To test the plugin for regular ruby objects, run:

rake spec:object

Testing ActiveRecord integration requires the install of Sqlite3 and the sqlite3-ruby gem. To test ActiveRecord, run:

rake spec:ar

And for testing enum_select in form views:

rake spec:forms

To test all specs:

rake spec:all

Dependencies

  • ActiveRecord (but not required)

  • Sqlite3 and sqlite3-ruby gem (for testing)

enumerated_attribute's People

Contributors

adivinaelnombre avatar be9 avatar fringd avatar jeffp avatar jip149 avatar petyosi avatar rymohr avatar trollixx avatar turadg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

enumerated_attribute's Issues

Unnecessary uppercase in view

Sorry for bad English.
There are unnecessary uppercase in view, may be more better if user could told wich string function he want to use?
According to naming convention i want to use utf8, cp1251 etc. in view, but not Utf8, Cp1251.

By the way thank you for good work!

1.8 compatability with Rails 3

After upgrading to Rails 3 I get the following error

 
undefined method `size' for :CPA:Symbol

Symbol#size is defined in 1.9, but not in 1.8

I am going to work around this by adding the 1.9 method

class Symbol
  def size; to_s.size end
end

#to_xml only works when record loaded from database

Calling #to_xml on a record with enumerated_attribute results in an error when the record is created and still in memory. The error disappears when the record is loaded from the database.

class Post
  enumerated_attribute :kind, %w(post page)
end

This fails:

post = Post.create! name: 'First post'
post.to_xml

This works:

Post.create! name: 'Second post'
post = Post.find_by_name 'Second post'
post.to_xml

pls ad to readme: if using postgres (Heroku), use :string not :enum in migrations

I found a note to this in an old issue, but it really ought to be in the readme because ...

by the time you push to heroku,
hit the error,
FIND the error,
then fix the error several commits back in your repo's to fix the migration (have to go back in history to fix it, can't add another migration later to fix it because the migration with :enum stops further migrations) is a real pain.

For that matter, is there any reason to recommend using :enum instead of :string in migrations in the first place?

Formtastic support doesn't work with empty string

I'm trying to use your Formtastic integration as per the readme but I'm getting an error when I edit a user record with a blank field for the current_status.

ArgumentError in Users#edit
interning empty string

= f.input :current_status, :as => :enum

Rolling back a migration fails

I'm getting

undefined method `to_sym' for nil:NilClass
/Users/a5sk4s/.rvm/gems/ruby-1.9.2-p0@rails300_final/gems/activesupport-3.0.0/lib/active_support/whiny_nil.rb:48:in `method_missing'
/Users/a5sk4s/.rvm/gems/ruby-1.9.2-p0@rails300_final/gems/activerecord-3.0.0/lib/active_record/connection_adapters/abstract/schema_definitions.rb:487:in `column'
/Users/a5sk4s/.rvm/gems/ruby-1.9.2-p0@rails300_final/gems/enumerated_attribute-0.2.16/lib/enumerated_attribute/rails_helpers.rb:9:in `column_with_enumerated_attribute'

on the following migration

class AddStatus < ActiveRecord::Migration
  def self.up
    add_column :memberships, :status, :enum, :default => :pending
  end
  def self.down
    remove_column :memberships, :status
  end
end

What am I missing?

Rails 3 scaffold generator bork

Hi,

Using this plugin (as a gem) causes Rails 3 scaffold generator to bork. Seems like something in the rails_helper.rb is not going down well...

Thanks.

save model with enums not working in Rails 3

I installed your gem in my project. In migration I have:
def self.up
create_table :ads do |t|
t.integer :price
t.string :aasm_column
t.integer :visualized
t.enum :property_type
t.enum :ad_type
..........

The model:
class Ad < ActiveRecord::Base
enum_attr :property_type, %w(apartment house land) #, :nil => false
enum_attr :ad_type, %w(sell rent) #, :nil => false
...........

I create a new Ad in console:

ruby-1.9.2-head > ad = Ad.new
=> #<Ad id: nil, price: nil, aasm_column: nil, visualized: nil, property_type: "apartment", ad_type: "sell", description: nil, attributes: nil, aditional_attributes: nil, has_attached_image: nil, zone_id: nil, user_id: nil, created_at: nil, updated_at: nil>
.................

When I try to save the entity I receive this error:

ruby-1.9.2-head > ad.save
ActiveRecord::DangerousAttributeError: attributes_before_type_cast is defined by ActiveRecord
from /Users/silviu/.rvm/gems/ruby-1.9.2-head/gems/activerecord-3.0.3/lib/active_record/attribute_methods.rb:23:in instance_method_already_implemented?' from /Users/silviu/.rvm/gems/ruby-1.9.2-head/gems/activemodel-3.0.3/lib/active_model/attribute_methods.rb:263:inblock (2 levels) in define_attribute_methods'
from /Users/silviu/.rvm/gems/ruby-1.9.2-head/gems/activemodel-3.0.3/lib/active_model/attribute_methods.rb:262:in each' from /Users/silviu/.rvm/gems/ruby-1.9.2-head/gems/activemodel-3.0.3/lib/active_model/attribute_methods.rb:262:inblock in define_attribute_methods'
from /Users/silviu/.rvm/gems/ruby-1.9.2-head/gems/activemodel-3.0.3/lib/active_model/attribute_methods.rb:261:in each' from /Users/silviu/.rvm/gems/ruby-1.9.2-head/gems/activemodel-3.0.3/lib/active_model/attribute_methods.rb:261:indefine_attribute_methods'
from /Users/silviu/.rvm/gems/ruby-1.9.2-head/gems/activerecord-3.0.3/lib/active_record/attribute_methods.rb:13:in define_attribute_methods' from /Users/silviu/.rvm/gems/ruby-1.9.2-head/gems/activerecord-3.0.3/lib/active_record/attribute_methods.rb:41:inmethod_missing'
from /Users/silviu/.rvm/gems/ruby-1.9.2-head/gems/enumerated_attribute-0.2.16/lib/enumerated_attribute/attribute/instance_methods.rb:9:in block in included' from /Users/silviu/.rvm/gems/ruby-1.9.2-head/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract/database_statements.rb:296:inflatten'
from /Users/silviu/.rvm/gems/ruby-1.9.2-head/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract/database_statements.rb:296:in rollback_transaction_records' from /Users/silviu/.rvm/gems/ruby-1.9.2-head/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract/database_statements.rb:147:inrescue in transaction'
from /Users/silviu/.rvm/gems/ruby-1.9.2-head/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract/database_statements.rb:127:in transaction' from /Users/silviu/.rvm/gems/ruby-1.9.2-head/gems/activerecord-3.0.3/lib/active_record/transactions.rb:204:intransaction'
from /Users/silviu/.rvm/gems/ruby-1.9.2-head/gems/activerecord-3.0.3/lib/active_record/transactions.rb:287:in with_transaction_returning_status' from /Users/silviu/.rvm/gems/ruby-1.9.2-head/gems/activerecord-3.0.3/lib/active_record/transactions.rb:237:inblock in save'
from /Users/silviu/.rvm/gems/ruby-1.9.2-head/gems/activerecord-3.0.3/lib/active_record/transactions.rb:248:in rollback_active_record_state!' from /Users/silviu/.rvm/gems/ruby-1.9.2-head/gems/activerecord-3.0.3/lib/active_record/transactions.rb:236:insave'
from (irb):2
from /Users/silviu/.rvm/gems/ruby-1.9.2-head/gems/railties-3.0.3/lib/rails/commands/console.rb:44:in start' from /Users/silviu/.rvm/gems/ruby-1.9.2-head/gems/railties-3.0.3/lib/rails/commands/console.rb:8:instart'
from /Users/silviu/.rvm/gems/ruby-1.9.2-head/gems/railties-3.0.3/lib/rails/commands.rb:23:in <top (required)>' from script/rails:6:inrequire'
............

Do you know how can I solve this issue because I'm stuck with this from some time?

UPDATE: The error was from my mistake. I had a field in view "attributes" and there is a method with this name

Bug: Dynamically created methods return wrong result

There seem to be a problem with the dynamically created methods, when the selected value is a part of one of the other values of the attribute.

A good example is when adding eg. a "sex" enumerated attribute with "female" and "male" values:

class Tractor
   enum_attr :driver_sex, %w(male female)
end

These specs both fail:

it "should not fail like this:" do
    t = Tractor.new
    t.driver_sex = :male
    t.driver_sex_female?.should be_false
end

=> Failure/Error: t.driver_sex_female?.should be_false
       expected true to be false
it "should not fail like this:" do
    t = Tractor.new
    t.driver_sex = :female
    t.driver_sex_female?.should be_true
end

=> Failure/Error: t.driver_sex_female?.should be_true
       expected false to be true

schema.rb is borked when enum is used

did add_column :interests, :status, :enum

migration ran, but got this in schema.rb where my table should have apeared:

# Could not dump table "interests" because of following StandardError
#   Unknown type 'enum' for column 'status'

update_attributes doesn't work

I use a role enum with admin and ^customer. The enum_select transfers the selected value correctly, but it is not updated with udpate_attributes. attr_accessible :role is set, too.

I am running on Mac, Ruby 1.9.2, Rails 3.0.3, enumerated_attribute (0.2.16)

Dynamically-Generating Predicates Methods bug

I think there is a bug with theses predicated methods. Kind of confusion.

In my model:

  enum_attr :gender, %w(^none male female) do
    label :none => ''
    label :male => '男性'
    label :female => '女性'
  end

I set my model gender to :male.
Look at the result in the console:

1.9.3-p0 :018 > s.gender
 => :male 
1.9.3-p0 :019 > s.gender_male?
 => true 
1.9.3-p0 :020 > s.gender_female?
 => true 
1.9.3-p0 :021 > s.gender_none?
 => false 

Why does it return "true" for female ?
Is it because in "female" there is the word "male" so it is confused ?

I'm using:
Using enumerated_attribute (0.3.0.beta1) from https://github.com/jeffp/enumerated_attribute.git (at master)

creating instance with association doesn't work against AR3.2.1

Against AR 3.2.1, creating AR instance with association like Employee.create!(... :company => c) doesn't work and raise ActiveModel::MissingAttributeError (same on #new and #create).

I added that as an example on kakutani/enumerated_attribute@d885ac0.
That will success against AR 3.1.3 and fail against AR 3.2.1 (ran against cb915e2).
(I think related commit is rails/rails@50d395f.)

I've just fixed this issue on kakutani/enumerated_attribute@942087b,
but I'm not sure this way is correct or not.

Any idea how I can fix this issue?
Thanks in advance.

class constant please?

I find myself doing the following every time i declare an attribute

GEARS = enumerated_attributes[:gear].freeze

some of the competing enumerated libraries just do this, and i think they've got it right (although lack in places where this gem shines). Please consider this humble feature request.

Assigning non-enum attributes under inheritance throws error Rails 2.3.5

Model app/models/parent.rb

require 'enumerated_attribute'
class Parent < ActiveRecord::Base
enum_attr :parent_enum, %w(pvaluea pvalueb)
end

Model app/models/sub.rb

require 'enumerated_attribute'
class Sub < Parent
enum_attr :sub_enum, %w(svalue1 svalue2)
end

Migration db/migrate/20100518233259_create_parents.rb

class CreateParents < ActiveRecord::Migration
def self.up
create_table :parents do |t|
t.string :type
t.string :parent_enum
t.timestamps
end
end
def self.down
drop_table :parents
end
end

Migration db/migrate/20100518233302_add_sub_to_parents.rb

class AddSubToParents < ActiveRecord::Migration
def self.up
add_column :parents, :sub_nonenum, :string
add_column :parents, :sub_enum, :string
end
def self.down
remove_column :parents, :sub_enum
remove_column :parents, :sub_nonenum
end
end

Unit test sub_test.rb

require File.dirname(FILE) + '/../test_helper'
class SubTest < ActiveSupport::TestCase
test "enums for parent_enum" do
s = Sub.new()
s.parent_enum = :pvaluea
assert s.parent_enum == :pvaluea
begin
s.parent_enum = :bleech
rescue
end
assert s.parent_enum == :pvaluea
s.sub_nonenum = "any assignment causes error"
end
test "enums for sub_enum" do
s = Sub.new()
s.sub_enum = :svalue2
assert s.sub_enum == :svalue2
begin
s.sub_enum = :bleech
rescue
end
assert s.sub_enum == :svalue2
s.sub_nonenum = "any assignment causes error"
end
end

Unit test output

/usr/bin/ruby -I"lib:test" "/usr/lib64/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/rake_test_loader.rb" "test/unit/helpers/subs_helper_test.rb" "test/unit/sub_test.rb" "test/unit/parent_test.rb"
(in /home/xyz/abc/simple)
Loaded suite /usr/lib64/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/rake_test_loader
Started
.EE.
Finished in 0.21079 seconds.

  1. Error:
    test_enums_for_parent_enum(SubTest):
    SystemStackError: stack level too deep
    (eval):78:in define_enumerated_attribute_dynamic_method' (eval):5:inmethod_missing_without_enumerated_attribute'
    (eval):6:in method_missing_without_enumerated_attribute' (eval):6:inmethod_missing'
    /test/unit/sub_test.rb:15:in `test_enums_for_parent_enum'

  2. Error:
    test_enums_for_sub_enum(SubTest):
    SystemStackError: stack level too deep
    (eval):5:in method_missing_without_enumerated_attribute' (eval):6:inmethod_missing_without_enumerated_attribute'
    (eval):6:in method_missing' /test/unit/sub_test.rb:29:intest_enums_for_sub_enum'

4 tests, 6 assertions, 0 failures, 2 errors
rake aborted!
Command failed with status (1): [/usr/bin/ruby -I"lib:test" "/usr/lib64/rub...]

(See full trace by running task with --trace)

rails (3.1.3) scaffolding is completely broken by enumerated_attribute

if enumerated_attribute is in Gemfile, 'rails g scaffold Anything' breaks, with:

/Users/johndoe/.rvm/gems/ruby-1.9.2-p290/gems/enumerated_attribute-0.2.16/lib/enumerated_attribute/rails_helpers.rb:26:in `require': no such file to load -- rails_generator (LoadError)

100% repeatable.

Just to test, tried in brand new project:

rails new trythis
cd trythis
rails g scaffold ModelOne         (works fine)
           (add enumerated+attribute to Gemfile, run bundle install)
rails g scaffold ModelTwo         (throws error message above)
           (comment out enumerated_attribute in Gemfile, run bundle install)
rails g scaffold ModelThree      (works fine)

SQL error when migrating in production

I am using rails 3.0.3 with MySQL Ver 14.14 Distrib 5.1.41

At migration i have the following error :
Mysql::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1: ALTER TABLE carts ADD status enum

How can i solve it?

Postgres doesn't seem to correctly save values

After re-doing migrations to use :string instead of :enum, migrations now succeed for postgres (I used Heroku) per another issue reported... but a postgres issue remains.

On that platform when you submit a form containing f.enum_select after choosing a non-default value, it does not get saved to the database. The default value is the one that gets saved.

In my class I have:

    enum_attr :state_owner_submit, %w(^submit_none submit_standard submit_premium)

In my form I have:

    = f.label :state_owner_submit, :class => :label
    = f.enum_select :state_owner_submit

No matter which enumerated attribute I select in the selection box, "submit_none" is what gets saved.

It works fine under sqlite.

enum_attr messes up custom setters on .new and .create

# user.rb
# t.enum :rank
# t.string :name
class User < ActiveRecord::Base
    enum_attr :rank, %w{user administrator}

    def name=(_name)
        self[:name] = "#{_name.upcase} + THE GREAT"
    end
end

Then

User.new(:name => "bob").name =>
"bob"

User.create(:name => "bob").name =>
"bob"

When the return should be "BOB THE GREAT"

When enum_attr is commented out, it works correctly.

Using current version of enumerated_attribute (0.2.16) and Rails 3.1

generator with rails 3.2.8 dont work

piece of gemfile

gem 'rails', '3.2.8'

# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'

gem 'sqlite3'

group :test, :development do
  gem "rspec-rails", "~> 2.0"
end

gem 'devise'
gem 'rails-breadcrumbs'
gem 'enumerated_attribute'

and when i am trying generate with generator any scaffold i get an error

rails g scaffold Question section_id:integer question:string
/home/razor/.gem/ruby/1.9.1/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:251:in `require': cannot load such file -- rails_generator (LoadError)
        from /home/razor/.gem/ruby/1.9.1/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:251:in `block in require'
        from /home/razor/.gem/ruby/1.9.1/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:236:in `load_dependency'
        from /home/razor/.gem/ruby/1.9.1/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:251:in `require'
        from /home/razor/.gem/ruby/1.9.1/gems/enumerated_attribute-0.2.16/lib/enumerated_attribute/rails_helpers.rb:26:in `<top (required)>'
        from /home/razor/.gem/ruby/1.9.1/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:251:in `require'
        from /home/razor/.gem/ruby/1.9.1/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:251:in `block in require'
        from /home/razor/.gem/ruby/1.9.1/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:236:in `load_dependency'
        from /home/razor/.gem/ruby/1.9.1/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:251:in `require'
        from /home/razor/.gem/ruby/1.9.1/gems/enumerated_attribute-0.2.16/lib/enumerated_attribute/attribute.rb:7:in `<top (required)>'
        from /home/razor/.gem/ruby/1.9.1/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:251:in `require'
        from /home/razor/.gem/ruby/1.9.1/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:251:in `block in require'
        from /home/razor/.gem/ruby/1.9.1/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:236:in `load_dependency'
        from /home/razor/.gem/ruby/1.9.1/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:251:in `require'
        from /home/razor/.gem/ruby/1.9.1/gems/enumerated_attribute-0.2.16/lib/enumerated_attribute.rb:3:in `<top (required)>'
        from /home/razor/.gem/ruby/1.9.1/gems/bundler-1.2.1/lib/bundler/runtime.rb:68:in `require'
        from /home/razor/.gem/ruby/1.9.1/gems/bundler-1.2.1/lib/bundler/runtime.rb:68:in `block (2 levels) in require'
        from /home/razor/.gem/ruby/1.9.1/gems/bundler-1.2.1/lib/bundler/runtime.rb:66:in `each'
        from /home/razor/.gem/ruby/1.9.1/gems/bundler-1.2.1/lib/bundler/runtime.rb:66:in `block in require'
        from /home/razor/.gem/ruby/1.9.1/gems/bundler-1.2.1/lib/bundler/runtime.rb:55:in `each'
        from /home/razor/.gem/ruby/1.9.1/gems/bundler-1.2.1/lib/bundler/runtime.rb:55:in `require'
        from /home/razor/.gem/ruby/1.9.1/gems/bundler-1.2.1/lib/bundler.rb:128:in `require'
        from /home/razor/work/ruvote/config/application.rb:13:in `<top (required)>'
        from /home/razor/.gem/ruby/1.9.1/gems/railties-3.2.8/lib/rails/commands.rb:24:in `require'
        from /home/razor/.gem/ruby/1.9.1/gems/railties-3.2.8/lib/rails/commands.rb:24:in `<top (required)>'
        from script/rails:6:in `require'
        from script/rails:6:in `<main>'

allows_nil? and allows_value? do not appear to be usable

This may well be my fault: these methods are in the code but not mentioned in the README.rdoc.

I'm trying to write an rspec test that will check an enum is not allowing nil. Using this definition
enum_attr :country, %w{ England Scotland
Wales Northern\ Ireland Channel\ Islands Isle\ of\ Man },
:init => :England, :nil => false
and my reading of attribute_descriptor.rb suggests the test should be something like
county.country.allows_nil?.should be_false
but I get
NoMethodError in 'County should have a country'
undefined method `allows_nil?' for :England:Symbol

I'm not sure whether these methods are supposed to be usable in this sort of case, though.

I guess this ticket is either "allows_nil? and allows_value? aren't available for use in tests" or "documentation does not show how to use allows_nil? and allows_value?" :)

undefined method 'enum' when migrating

I've just installed enumerated_attribute (using rails 3.2.1) by the standard method of adding it to the Gemfile and running bundle. I have the following migration

class AddReadableByToArticle < ActiveRecord::Migration
  def change
    change_table :articles do |t|
      t.enum :readable_by
    end
  end
end

and the following as models/article.rb:

class Article < ActiveRecord::Base
  enum_attr :readable_by, %w(^draft branch members public)

According to the README, this should work, no?

But I get undefined methodenum' for #ActiveRecord::ConnectionAdapters::Table:0x007fbc533e87f0` when I try to migrate.

Are the docs out of date? I notice that the README still refers to using rake gems:install to install the gem, so I'm wondering if the docs no longer reflect reality.

Does not work with rails 3 beta 3

Typing rails c produces this with rails 3 beta 3 and either Ruby 1.8.7 or 1.9.1:

/Library/Ruby/Gems/1.8/gems/activesupport-3.0.0.beta3/lib/active_support/core_ext/module/aliasing.rb:31:in `alias_method': undefined method `column' for class `ActiveRecord::ConnectionAdapters::TableDefinition' (NameError)
    from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.0.beta3/lib/active_support/core_ext/module/aliasing.rb:31:in `alias_method_chain'
    from /Users/tinyclanger/.bundle/ruby/1.8/gems/enumerated_attribute-0.2.3/lib/enumerated_attribute/rails_helpers.rb:10
    from /Users/tinyclanger/.bundle/ruby/1.8/gems/enumerated_attribute-0.2.3/lib/enumerated_attribute/attribute.rb:4:in `require'
    from /Users/tinyclanger/.bundle/ruby/1.8/gems/enumerated_attribute-0.2.3/lib/enumerated_attribute/attribute.rb:4
    from /Users/tinyclanger/.bundle/ruby/1.8/gems/enumerated_attribute-0.2.3/lib/enumerated_attribute.rb:1:in `require'
    from /Users/tinyclanger/.bundle/ruby/1.8/gems/enumerated_attribute-0.2.3/lib/enumerated_attribute.rb:1
    from /Library/Ruby/Gems/1.8/gems/bundler-0.9.21/lib/bundler/runtime.rb:48:in `require'
    from /Library/Ruby/Gems/1.8/gems/bundler-0.9.21/lib/bundler/runtime.rb:48:in `require'
    from /Library/Ruby/Gems/1.8/gems/bundler-0.9.21/lib/bundler/runtime.rb:43:in `each'
    from /Library/Ruby/Gems/1.8/gems/bundler-0.9.21/lib/bundler/runtime.rb:43:in `require'
    from /Library/Ruby/Gems/1.8/gems/bundler-0.9.21/lib/bundler/runtime.rb:42:in `each'
    from /Library/Ruby/Gems/1.8/gems/bundler-0.9.21/lib/bundler/runtime.rb:42:in `require'
    from /Library/Ruby/Gems/1.8/gems/bundler-0.9.21/lib/bundler.rb:93:in `require'
    from /Users/tinyclanger/Documents/Development/test/config/application.rb:7
    from /Users/tinyclanger/Documents/Development/test/config/environment.rb:2:in `require'
    from /Users/tinyclanger/Documents/Development/test/config/environment.rb:2
    from /Library/Ruby/Gems/1.8/gems/railties-3.0.0.beta3/lib/rails/commands.rb:33:in `require'
    from /Library/Ruby/Gems/1.8/gems/railties-3.0.0.beta3/lib/rails/commands.rb:33
    from script/rails:9:in `require'
    from script/rails:9

Uninstalling enumerated_attribute allows the console to start, but then my models are all broken, of course, as they rely on it…

How can i retrierve label text for my enum attribute?

class Review < ActiveRecord::Base
  STATUS   = [:published, :unpublished, :rejected]

  enum_attr :status, STATUS, :init => :unpublished do
    label :unpublished => 'Not published yet'
    label :published   => 'Published'
    label :rejected    => 'Rejected!'
  end
end

review = Review.new
review.status = :published

So, how can i retrieve label text for status attr?
(I'm new to ruby & ror).

Formtastic ~>2.0.2 integration

Hello
What about integration with formtastic 2.0.2? Patch that was published for later version of formtastic doesn't work for new one =(

Deprecation warning when running RSpec tests

Am getting this warning....

"DEPRECATION WARNING: You're trying to create an attribute 'game_category'. Writing arbitrary attributes on a model is deprecated. Please just use 'attr_writer' etc. (called from write_enumerated_attribute at /Users/Dom/.rvm/gems/ruby-1.9.3-p194/bundler/gems/enumerated_attribute-56c3506a7778/lib/enumerated_attribute/integrations/active_record.rb:24)"

... when running RSpec tests. Tests do pass okay, and the code works fine. Is it something I am doing?

helper needed for labels

I'm hoping I missed something in the documentation. It seems there should be a view helper available to simplify the code below.

<%= d.fields_for :incidents do |incident| %>
<%= incident.object.enums(:incident_type).label(incident.object.incident_type.to_sym) %>
...

enumerated_attribute vs. xmlBuilder

I have an enumerated attribute which works beautifully until I try to put it into xml.

xml.instruct! :xml, :version => "1.0", :encoding => "UTF-8"
xml.publications do
  @publications.each do |p|
       xml.Year(p.Year)
       xml.Status(p.Status)
   end
end

produces


2009
Status:Published/

rather than the hoped for
Published

What should I do to get the enumerated attribute as value of the element.

enum_attr messes up custom setters on .new and .create

# user.rb
# t.enum :rank
# t.string :name
class User < ActiveRecord::Base
    enum_attr :rank, %w{user administrator}

    def name=(_name)
        self[:name] = "#{_name.upcase} + THE GREAT"
    end
end

Then

User.new(:name => "bob").name =>
"bob"

User.create(:name => "bob").name =>
"bob"

When the return should be "BOB THE GREAT"

When enum_attr is commented out, it works correctly.

Using current version of enumerated_attribute (0.2.16) and Rails 3.1

Rails 3.0.0 Crash

Hi all. I've intalled enumerated_attribute gem, and my app was working fine with migrations without 't.enum' types. Just rake db:migrate was making some noise for not knowing 'enum' methods.
After putting the line 'config.gem "enumerated_attribute"' in my environment.rb all my rails instance crashed ActiveRecord. Now my app can't connect with database.

I made a test, by installing a new fresh rails instance and creating a simple person scaffold. It works fine, my rails environment is updated and cleanup. But after writing the line to call the gem of 'enumerated_attribute' on my environment.rb, boom!

Any suggestions?

Defining other methods in an ActiveRecord model doesn't work

I'm trying to define my own methods like the 'parked?' and 'driving?' examples but can't get it to work. It works as long as the attribute is not a column in my database.

class Tractor < ActiveRecord::Base
  enum_attr :gear, %w(reverse ^neutral first second over_drive) do
    driving? [:first, :second, :over_drive]
  end
end

t = Tractor.new
t.driving?                        # => false

Works when 'gear' is not a column in the Tractors table but does not work when 'gear' is defined as a t.enum field in the migration (it will always return false in that case). It seems this has something to do with the string versus symbol comparison.

Using MySQL 5.1.40 and Ruby 1.8.7 with Rails 2.3.5.

Breaks on creating a record with fields from associated record.

I'm trying to create a new user and I pass a 'note' in the params as it's an associated model but this breaks with:

ActiveModel::MassAssignmentSecurity::Error (Can't mass-assign protected attributes: note):
activemodel (3.2.13) lib/active_model/mass_assignment_security/sanitizer.rb:48:in process_removed_attributes' activemodel (3.2.13) lib/active_model/mass_assignment_security/sanitizer.rb:20:indebug_protected_attribute_removal'
activemodel (3.2.13) lib/active_model/mass_assignment_security/sanitizer.rb:12:in sanitize' activemodel (3.2.13) lib/active_model/mass_assignment_security.rb:230:insanitize_for_mass_assignment'
activerecord (3.2.13) lib/active_record/attribute_assignment.rb:75:in assign_attributes' activerecord (3.2.13) lib/active_record/base.rb:498:ininitialize'
lib/enumerated_attribute/integrations/active_record.rb:106:in `new'

When used with sunspot gem: method_missing_without_enumerated_attribute already exists.

Scenario:

Use enumerated_attribute on some models, then try to use sunspot gem.

When you declare a model to be searchable using sunspot, then attempt to do rake sunspot:solr:reindex to build your index, you get:

rake aborted!
method_missing_without_enumerated_attribute already exists.  Circular references not permitted.
/Users/aisrael/.rvm/gems/ruby-1.9.3-p327/gems/meta_programming-0.2.2/lib/meta_programming/object.rb:43:in `block in safe_alias_method_chain'
/Users/aisrael/.rvm/gems/ruby-1.9.3-p327/gems/meta_programming-0.2.2/lib/meta_programming/object.rb:39:in `class_eval'
/Users/aisrael/.rvm/gems/ruby-1.9.3-p327/gems/meta_programming-0.2.2/lib/meta_programming/object.rb:39:in `safe_alias_method_chain'
/Users/aisrael/.rvm/gems/ruby-1.9.3-p327/gems/meta_programming-0.2.2/lib/meta_programming/object.rb:66:in `define_chained_method'
/Users/aisrael/.rvm/gems/ruby-1.9.3-p327/bundler/gems/enumerated_attribute-84221b872f7f/lib/enumerated_attribute/integrations/active_record.rb:107:in `singletonclass'
/Users/aisrael/.rvm/gems/ruby-1.9.3-p327/bundler/gems/enumerated_attribute-84221b872f7f/lib/enumerated_attribute/integrations/active_record.rb:94:in `block in define_enumerated_attribute_new_method'
/Users/aisrael/.rvm/gems/ruby-1.9.3-p327/bundler/gems/enumerated_attribute-84221b872f7f/lib/enumerated_attribute/integrations/active_record.rb:93:in `class_eval'
/Users/aisrael/.rvm/gems/ruby-1.9.3-p327/bundler/gems/enumerated_attribute-84221b872f7f/lib/enumerated_attribute/integrations/active_record.rb:93:in `define_enumerated_attribute_new_method'
/Users/aisrael/.rvm/gems/ruby-1.9.3-p327/bundler/gems/enumerated_attribute-84221b872f7f/lib/enumerated_attribute/attribute.rb:45:in `create_enumerated_attribute'
/Users/aisrael/.rvm/gems/ruby-1.9.3-p327/bundler/gems/enumerated_attribute-84221b872f7f/lib/enumerated_attribute.rb:13:in `enumerated_attribute'
/Users/aisrael/workspaces/rails/likejobs/web/app/models/user.rb:22:in `<class:User>'
/Users/aisrael/workspaces/rails/likejobs/web/app/models/user.rb:1:in `<top (required)>'
/Users/aisrael/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:251:in `require'
/Users/aisrael/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:251:in `block in require'
/Users/aisrael/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:236:in `load_dependency'
/Users/aisrael/.rvm/gems/ruby-1.9.3-p327/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:251:in `require'
/Users/aisrael/.rvm/gems/ruby-1.9.3-p327/gems/sunspot_rails-1.3.3/lib/sunspot/rails/tasks.rb:34:in `block (3 levels) in <top (required)>'
/Users/aisrael/.rvm/gems/ruby-1.9.3-p327/gems/sunspot_rails-1.3.3/lib/sunspot/rails/tasks.rb:34:in `each'
/Users/aisrael/.rvm/gems/ruby-1.9.3-p327/gems/sunspot_rails-1.3.3/lib/sunspot/rails/tasks.rb:34:in `block (2 levels) in <top (required)>'
Tasks: TOP => sunspot:solr:reindex => sunspot:reindex
(See full trace by running task with --trace)

This happens even if the searchable model itself doesn't declare any enumerated_attributes.

dry_scaffold sometimes crashes when used with this plugin

Ruby 1.9.1, latest dry_scaffold and enumerated_attribute sometimes crashes with the error

/usr/lib64/ruby/gems/1.9.1/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require': no such file to load -- rails/generators (MissingSourceFile)
from /usr/lib64/ruby/gems/1.9.1/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `block in require'
from /usr/lib64/ruby/gems/1.9.1/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:521:in `new_constants_in'
from /usr/lib64/ruby/gems/1.9.1/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'
from /home/anshul/project/vendor/plugins/enumerated_attribute/lib/enumerated_attribute/rails_helpers.rb:28:in `<top (required)>'

This happens because rescue on that line 30 is ineffective. Here is a trivial patch... http://baboonlogic.com/files/0001-BUGFIX-incorrect-use-of-rescue.patch

Cannot use accentued character.

Accentued special char ( éèàÉÈã....) cannot be used as enum value. Problematic in almost all non english-germanic language.

Rails 3 error

I added a basic enum field, then when running db:migrate it complains about this:
undefined method to_tag' for classActionView::Helpers::InstanceTag'

label and I18n

Here is my code in my model :

    enum_attr :currency, %w(en ja), :init => I18n.locale do 
      label :en => I18n.t(:dollar)
      label :ja => I18n.t(:yen)
    end

My locale files :

    en:
      dollar : "$"
      yen : "¥"
    ja:
       dollar: "$"
       yen : "円"

This works as expected on my development environment, but on my staging (and production) environment, the labels are strange!
In my page I print out I18n.locale and I18n.default_locale, and both are "ja" as expected.
But the labels are:
<option value="en">translation missing: en.dollar</option>
<option selected="selected" value="ja">translation missing: en.yen</option>

Why it is looking for "en" despite that I18n.locale = "ja" ?
Even why it cannot find "en.dollar" despite that it exists in my locale file ?

enum value written to db as symbol when using acts_as_versioned

rails 2.3.8
acts_as_versioned 0.3.1

I have an enum value, that when the model is saved, and a version is created in the db, by acts_as_versioned, ends up with a symbol instead of the expected string.

my solution to address this in the short term is to intercept calls to my enum, detect if the callstack contains acts_as_versioned, and return the string value, instead of the symbol.

This may not be the best way to handle it, so I'm looking for suggestions.

#detect when called by the acts_as_versioned clone process, and write out a string, instead of the symbol

alias_method :mask_ssn_orig, :mask_ssn
  def mask_ssn
    val = mask_ssn_orig
    val = val.to_s if caller.any? {| method | method.match /acts_as_versioned/}
    val
 end

I guess I could have intercepted the write method instead of the read method.
I'm not sure why this happens.
Perhaps I need to move the enum behavior to a module, and include it in my main class, and the versioned class that acts_as_versioned creates, so the default enum read/write behavior will be present in both places, without me having to monkey around with this interception junk.

Thoughts?

Use in multiple models?

Hi,

Is it posible to define a GenderEnum like:

require 'enumerated_attribute'

class GenderEnum
  enum_attr :gender, %w(male female)
end

and use it in many models?

Many thanks

the :include_blank option for form helper is not working

The option :include_blank is not wokring when set to false
<%= form.enum_select :gender, :include_blank => false %>

The bug is in the rails_helper:
def to_enum_select_tag(options, html_options={})
choices = []
if self.object.respond_to?(:enums)
enums = self.object.enums(method_name.to_sym)
choices = enums ? enums.select_options : []
if (value = self.object.send(method_name.to_sym))
options[:selected] ||= value.to_s
else
options[:include_blank] ||= true
end
end
to_select_tag(choices, options, html_options)
end

the line
options[:include_blank] ||= true
should be
options[:include_blank] = enums.allows_nil? if options[:include_blank].nil?

Multiple enum_attr's and annotate gem

Given a model that looks like

class user < ActiveRecord::Base
    enum_attr :status %w{suspended pending approved}
    enum_attr :role %w{regular moderator admin}
end

When attempting to run annotate on that model,
Then I get the following error

Unable to annotate user.rb: #<MetaProgramming::AliasMethodChainError: method_missing_without_enumerated_attribute already exists.  Circular references not permitted.>

Nothing annotated.

I seem to have narrowed it down to the fact that enum_attr is being used twice in the model. Removing (or commenting out) one or both allows the model to be annotated as expected, even when both enums are defined in the migration. My guess is that method_missing_without_enumerated_attribute is being defined each time enum_attr is used, but I don't know enough about the internals of enumerated_attribute to determine this.

Easier way to get label

This is more of a question than an issue. I'm just wondering if there is a more convenient way of getting the label for an enum?

Lets say I have an enum_attr called "visibility" on the Post model. Right now I'm doing this:

p = Post.find(1)
p.enums(:visibility).label(p.visibility)

Is there an easier way?

migrations don't work in postgresql

change_table...
t.enum fieldname
...

error type "string" DOES NOT EXIST.

didn't catch this in development, apparently sqlite doesn't mind it, but PostgreSQL did not like it when i pushed to staging.

WHY "...but may not be set to nil thereafter."

Sorry for bad English. I want to help improve this plugin. Why so restriction? It could be more logically if there will be flag wich allow to use empty value which not dependent on action 'new' or 'edit'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.