Advertisement
Guest User

Untitled

a guest
Nov 8th, 2011
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. # ActiveRecord helper to manage an integer `status` column using Ruby :symbols.
  2. # (C) 2009 Marcello Barnaba <vjt@openssl.it> - Released under the terms of the MIT License
  3. # http://sindro.me/
  4. #
  5. # == Usage ==
  6. #
  7. # [REQUIRED] Put this file in lib/
  8. # [OPTIONAL] Fork this gist
  9. # [OPTIONAL] Pluginize it
  10. # [OPTIONAL] Write some tests
  11. # [OPTIONAL] Notify me
  12. #
  13. # Items marked [OPTIONAL] are implicitly marked also
  14. # [APPRECIATED] and will get you a free beer from me ;)
  15. #
  16. # model.rb:
  17. # require 'statuses'
  18. #
  19. # class Model < ActiveRecord::Base
  20. # has_multiple_statuses :public => 1, :private => 2, :whatever => 3
  21. # end
  22. #
  23. # migration.rb:
  24. # add_column :models, :status, :integer, :default => [your choice]
  25. #
  26. # You get:
  27. # model.public?, model.private? and model.whatever? that return a Boolean
  28. # model.status returns the status Symbol (ah ah): model.status #=> :public
  29. # model.status(:db) return the status Integer: model.status(:db) #=> 1
  30. # model.status= makes you able to set the status via a Symbol or an Integer:
  31. # model.status = :public or model.status = 1
  32. #
  33. # Have fun! :) -vjt
  34. #
  35. module MultipleStatuses
  36. def self.included(target)
  37. target.extend ClassMethods
  38. end
  39.  
  40. module ClassMethods
  41. def has_multiple_statuses(statuses_hash)
  42. write_inheritable_attribute :statuses, statuses_hash
  43. class_inheritable_reader :statuses
  44.  
  45. statuses_hash.each do |name, status|
  46. # Defines a query method on the model instance, one
  47. # for each status name (e.g. Song#published?)
  48. define_method("#{name}?") { self.read_attribute(:status) == status }
  49.  
  50. # Defines on the `statuses` object a method for
  51. # each status name. Each return the status value.
  52. # So you can do both statuses[:public] and statuses.public
  53. #
  54. class<<statuses;self;end.send(:define_method, name) { status }
  55. end
  56.  
  57. include InstanceMethods
  58. end
  59. end
  60.  
  61. module InstanceMethods
  62. def status(format = nil)
  63. status = read_attribute :status
  64. if format == :db
  65. status
  66. else
  67. statuses.invert[status]
  68. end
  69. end
  70.  
  71. def status=(value)
  72. if statuses.has_key? value
  73. write_attribute :status, statuses[value]
  74. elsif statuses.values.include? value
  75. write_attribute :status, value
  76. else
  77. raise ActiveRecord::ActiveRecordError, "invalid status #{value.inspect}"
  78. end
  79. end
  80.  
  81. end
  82. end
  83.  
  84. ActiveRecord::Base.send :include, MultipleStatuses
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement