2013-06-24 60 views
0

我有這個mailchimp.rb文件,但我認爲它效率不高。用乾燥的方式導軌自定義庫重新編碼

class MailchimpAdapter 
    class << self 


    def remove_from_mailchimp_list(user, bucket_id) 
     connection = Gibbon.new 
     lists = connection.lists 
     begin 
     connection.list_unsubscribe({:id => lists["data"][user_type_id]["id"], :email_address => user.email, :delete_member => true, :send_goodbye => false, :send_notify => false}) 
     rescue Exception => ex 
     end 
    end 

    def add_to_mailchimp_list(user, bucket_id) 
     connection = Gibbon.new 
     lists = connection.lists 
     begin 
     connection.list_subscribe({:id => lists["data"][user_type_id]["id"], :email_address => user.email, :merge_vars => {:FNAME => user.user_name, :LNAME => ""}, :double_optin => false}) 
     rescue Exception => ex 
     end 
    end 

    end 
end 

有沒有更好的方法來編寫這個類?因爲我重複這部分

connection = Gibbon.new 
lists = connection.lists 

回答

1

我會做這樣的事情:

class MailchimpAdapter 
    class << self 

    def remove_from_mailchimp_list(user, bucket_id) 
     list_operation do |connection, lists| 
     connection.list_unsubscribe({:id => lists["data"][user_type_id]["id"], :email_address => user.email, :delete_member => true, :send_goodbye => false, :send_notify => false}) 
     end 
    end 

    def add_to_mailchimp_list(user, bucket_id) 
     list_operation do |connection, lists| 
     connection.list_subscribe({:id => lists["data"][user_type_id]["id"], :email_address => user.email, :merge_vars => {:FNAME => user.user_name, :LNAME => ""}, :double_optin => false}) 
     end 
    end 

    private 

    def list_operation 
     connection = Gibbon.new 
     lists = connection.lists 
     begin 
     yield(connection, lists) 
     rescue Exception => ex 
     end 
    end 

    end 
end