51224bdd17878b3b19e8987e9bb336a2

In following Home controller I have written a some validation which could be re factored but I am not getting any hint.
- Home controller don't have any respective (Home) model.So I am getting little bit confused
where should I write those validations.

Thanks in advance
DG

Home controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
 def invite_friends
    user_name =  params['user_name']
    emails =  params['recipient_list']
    @message = params['message']
    
    @error = []
    if user_email.blank? 
     @error << "Please enter your email."
     flag=false
    end    
    
    if user_name.blank?
      @error << "Please enter your name."
      flag=false
    end
    
    if emails.blank?
      @error << "Please enter email addresses of friends." 
      flag=false
    end
    
    if @message.blank?
      @error << "Please enter message." 
      flag=false
    end

    unless emails.blank?
      emails=emails.split(",")
      emails.delete_if {|x| x.blank? }
      if emails.blank?
        @error << "Please enter email addresses of friends." 
        flag=false
      end  
    end
    
        
    if flag
      send_emails(user_email,user_name,emails,@message)
    end
end

Refactorings

No refactoring yet !

1e8f141e7857d397d8020ed3b759e88a

Maciej Piechotka

July 30, 2008, July 30, 2008 11:46, permalink

1 rating. Login to rate!

Do it RESTful. Use fat models. It is very hard to do it in other way in RoR/Merb/... Create invitation model without any DB table associated (i.e. fake model).

Alternativly you can send email in the constructor

app/model/invitation.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Invitation
  include Validatable

  attr_accessor ...

  def initialize(*args)
    ... # Set the parameters
  end

  def save
    if valid?
      send_email # Have to return non-0/non-nil on success
    else
      false
    end
  end
  
  def save!
    save || raise ProperException
  end
end
880cbab435f00197613c9cc2065b4f5a

danielharan

July 30, 2008, July 30, 2008 12:32, permalink

No rating. Login to rate!

It doesn't have to be an ActiveRecord object; you can put any object you want in /app/models/

Google "form validation without activerecord"

Your refactoring





Format Copy from initial code

or Cancel