class Customer < CouchRest::Model::Base #FIELDS = [:first_name, :last_name, :phone, :website, :company, :fax, :addresses, :credit_cards, :custom_fields] use_database "customers" belongs_to :user property :braintree_customer_id validates :user, presence: true design do view :by_user_id view :by_braintree_customer_id end def has_payment_info? !!braintree_customer_id end # from braintree_ruby_examples/rails3_tr_devise and should be tweaked =begin def with_braintree_data! return self unless has_payment_info? braintree_data = Braintree::Customer.find(braintree_customer_id) #FIELDS.each do |field| # send(:"#{field}=", braintree_data.send(field)) #end self end =end #slow to get Braintree Customer data, so pass it if have already retrieved it # won't really have multiple credit cards on file # instead of having method, should just be able to call braintree_data.credit_cards.first if just one is allowed def default_credit_card(braintree_data = nil) return unless has_payment_info? braintree_data = braintree_data || Braintree::Customer.find(braintree_customer_id) braintree_data.credit_cards.find { |cc| cc.default? } end # based on 2nd parameter, either returns the single active subscription (or nil if there isn't one), or an array of all subsciptions def subscriptions(braintree_data=nil, only_active=true) return unless has_payment_info? braintree_data = braintree_data || Braintree::Customer.find(braintree_customer_id) subscriptions = [] braintree_data.credit_cards.first.subscriptions.each do |sub| if only_active and sub.status == 'Active' return sub else subscriptions << sub end end only_active ? nil : subscriptions end end