iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 25
1
Modern Web

Ruby礦工的Rails地圖系列 第 25

淺談Concern -- 相同的方法要好好收納

整理相同方法到concern裡

如果現在用rails開一個新專案
你會在model與controller裡面發現一個空的資料夾叫做「concerns」
這就是rails預設你會用來放concern的地方

concern簡單說就是可以將model與controller相同的部分抽出
成為一個更高階的方法,避免重複
實踐「DRY」的精神
但一般而言新手可能會更熟悉將controller整理到service或是上層controller
例如說有一段controller如下:

class WebsiteController < ApplicationController
	def index
        @events = Event.all
	end
end

用service整理如下:

#app/services/event_service.rb
class EventService
    def self.source
        Event.all
    end
end

class WebsiteController < ApplicationController
	def index
        @events = EventService.source
        # 將複雜的邏輯藏到service裡面
	end
end

用上層controller整理如下:

#上層的controller
class BaseController < ApplicationController
	def source
        Event.all
	end
end

class WebsiteController < BaseController
	def index
        @events = source
        # 將複雜的邏輯藏到BaseController裡面
	end
end

但如果要整理model,選擇似乎就少了些
這時候concern就是個好選擇

class Company < ApplicationRecord
    scope :open, -> { where(statue: "open")}
    def is_open?
        status == "open"
    end
end
class Event < ApplicationRecord
    scope :open, -> { where(statue: "open")}
    def is_open?
        status == "open"
    end
end

像是上面的例子,可能在專案內會有類似的scope,instance method
可以抽出來:

#app/models/concerns/can_openable.rb
module CanOpenable
  extend ActiveSupport::Concern
  def self.included(base)
    base.send(:include, InstanceMethods)
    base.class_eval do
        scope :open, -> { where(statue: "open")}
    end
  end

  module InstanceMethods
    def is_open?
        status == "open"
    end
  end
end

class Company < ApplicationRecord
    include CanOpenable
end

class Event < ApplicationRecord
    include CanOpenable
end

如此就可以達到整理重複程式碼的效果
參考文件參考文件2
API


上一篇
Pair Programing
下一篇
新年快樂之準備跨年以前的一些Rails命令列提醒
系列文
Ruby礦工的Rails地圖30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
Bater
iT邦新手 4 級 ‧ 2017-01-11 12:08:00

自己開發時,需要參考自己寫的文章XD

我要留言

立即登入留言