2016-11-01 41 views
5

Bir çok uygulamada önceden denetime sahip bir denetleyici üzerinde çalışıyorum. Çoğu, ayarladıkları örnek değişkenlerle birbirleriyle bağlanır. Örneğin:Birden çok before_action hatalı kod stili mi çağırıyor?

def first_action 
    @first_variable = Something.new 
end 

def second_action 
    if @first_variable 
    @second_variable = Other.new 
    end 
end 

Kontrolör şuna benzer:

class ExampleController < ApplicationController 
    before_action :first_action, only: [:index, :show, :create] 
    before_action :second_action, only: [:index, :show, :create] 
    before_action :third_action, only: [:index, :show, :create] 
    before_action :fourth_action, only: [:index, :show, :create] 
    before_action :fifth_action, only: [:index, :show, :create] 
    before_action :sixth_action, only: [:index, :show, :create] 
    before_action :seventh_action, only: [:index, :show, :create] 

    def index 
    # some code 
    end 

    def show 
    # some code 
    end 

    def create 
    # some code 
    end 

    private 

    # all of the before_action methods 
end 

Bu bakış maden açıdan anlamak gerçekten zor. Bu yöntemlerin her birinin çok sayıda kodu vardır. Ek olarak, bunlardan miras alan kontrolörler de vardır ve bu eylemlerin bir kısmını veya tamamını kullanırlar.

class ExampleController < ApplicationController 

    def index 
    first_action 
    second_action 
    third_action 
    fourth_action 
    fifth_action 
    sixth_action 
    seventh_action 
    # some code 
    end 

    def show 
    first_action 
    second_action 
    third_action 
    fourth_action 
    fifth_action 
    sixth_action 
    seventh_action 
    # some code 
    end 

    def create 
    first_action 
    second_action 
    third_action 
    fourth_action 
    fifth_action 
    sixth_action 
    seventh_action 
    # some code 
    end 

    private 

    # all of the before_action methods 
end 

çok daha iyi görünmüyor:

Hiç dolu her yöntemde değişkenler ancak bu konuda açık olmak daha iyi olduğunu duydum. Daha fazla okunabilirlik için yeniden düzenlemek için bir yol var mı yoksa mevcut çözüm ile yapışmalı mıyım?

+0

Birden çok 'before_actions' seçeneğine sahip olmakta yanlış bir şey yok - ama daha çok tek bir eylemde toplanabilecekleri bir durumunuz var gibi görünüyor? – Matt

+0

Fikrinizle gittim @Matt Teşekkürler ve eğer bir cevap olarak eklerseniz, benim sorunumun bir çözümü olarak kontrol edebilirim :) – zeth

+0

Bitti, yardımcı olduğunu duyduğuma sevindim! – Matt

cevap

1

gibi kullanabilir?

8

Geçerli çözümünüz doğru değil. ama onlar bir eyleme toplanan edilebilecek bir durum var daha benziyor - Sen Orada hiçbir şey birden before_actions sahip yanlış

before_action :first_action, :second_action, :third_action, :fourth_action, :fifth_action, :sixth_action, :seventh_action, only: [:index, :show, :create]