2015-05-14 41 views
0

我想按照正確的OOP協議將一些滑軌業務邏輯轉移到服務中。我遵循以下推薦的方法:Private module methods in RubyRuby - 將滑軌的「業務邏輯」移動到服務模塊中

最終,我想將業務邏輯從模型和控制器轉移到服務中,這些服務是簡單的舊Ruby對象。因此,模型將只關注持久性,範圍界定,驗證。

這是製作服務模塊的正確方法嗎?

版本2:

module CategorizeJobs 

    def self.fetch(location, category_name) 
    c = Categorizer.new(location, category_name) 
    c.get_jobs 
    end 

    class Categorizer 

    def initialize(location, category_name) 
     @location = location 
     @category_name = category_name 
    end 

    def get_jobs 
     job_ids = get_correct_jobs 
     Category.includes(:jobs).where(jobs: { id: job_ids }) 
    end 

    private 

     def get_correct_jobs 
     jobs = filter_by_location 
     jobs = filter_by_category(jobs) 

     jobs.collect(&:id) 
     end 

     def filter_by_category(jobs) 
     return jobs unless @category_name.present? 

     category = Category.where(name: @category_name).first 
     if category 
      jobs = jobs.where(category: category) 
     end 

     jobs 
     end 

     def filter_by_location 
     if @location.present? 
      jobs = get_jobs_at_location 
     else 
      jobs = Job.open 
     end 
     end 

     def get_jobs_at_location(location) 
     Job.joins(:location).within(20, origin: @location).open 
     end 

    end 

end 

版本1:

module CategorizeJobs 

    def self.fetch(location, category_name) 
    c = Categorizer.new 
    c.perform(location, category_name) 
    end 


    class Categorizer 

    def perform(location, category_name) 
     job_ids = get_correct_jobs(location, category_name) 
     Category.includes(:jobs).where(jobs: { id: job_ids }) 
    end 

    private 

     def get_correct_jobs(location, category_name) 
     jobs = filter_by_location(location) 
     jobs = filter_by_category(jobs, category_name) 

     jobs.collect(&:id) 
     end 

     def filter_by_category(jobs, category_name) 
     return jobs unless category_name 

     category = Category.where(name: category_name).first 
     if category 
      jobs = jobs.where(category: category) 
     end 

     jobs 
     end 

     def filter_by_location(location) 
     if location 
      jobs = get_jobs_at_location(location) 
     else 
      jobs = Job.open 
     end 
     end 

     def get_jobs_at_location(location) 
     Job.joins(:location).within(20, origin: location).open 
     end 

    end 

end 
+1

你在問什麼? –

+0

哎呀 - 意外刪除它! 「這是製作服務模塊的正確方法嗎?」 –

+0

你總是傳遞位置和類別名稱。爲什麼不創建一個初始化器並將它們存儲在變量中,所以你不需要傳遞它們呢? –

回答

3

有一個寶石由Aldous的名稱,可以幫助您實現服務對象的基礎架構到您的Rails應用程序。看看它。

如果您需要關於如何使用它並構建您的應用程序的進一步幫助,您可以查看thisthis獲取更多幫助。

+0

謝謝!有一個通讀 - 好主意。我不認爲我想完全重新構建我的應用程序,我不知道這將如何與我正在使用的其他寶石一起工作 - 而且我將不得不培訓任何我帶到Aldous項目中的開發人員 –

+0

@WillTaylor無需重新構建您的應用程序或採取學習曲線來實現寶石。只需瞭解如何通過這些資源實現服務對象並破解您的項目。 –