Guest User

Untitled

a guest
May 27th, 2018
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. ## app/models/comment.rb
  2. class Comment < ActiveRecord::Base
  3.  
  4. def validate
  5. puts "CNK validating optional attributes"
  6. ["name", "email", "affiliation"].each do |attr_name|
  7. if send(attr_name+'_required') and self.send(attr_name).blank?
  8. errors.add(attr_name, "is required.")
  9. end
  10. end
  11. end
  12.  
  13. def method_missing_with_setting_delegation(method, *args)
  14. puts "CNK looking for method "+method.to_s
  15. if method.to_s =~ /_required$/
  16. puts "CNK in method missing about to send to setting"
  17. # attempt to delegate to setting
  18. CommentSetting.instance.send(method, *args)
  19. else
  20. puts "CNK in method missing using the old one"
  21. # use old method_missing
  22. method_missing_without_setting_delegation method, *args
  23. end
  24. end
  25.  
  26. alias_method_chain :method_missing, :setting_delegation
  27.  
  28. end
  29.  
  30. ## This code works fine from the browser. If CommentSetting.instance.email_required is 'true', then comment must have an email address in email field.
  31.  
  32. ## So for a test, created a factory method that gets included by test_helper.rb
  33. module Factory
  34. def self.create_comment(attributes = {})
  35. default_attributes = {
  36. :name => 'Someone',
  37. :email => 'me@example.com',
  38. :affiliation => 'Undergrad',
  39. :creation_ip => '131.215.130.46',
  40. :anonymous => false,
  41. :body => 'Some basic comment.'
  42. }
  43. Comment.create(default_attributes.merge(attributes))
  44. end
  45.  
  46. end
  47.  
  48. ##
  49. require File.dirname(__FILE__) + '/../test_helper'
  50.  
  51. class CommentTest < ActiveSupport::TestCase
  52. def test_factory
  53. comment = Factory.create_comment
  54. # assert_not_valid comment
  55. puts comment.valid?
  56. puts comment.errors.inspect
  57. end
  58.  
  59. end
  60.  
  61. $ ruby test/unit/comment_test.rb
  62. Loaded suite test/unit/comment_test
  63. Started
  64. CNK looking for method name=
  65. CNK in method missing using the old one
  66. false
  67. #<ActiveRecord::Errors:0x9d26668 @base=#<Comment id: nil, name: "Someone", email: "me@example.com", affiliation: "Under\
  68. grad", creation_ip: "131.215.130.46", anonymous: false, body: "Some basic comment.", approved: false, approved_by: nil,\
  69. approved_at: nil, updated_by: nil, created_at: nil, updated_at: nil>, @errors={}>
  70. .
  71. Finished in 0.431101 seconds.
  72.  
  73. 1 tests, 0 assertions, 0 failures, 0 errors
Add Comment
Please, Sign In to add comment