lucascaton / enumerate_it Goto Github PK
View Code? Open in Web Editor NEWEnumerations for Ruby with some magic powers! π©
License: Other
Enumerations for Ruby with some magic powers! π©
License: Other
In enumerations/status.rb
class Status < EnumerateIt::Base
associate_values(
:busy,
:away,
:'out of office',
:'in a meeting'
...
end
Will error with NameError: wrong constant name OUT OF OFFICE
, NameError: wrong constant name IN A MEETING
etc.
Workaround involves using a hash instead of an array:
class Status < EnumerateIt::Base
associate_values(
busy: 'busy',
away: 'away',
out_of_office: 'out of office',
in_a_meeting: 'in a meeting'
...
end
I have a patch I can submit for which should allow the use of symbols with spaces in it if you're interested. The patch involves removing spaces before the call to const_set
in base.rb
.
I also wanted to provide this solution to others as well.
Hi first of all thanks for your work! π
Would make sense to have a method that would return an array of values, just like we have for the keys?
I've found it useful in one task and that made me wonder why the method it's not available?
Hi! Thanks for this nice gem.
I have the below error when generate a hash enum:
Command:
rails g enumerate_it:enum CivilStatus single:1 married:2 divorced:3 widower:4
Error:
Could not generate field 'single' with unknown type '1'.
Enviroment:
In Rails 6 works.
Thanks!
My CI Server (Codeship) is failing because of enumerate_it:
Fetching gem metadata from https://rubygems.org/........
Resolving dependencies...
Could not find enumerate_it-1.2.4 in any of the sources
Running on ruby 1.9.2 and rails 3.1.4
I am getting the following error when I attempt to run my request specs.
Failure/Error: click_on 'SEND INQUIRY'
ActionView::Template::Error:
undefined method `occasion' for #Event:0x007fe28da08800
I've tried including the EnumerateIt gem in various parts of the spec_helper, and tried placing in the preload block to get the models to load. I have also had this problem in another model, where the enumeration will stop the spec from running.
Dir["#{Rails.root}/app/models/enumerations/*.rb"].each do |model|
puts model
load model
end
The shortened model Event code is:
class Event < ActiveRecord::Base
include EnumerateIt
has_enumeration_for :occasion
I call the enumeration in the view as the possible values for a drop down list
class Occasion < EnumerateIt::Base
associate_values(
:no_occasion => [1, 'Casual'],
:holiday => [4, 'Holiday'],
:work_related => [5, 'Work'],
:other => [6, 'Other']
)
end
view
<%= f.select :occasion, options_for_select(
Occasion.sorted_list.unshift(['Select from list', 0]), :selected => (@event.occasion ? @event.occasion : nil)) %>
the other enumeration which throws an error ```/Users/davidcys/.rvm/gems/ruby-1.9.2-p290/gems/activemodel-3.1.4/lib/active_model/attribute_methods.rb:385:inmethod_missing': undefined method
consumer_profile' for #User:0x007fe61e312c78 (NoMethodError)
model - user
class User < ActiveRecord::Base
include EnumerateIt
include TimeConverter
has_enumeration_for :invited_mechanism, :create_helpers => true
has_enumeration_for :consumer_profile, :create_helpers => true
end
in this case, commenting out just the enumeration for :consumer_profile allows the spec to complete successfully
Hello Cassio! Nice job! Thanks!
I using enumerate_it in my project. And, in "status" field I need the select (combobox) in a specific sequence (ex: Published, Draft, Inactive). If I use to_a method to populate my select in rails, it will always sort my values.
Do you know how I can show values in to_a without sort?
I have a fork with all tests passing with more one param in to_a: MyEnum.to_a :sort => false (it's sets to true by default).
What do you think?
Thanks
New method:
def self.to_a params = {:sort => true}
raise ArgumentError, 'Argument :sort is not Boolean' unless params[:sort].is_a?(TrueClass) || params[:sort].is_a?(FalseClass) if params[:sort]
(params[:sort]) ? enumeration.values.map {|value| [translate(value[1]), value[0]] }.sort_by { |value| value[0] } : enumeration.values.map {|value| [translate(value[1]), value[0]] }
end
PS: If you have any suggestion to new code don't be ugly, please tell me ;)
It would be great if the human representation for each option could be internationalized.
enumerations:
foobar:
option_a: 'Option A'
option_b: 'Option B'
Hello Cassio!
I'm developing an API that user need to assign to model a status (active or inactive), but it need to pass the integer.
To become more comprehensive, I added the following code in controller (the user can pass the value instead integer):
model.status = CommonStatus.value_for(params[:status].upcase)
But I'd like to use:
model.status = :active
What you think? Or do you suggest a better workaround?
Thanks!
Is there a way to have "base" enumeration and then extend it with another enumeration, adding additional values to the extended enumeration as well as carrying the original/base enumeration values?
Example case:
We might have a tax enumeration like
class Payroll::TaxTableType < EnumerateIt::Case
associate_values(:futa, :suta, :fica, :medicare, :fit, :sit, :lit)
end
We then have a model like "Payroll::TaxTable" that has a table_type field that is connected to that association. So far, easy!
In some other table, we have the need to reference a specific tax table type OR allow any type. For example/hypothetically:
class Payroll::TaxTableUserType < Payroll:TaxTableType
associate_values(:any)
end
Which would ideally result in a list of values that looked like :any, :futa, :suta, :fica, :medicare, etc
That may be just a long way of asking if there is a way to accomplish this when you want two enumerations but just adds a bit on to another enumeration
When using polymorphic enumerations, after I assign a value to a properly setup ActiveRecord model field, I can then reference that field with a _object suffix and then access the polymorphic instance method for the currently assigned value. Using the project documentation as an example, I can write
p.relationship_status_object.saturday_night
However, if I have a enumeration value that I have not assigned to a record/model (e.g. want to filter through enumerations for a particular related value), there is no easy way to get that _object reference if in order to access that polymorphic instance method. Right now, we're hacking around this with a method like this:
def type_instance(type)
Payroll::TaxTableType.const_get(type.titleize.gsub(' ','')).new
end
# Access via ActiveRecord model assignment
myRec.tax_type = Payroll::TaxTableType::FICA
myRec.tax_type_object.maximum_brackets
# Access without assigning value to an ActiveRecord model
x = type_instance(Payroll::TaxTableType::FICA)
x.maximum_brackets
(where the Payroll::TaxTableType is an enumeration class and maximum_brackets is a method defined for each possible Payroll::TaxTableType enumeration value via polymorphic class objects for each enumeration value).
It feels like there should be an enumeration method that, given an enumeration value (what is actually stored in such a field) can be translated into an instance of that values polymorphic class without having to first assign a value to an ActiveRecord field/attribute.
For example, in your notes, If I try to set the relationship_status on a person - I can in the console - but when I try to save it, the database still sets the value with null.
Can you add guidance as to what the data type the underlying association should be? (for different database vendors) - I'm assuming the associated types should be integer - but I can't get the enumerated type to save.
Is there a sample somewhere I should be able to see that at? and show us the migration for the underlying object (for example, for the Person class in your sample)
Thanks in advance.
--Dan
The translate for namespaced enumeration is not working, any workaround for it?
It's possible support the Mongoid? http://mongoid.org/
enumerate_it.rb:1:in `<top (required)>': uninitialized constant ActiveRecord (NameError)
:(
ActiveRecord updated_at doesn't get updated when a model class has_enumeration_for.
I'm using enumerate_it 0.7.17:
from Gemfile.lock:
enumerate_it (0.7.17)
activesupport (>= 3.0.0)
I have two classes:
class Thing < ActiveRecord::Base
end
class ThingWithEnum < ActiveRecord::Base
self.table_name = 'things'
has_enumeration_for :state, :with => ThingState, :create_helpers => true, :create_scopes => true
end
Testing in the rails console:
ruby-1.9.2-p290 :001 > t = Thing.find( 1 )
Thing Load (0.4ms) SELECT things
.* FROM things
WHERE things
.id
= 1 LIMIT 1
=> #<Thing id: 104, ... >
ruby-1.9.2-p290 :002 > t.test = 1
=> 1
ruby-1.9.2-p290 :003 > t.save
(0.1ms) BEGIN
(1.7ms) UPDATE things
SET test
= 1, updated_at
= '2012-10-25 00:02:49' WHERE things
.id
= 1
(15.2ms) COMMIT
ruby-1.9.2-p290 :001 > t = ThingWithEnum.find( 1 )
ThingWithEnum Load (0.4ms) SELECT things
.* FROM things
WHERE things
.id
= 1 LIMIT 1
=> #<Thing id: 104, ... >
ruby-1.9.2-p290 :002 > t.test = 2
=> 2
ruby-1.9.2-p290 :003 > t.save
(0.1ms) BEGIN
(1.4ms) UPDATE things
SET test
= 2 WHERE things
.id
= 1
(23.1ms) COMMIT
=> true
I have a rails engine that need add extra values to an existing enumeration in a rails application. I had found a workahound to make it works, but it generate warning when its setting the constants:
MyEngine.enumeration_class_string.constantize.class_eval do
def self.add_values(*args)
current_keys = keys || []
current_keys += args
associate_values(*current_keys)
end
add_values(:my_extra_value1, :my_extra_value2)
end
I considered three possible solutions:
add_values
mehtod that receive the new values.What do you think?
Hi there!
Is there a way to set a default value when using an enumeration with an ActiveRecord model (or any other kind of object)?
I have an enumeration class like this:
class MyEnumeration < EnumerateIt::Base
associate_values :b, :a, :c
sort_by :none
end
If I call MyEnumeration.list, it will return ["a", "b", "c"] but I want to receive ["b", "a", "c"]. Is there any way to do that?
DEPRECATION WARNING: ActiveRecord::Base.raise_in_transactional_callbacks= is deprecated, has no effect and will be removed without replacement. (called from <top (required)> at (...)/config/initializers/enumerate_it.rb:1)
Content of my enumerate_it.rb:
ActiveRecord::Base.extend EnumerateIt
Hello
I have this class
class TimePeriod < EnumerateIt::Base
associate_values(
:hours24 => [0, '24 hours'],
:hours48 => [1, '48 hours'],
:week1 => [2, 'a week'],
:month1 => [3, 'a month']
)
end
and i am trying to find a way to give to the enumerator the integer 1 and return '48 hours'
Something like name_for(1)->'48 hours'
Am i doing something wrong or i missed something in the ReadME?
Thanks
When running:
rails g enumerate_it:enum CivilStatus single married divorced widower concubinage separated stable
I'm getting this error:
create config/locales/civil_status.yml
/.../enumerate_it-3.2.3/lib/generators/enumerate_it/enum/enum_generator.rb:37:in `fields': undefined method `type' for nil:NilClass (NoMethodError)
if attributes.first.type == :string
^^^^^
from /.../enumerate_it-3.2.3/lib/generators/enumerate_it/enum/templates/enumerate_it.rb:3:in `template'
I tried to debug:
def fields
puts attributes # => nil
puts args # => ["single", "married", "divorced", "widower", "concubinage", "separated", "stable"]
if attributes.first.type == :string
attributes.map(&:name)
else
attributes.map { |attribute| [attribute.name, attribute.type] }
end
end
Looks like argument :attributes, type: :hash
isn't working for arrays, just for hashes. I tried to change to argument :attributes, type: :array
and worked fine.
This PR #103 changed from 'array' to :hash and broke. I did a search for argument
method, but I didn't find anything about an argument accepts two types (hash and array), so I'm not sure how to solve it, but I will open a PR to discuss the solution.
Versions:
# Gemfile.lock
...
enumerate_it (3.2.3)
activesupport (>= 5.0.7.2)
...
rails (7.0.4)
...
RUBY VERSION
ruby 3.1.2p20
rails generate enumerate_it:enum foo_type bar_baz
create config/locales/foo_type.yml
create app/enumerations/foo_type.rb
# config/locales/foo_type.yml
en:
enumerations:
foo_type:
bar_baz: 'Bar_baz'
I would expect the value for bar_baz
to be humanize: 'Bar baz'
instead of 'Bar_baz'
.
"bar_baz".humanize
# => "Bar baz"
I have several enumerations. I'm setting the following for each of them:
create_helpers: { prefix: true },
create_scopes: { prefix: true }
Would be nice to be able to set default options, e.g.
EnumerateIt.configuration.defaults = {
create_helpers: { prefix: true },
create_scopes: { prefix: true }
}
Those this gem works will Rails 6?
It would be nice to add the version in the documentation and run the test suite on the version.
Hello CΓ‘ssio,
When I use version 0.7.13 with ruby 1.8.7-p352 I got the following error:
rake aborted! /home/felipefontoura/.rbenv/versions/1.8.7-p352/lib/ruby/gems/1.8/gems/enumerate_it-0.7.13/lib/enumerate_it.rb:228: odd number list for Hash ...lues.collect {|value| { value: value[0], label: translate(va... ^ /home/felipefontoura/.rbenv/versions/1.8.7-p352/lib/ruby/gems/1.8/gems/enumerate_it-0.7.13/lib/enumerate_it.rb:228: syntax error, unexpected ':', expecting '}' ...lues.collect {|value| { value: value[0], label: translate(va... ^ /home/felipefontoura/.rbenv/versions/1.8.7-p352/lib/ruby/gems/1.8/gems/enumerate_it-0.7.13/lib/enumerate_it.rb:228: syntax error, unexpected ':', expecting '=' ...lue| { value: value[0], label: translate(value[1]) } }.to_js... ^ /home/felipefontoura/.rbenv/versions/1.8.7-p352/lib/ruby/gems/1.8/gems/enumerate_it-0.7.13/lib/enumerate_it.rb:228: syntax error, unexpected '}', expecting kEND ...label: translate(value[1]) } }.to_json ^ /home/felipefontoura/.rbenv/versions/1.8.7-p352/lib/ruby/gems/1.8/gems/bundler-1.1.3/lib/bundler/runtime.rb:68:in `require' /home/felipefontoura/.rbenv/versions/1.8.7-p352/lib/ruby/gems/1.8/gems/bundler-1.1.3/lib/bundler/runtime.rb:68:in `require' /home/felipefontoura/.rbenv/versions/1.8.7-p352/lib/ruby/gems/1.8/gems/bundler-1.1.3/lib/bundler/runtime.rb:66:in `each' /home/felipefontoura/.rbenv/versions/1.8.7-p352/lib/ruby/gems/1.8/gems/bundler-1.1.3/lib/bundler/runtime.rb:66:in `require' /home/felipefontoura/.rbenv/versions/1.8.7-p352/lib/ruby/gems/1.8/gems/bundler-1.1.3/lib/bundler/runtime.rb:55:in `each' /home/felipefontoura/.rbenv/versions/1.8.7-p352/lib/ruby/gems/1.8/gems/bundler-1.1.3/lib/bundler/runtime.rb:55:in `require' /home/felipefontoura/.rbenv/versions/1.8.7-p352/lib/ruby/gems/1.8/gems/bundler-1.1.3/lib/bundler.rb:119:in `require' /home/felipefontoura/Dev/ruby/workspace/alpex-site/config/application.rb:7 /home/felipefontoura/Dev/ruby/workspace/alpex-site/Rakefile:5:in `require' /home/felipefontoura/Dev/ruby/workspace/alpex-site/Rakefile:5 /home/felipefontoura/.rbenv/versions/1.8.7-p352/lib/ruby/gems/1.8/gems/rake-0.9.2.2/lib/rake/rake_module.rb:25:in `load' /home/felipefontoura/.rbenv/versions/1.8.7-p352/lib/ruby/gems/1.8/gems/rake-0.9.2.2/lib/rake/rake_module.rb:25:in `load_rakefile' /home/felipefontoura/.rbenv/versions/1.8.7-p352/lib/ruby/gems/1.8/gems/rake-0.9.2.2/lib/rake/application.rb:501:in `raw_load_rakefile' /home/felipefontoura/.rbenv/versions/1.8.7-p352/lib/ruby/gems/1.8/gems/rake-0.9.2.2/lib/rake/application.rb:82:in `load_rakefile' /home/felipefontoura/.rbenv/versions/1.8.7-p352/lib/ruby/gems/1.8/gems/rake-0.9.2.2/lib/rake/application.rb:133:in `standard_exception_handling' /home/felipefontoura/.rbenv/versions/1.8.7-p352/lib/ruby/gems/1.8/gems/rake-0.9.2.2/lib/rake/application.rb:81:in `load_rakefile' /home/felipefontoura/.rbenv/versions/1.8.7-p352/lib/ruby/gems/1.8/gems/rake-0.9.2.2/lib/rake/application.rb:65:in `run' /home/felipefontoura/.rbenv/versions/1.8.7-p352/lib/ruby/gems/1.8/gems/rake-0.9.2.2/lib/rake/application.rb:133:in `standard_exception_handling' /home/felipefontoura/.rbenv/versions/1.8.7-p352/lib/ruby/gems/1.8/gems/rake-0.9.2.2/lib/rake/application.rb:63:in `run' /home/felipefontoura/.rbenv/versions/1.8.7-p352/lib/ruby/gems/1.8/gems/rake-0.9.2.2/bin/rake:33 /home/felipefontoura/.rbenv/versions/1.8.7-p352/bin/rake:23:in `load' /home/felipefontoura/.rbenv/versions/1.8.7-p352/bin/rake:23
I can't imagine what is happening, because when I use 0.7.11 everything runs fine.
If I can help with anything, just tell me ;)
Thanks and nice job! I'm using enumerate_it on my last 10 projects and is amazing gem, very useful!
Hello, can I fetch key-value collection from enum object?
>> Organization.new.org_type_object
=> nil
vs
>> Organization.new(org_type: "Admin").org_type_object
=> #<OrgTypes::Admin:0x0000000158bf5320>
Of course this doesn't work:
associate_values(
nil => nil,
since the object doesn't have a class to be an instance of until there is a value on the attribute, and nil wouldn't reference any class at all. But I didn't see it mentioned in the README, and it threw me for a minute.
This isn't really a bug. It is something obvious that wasn't obvious until it hit me. I'm refactoring legacy code, and adding enumerators, and the old code does many checks of type and status on objects, regardless of whether the values have been set, so the object replacement paradigm breaks down there. (for example they are checked during the custom validations on the model, which are before create, and possibly without the instance having a value set for anything).
The solution is to defensively code access to the enumeration object, like with &
or Rails' try
, etc.
Greetings ... great gem but not clicking yet.
I've set this up and it seems to work fine as documented... except I cannot save it.
i have model
class EventType < EnumerateIt::Base associate_values( :phone => [1, 'Phone'], :meeting => [2, 'Meeting'], :conference => [3, 'Conference'], :task => [4, 'Task'], :email => [4, 'Email'] ) end
and in Events:
class Event < ActiveRecord::Base extend EnumerateIt attr_accessor :event_type has_enumeration_for :event_type, :with => EventType end
My event_type column in the DB in events is type: integer
When i manually enter data in the DB and try to list the records nothing dispalys for Event_type even though i can debug it and see the value in the attributes.
--- !ruby/object:Event raw_attributes: id: '1' name: Start up Meeting event_start: '2015-03-02 03:52:00' event_end: '2015-03-02 15:52:00' manager_id: '1' backup_id: '1' location: meeting room 3 created_at: '2015-03-02 03:53:57.160064' updated_at: '2015-03-02 03:53:57.160064' description: eventable_id: eventable_type: event_type: '3'
I am thinking maybe I need to use another column type. What value should get saved?
:meeting or 2 ?
in the form the drop down works fine and passes the value to the console object and the request parameters
{"utf8"=>"β", "_method"=>"patch", "authenticity_token"=>"Q5J84VkpYcr1nGSoJDmatOkXA2s2yvvcY322epuCLDJuFmzxPRrhQNNw4HANJPMSmD2rf5TMNHqypoBPmdNR4w==", "event"=>{"name"=>"Start up Meeting", "event_type"=>"4", "event_start(1i)"=>"2015", "event_start(2i)"=>"3", "event_start(3i)"=>"2", "event_start(4i)"=>"03", "event_start(5i)"=>"52", "event_end(1i)"=>"2015", "event_end(2i)"=>"3", "event_end(3i)"=>"2", "event_end(4i)"=>"15", "event_end(5i)"=>"52", "manager_id"=>"1", "backup_id"=>"1", "location"=>"meeting room 3"}, "commit"=>"Update Event", "controller"=>"events", "action"=>"update", "id"=>"1"}
but I get this error when it tries to update:
ActionView::MissingTemplate at /events/1 Missing template events/update, application/update with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in: * "/home/ims/railsdev/watan_0228/app/views" * "/home/ims/.rvm/gems/ruby-2.0.0-p353/gems/devise-3.4.1/app/views"
any help would be appreciated
Thanks
Steve
Hello,
Nice Job!
Is-it possible to add to many enumerations? For example to save user hobbies (multiple choices)
Thank you
Hi there,
can enumerate_it automagically use postgresql enum types?
Here is a Tutorial with some rails-examples:
Sometimes, we need to keep a value at the end of a sorted list regardless its value.
For example, I have a list of movie types like ['comedy', 'romance', 'thiller', 'other'] and I need to keep the value 'other' always at the end even if I sort.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.