rails自定义库以干燥方式重新编码

时间:2013-06-24 13:52:34

标签: ruby-on-rails dry gibbon

我有这个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 个答案:

答案 0 :(得分: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