Advertisement
Guest User

Untitled

a guest
Sep 21st, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rails 1.88 KB | None | 0 0
  1. class CustomersController < ApplicationController
  2.   define_model :customer, :redirect_on_save => proc { edit_customer_path @customer },
  3.          :before_save => :save_contacts,
  4.          :after_save => proc{  @customer.save_actual_term }
  5.  
  6.   after_filter :fetch_customers, :only => [:list, :print]
  7.   before_filter :find_customer, :only => [:set_approve, :approve]
  8.   around_filter ScopedAccess::Filter.new(Customer, :scoped_by_filter)
  9.  
  10.  def approve
  11.     if @customer.can_be_approved?
  12.       @customer.credit_limit = params[:credit_limit]
  13.       @customer.approve!
  14.       flash[:notice] = "Customer has been approved."
  15.     else
  16.       flash[:warning] = "The selected customer cannot be approved!"
  17.     end
  18.     redirect_to customer_path(@customer)
  19.   end
  20.  
  21.   def list
  22.     @customers = Customer.find(:all, :order => 'name')
  23.     session[:last_list_filter] = uri_encode(params[:filter] || {})
  24.   end
  25.  
  26.   def print
  27.     @customers = Customer.find(:all, :order => 'name')
  28.     @landscape = false
  29.     @paper = 'letter'
  30.     render :layout => false
  31.   end
  32.  
  33.  
  34.   protected
  35.    
  36.     def fetch_customers
  37.       @customers = Customer.find(:all, :order => 'name')
  38.     end
  39.    
  40.     # before save
  41.     def save_contacts
  42.       return if params[:contact].blank?
  43.       fields, values = [*params[:contact]].transpose
  44.       contacts = values.transpose.reject { |vals| vals[0].blank? }.collect do |vals|
  45.         attributes = fields.zip(vals).inject({}) { |h, p| h.merge(p[0] => p[1]) }
  46.         Contact.new attributes
  47.       end
  48.       @customer.contacts = contacts
  49.     end
  50.    
  51.     def find_customer
  52.       @customer = Customer.find(params[:id])
  53.     end
  54. end
  55.  
  56.  
  57. class Hash
  58.   def to_attribute_array
  59.     fields, values = [*self].transpose
  60.     values.transpose.reject { |vals| vals.all?(&:blank?) }.collect do |vals|
  61.       fields.zip(vals).inject({}) { |h, p| h.merge(p[0] => p[1]) }
  62.     end
  63.   end
  64. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement