Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class NeuroticException < Exception; end
- module NeuroticBuilder
- @@_required_on_create = []
- def build(*args)
- instance = self.send(:new, *args)
- yield(instance) if block_given?
- @@_required_on_create.each do |attribute|
- if instance.respond_to? attribute and blank? instance.send(attribute)
- raise NeuroticException, "'#{attribute}' is blank but is required"
- end
- end
- instance
- end
- private
- def blank?(attr_value)
- attr_value.respond_to?(:empty?) ? attr_value.empty? : !self
- end
- def required_on_creation(*attributes)
- @@_required_on_create = attributes
- end
- def extended(base)
- base.include(Buildable::ClassMethods)
- end
- end
- class Person
- extend NeuroticBuilder
- attr_accessor :first_name, :last_name, :age
- # See it! You can declare which fields are
- # required to build (instanciate) this classe.
- #
- # If any of attributes aren't filled an
- # Exception is raised.
- #
- # See the tests below for better understanding.
- required_on_creation :first_name, :age
- def initialize(*first_name)
- @first_name = first_name
- end
- end
- require 'test/unit'
- class TestNeuroticBuilder < Test::Unit::TestCase
- def test_should_raise_a_exception_because_first_name_isnt_filled_in_creation_of_the_object
- assert_raise NeuroticException do
- person = Person.build do |p|
- p.last_name = "Senna"
- p.age = 33
- end
- end
- end
- def test_should_not_raise_exception_because_all_of_required_attributes_are_filled
- person = nil
- assert_nothing_raised do
- person = Person.build do |p|
- p.first_name = "Ayrton"
- p.age = 33
- end
- end
- assert_not_nil person
- end
- def test_should_not_raise_exception_because_all_of_required_attributes_are_filled_again
- assert_nothing_raised do
- person = Person.build "Ayrton" do |p| # Note
- p.last_name = "Senna"
- p.age = 33
- end
- end
- end
- end
Add Comment
Please, Sign In to add comment