Hidden instance variables in before_filter method

≡放荡痞女 提交于 2019-12-11 10:12:02

问题


Is it a good practice to hide instance variable initialization in private methods?

For example, I have a user controller with some actions:

class UsersController < ApplicationController
  before_filter :get_user, only: [:show, :edit, :update, :destroy]
  before_filter :set_user, only: [:new, :create]

  def index
    @users = User.all
  end

  def show
  end

  def new
  end

  def edit
  end

  def create
    if @user.save
      redirect_to @user, notice: 'User was successfully created.'
    else
      render action: 'new'
    end
  end

  def update
    if @user.update_attributes(params[:user])
      redirect_to @user, notice: 'User was successfully updated.'
    else
      render action: 'edit'
    end
  end

  def destroy
    @user.destroy
    redirect_to users_path
  end

private

  def get_user
    @user = User.find(params[:id])
  end

  def set_user
    @user = User.new(params[:user])
  end
end

Some people say that it seems like a magic, but it's DRY. What do you think?


回答1:


They're not hidden, they're right there.

Personally, when it comes to DRY, there's a rule I like to follow (I read it somewhere but I don't remember where, forgive me) - the first time you want to duplicate content, you copy and paste it with a frown, but if you want to duplicate it again, that's when you extract it out into one place.

Your :load_user example is fine, but I wouldn't bother with :set_user.




回答2:


This is too DRY for me.

before_filter for routine stuff like instance variable initialization drives me insane because the method appears blank, yet stuff is happening. Not a big deal if the method is otherwise empty, but large methods may obscure the filter, or you might overlook it altogether. You then have to hunt down the filter method and mentally reconstruct the workflow. It makes maintenance more difficult than it needs to be.

I would forego filters and call getter/setter methods in place:

def show
  get_user
end  

That way you can see where initialization is happening. If you insist on using filters, put a comment in the method advising that filters are being applied.

Personally, I reserve before_filter for conditional logic only.



来源:https://stackoverflow.com/questions/14413539/hidden-instance-variables-in-before-filter-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!