Advertisement
Guest User

Untitled

a guest
Dec 23rd, 2017
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
BibTeX 2.27 KB | None | 0 0
  1. Enum method in Ruby on Rails
  2. A little history.
  3. Enumerize gem was written by Sergey Nartimov as a new way to handle specific attributes in a database column. Thus, developers could manage attributes that could only take predefined values. For example, if you could only have 3 types of enterprises, you could use something like this:
  4. enumerize enterprise_type, in: ['large', medium', 'small']
  5. This also creates new methods like @enterprise.enterprise_type_large? for handle the value in the column. This is good!
  6. You could to use them as select input in the view:
  7. # Enumerize
  8. options_for_select(Enterprise.enterprise_type.options)
  9. # Enum
  10. options_for_select(Enterprise.enterprise_types)
  11. The idea of this was to handle those attributes on the model. The Rails core team saw that many developers were using it in this way on their projects
  12. From Rails 4 was included as module to ActiveRecord::Enum. But it was not until Rails 5 that enum support was completed.
  13. In Rails 4 does not exists supports for somethings as _preffix or _suffix.
  14. If you’d 2 enum methods with the same values for example:
  15. enum gift_status: [:open, :closed]
  16. enum door_status: [:open, :closed]
  17. This brings errors because creates 2 same method for “open? or closed?”.
  18. In Rails 5.x was added this new support for those methods so you could to do:
  19. enum gift_status: [:open, :closed], _prefix: true
  20. enum door_status: [:open, :closed], _suffix: :my_door
  21. This fixed these errors.
  22. # With _prefix
  23. @gift.gift_status_open?
  24. # With _suffix
  25. @door.my_door_open?
  26. Enum offers methods to set values, for example:
  27. @door.my_door_open? => false
  28. @door.my_door_open!
  29. @door.my_door_open? => true
  30. Conclusion
  31. 1- When must I to use enum or enumerize?
  32. R: If you consider that your attributes must be a few, so you could to use them.
  33. 2- What’s better between enum and enumerize?
  34. R: Both are good, they work similar. Rails core always be updating enum module and adding new features and enumerize too.
  35. 3- What’s a difference between enum and enumerize?
  36. R: The major different between them it is that enum work with integer datatype and enumerize with strings.
  37. 4- Could I create default values with both?
  38. R: Yes, with enum you must to do with migration file adding default argument. With enumerize you can do it in the model with default too.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement