2015-05-14 68 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无需重新构建您的应用程序或采取学习曲线来实现宝石。只需了解如何通过这些资源实现服务对象并破解您的项目。 –