Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module ModelFactory
- def valid_user_attributes
- {
- :username => "scott",
- :password => "my-pass",
- :password_confirmation => "my-pass",
- :gender => "male",
- :email_address => "scott@railsnewbie.com",
- :email_address_confirmation => "scott@railsnewbie.com",
- :date_of_birth => Time.mktime('1985', '06', '12'),
- :active => true
- }
- end
- def valid_comments
- {
- :text => "blah blah",
- :post => create_post
- }
- end
- # ...
- end
- ## implementation:
- module ModelFactory; end
- ModelFactory.module_eval do
- instance_methods.each do |method|
- if method =~ /valid_(.*)_attributes/
- model_name_as_underscores = $1
- model_name_as_class = instance_eval($1.classify)
- define_method "new_#{model_name_as_underscores}" do |*args|
- hash = create_hash_from_args(*args)
- model_name_as_class.new(instance_eval("#{method}.merge(hash)"))
- end
- define_method "create_#{model_name_as_underscores}" do |*args|
- hash = create_hash_from_args(*args)
- obj = instance_eval "new_#{model_name_as_underscores}(hash)"
- obj.save!
- obj
- end
- end
- end
- private
- def create_hash_from_args(*args)
- hash = *args
- hash ||= Hash.new
- end
- end
Add Comment
Please, Sign In to add comment