Guest User

Untitled

a guest
Mar 11th, 2018
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. module ModelFactory
  2.  
  3. def valid_user_attributes
  4. {
  5. :username => "scott",
  6. :password => "my-pass",
  7. :password_confirmation => "my-pass",
  8. :gender => "male",
  9. :email_address => "scott@railsnewbie.com",
  10. :email_address_confirmation => "scott@railsnewbie.com",
  11. :date_of_birth => Time.mktime('1985', '06', '12'),
  12. :active => true
  13. }
  14. end
  15.  
  16. def valid_comments
  17. {
  18. :text => "blah blah",
  19. :post => create_post
  20. }
  21. end
  22.  
  23. # ...
  24. end
  25.  
  26.  
  27. ## implementation:
  28.  
  29.  
  30.  
  31. module ModelFactory; end
  32.  
  33. ModelFactory.module_eval do
  34.  
  35. instance_methods.each do |method|
  36. if method =~ /valid_(.*)_attributes/
  37. model_name_as_underscores = $1
  38. model_name_as_class = instance_eval($1.classify)
  39.  
  40. define_method "new_#{model_name_as_underscores}" do |*args|
  41. hash = create_hash_from_args(*args)
  42. model_name_as_class.new(instance_eval("#{method}.merge(hash)"))
  43. end
  44.  
  45. define_method "create_#{model_name_as_underscores}" do |*args|
  46. hash = create_hash_from_args(*args)
  47. obj = instance_eval "new_#{model_name_as_underscores}(hash)"
  48. obj.save!
  49. obj
  50. end
  51. end
  52. end
  53.  
  54. private
  55.  
  56. def create_hash_from_args(*args)
  57. hash = *args
  58. hash ||= Hash.new
  59. end
  60. end
Add Comment
Please, Sign In to add comment