Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## app/models/comment.rb
- class Comment < ActiveRecord::Base
- def validate
- puts "CNK validating optional attributes"
- ["name", "email", "affiliation"].each do |attr_name|
- if send(attr_name+'_required') and self.send(attr_name).blank?
- errors.add(attr_name, "is required.")
- end
- end
- end
- def method_missing_with_setting_delegation(method, *args)
- puts "CNK looking for method "+method.to_s
- if method.to_s =~ /_required$/
- puts "CNK in method missing about to send to setting"
- # attempt to delegate to setting
- CommentSetting.instance.send(method, *args)
- else
- puts "CNK in method missing using the old one"
- # use old method_missing
- method_missing_without_setting_delegation method, *args
- end
- end
- alias_method_chain :method_missing, :setting_delegation
- end
- ## This code works fine from the browser. If CommentSetting.instance.email_required is 'true', then comment must have an email address in email field.
- ## So for a test, created a factory method that gets included by test_helper.rb
- module Factory
- def self.create_comment(attributes = {})
- default_attributes = {
- :name => 'Someone',
- :email => 'me@example.com',
- :affiliation => 'Undergrad',
- :creation_ip => '131.215.130.46',
- :anonymous => false,
- :body => 'Some basic comment.'
- }
- Comment.create(default_attributes.merge(attributes))
- end
- end
- ##
- require File.dirname(__FILE__) + '/../test_helper'
- class CommentTest < ActiveSupport::TestCase
- def test_factory
- comment = Factory.create_comment
- # assert_not_valid comment
- puts comment.valid?
- puts comment.errors.inspect
- end
- end
- $ ruby test/unit/comment_test.rb
- Loaded suite test/unit/comment_test
- Started
- CNK looking for method name=
- CNK in method missing using the old one
- false
- #<ActiveRecord::Errors:0x9d26668 @base=#<Comment id: nil, name: "Someone", email: "me@example.com", affiliation: "Under\
- grad", creation_ip: "131.215.130.46", anonymous: false, body: "Some basic comment.", approved: false, approved_by: nil,\
- approved_at: nil, updated_by: nil, created_at: nil, updated_at: nil>, @errors={}>
- .
- Finished in 0.431101 seconds.
- 1 tests, 0 assertions, 0 failures, 0 errors
Add Comment
Please, Sign In to add comment