Guest User

Untitled

a guest
Jul 22nd, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. class NeuroticException < Exception; end
  2.  
  3. module NeuroticBuilder
  4.  
  5. @@_required_on_create = []
  6.  
  7. def build(*args)
  8. instance = self.send(:new, *args)
  9. yield(instance) if block_given?
  10.  
  11. @@_required_on_create.each do |attribute|
  12. if instance.respond_to? attribute and blank? instance.send(attribute)
  13. raise NeuroticException, "'#{attribute}' is blank but is required"
  14. end
  15. end
  16.  
  17. instance
  18. end
  19.  
  20. private
  21. def blank?(attr_value)
  22. attr_value.respond_to?(:empty?) ? attr_value.empty? : !self
  23. end
  24.  
  25. def required_on_creation(*attributes)
  26. @@_required_on_create = attributes
  27. end
  28.  
  29. def extended(base)
  30. base.include(Buildable::ClassMethods)
  31. end
  32. end
  33.  
  34.  
  35. class Person
  36. extend NeuroticBuilder
  37.  
  38. attr_accessor :first_name, :last_name, :age
  39.  
  40. # See it! You can declare which fields are
  41. # required to build (instanciate) this classe.
  42. #
  43. # If any of attributes aren't filled an
  44. # Exception is raised.
  45. #
  46. # See the tests below for better understanding.
  47. required_on_creation :first_name, :age
  48.  
  49. def initialize(*first_name)
  50. @first_name = first_name
  51. end
  52. end
  53.  
  54.  
  55. require 'test/unit'
  56.  
  57. class TestNeuroticBuilder < Test::Unit::TestCase
  58.  
  59. def test_should_raise_a_exception_because_first_name_isnt_filled_in_creation_of_the_object
  60.  
  61. assert_raise NeuroticException do
  62. person = Person.build do |p|
  63. p.last_name = "Senna"
  64. p.age = 33
  65. end
  66. end
  67. end
  68.  
  69. def test_should_not_raise_exception_because_all_of_required_attributes_are_filled
  70. person = nil
  71.  
  72. assert_nothing_raised do
  73. person = Person.build do |p|
  74. p.first_name = "Ayrton"
  75. p.age = 33
  76. end
  77. end
  78.  
  79. assert_not_nil person
  80. end
  81.  
  82. def test_should_not_raise_exception_because_all_of_required_attributes_are_filled_again
  83.  
  84. assert_nothing_raised do
  85. person = Person.build "Ayrton" do |p| # Note
  86. p.last_name = "Senna"
  87. p.age = 33
  88. end
  89. end
  90. end
  91.  
  92. end
Add Comment
Please, Sign In to add comment