重构并将控制器代码移动到模型问题中

时间:2015-09-17 20:09:30

标签: ruby-on-rails

因此,当我改进代码时,我遇到了一些我不知道如何解决的问题。

目前在我的控制器#show中,我有这段丑陋的代码:

def show
  @room = Room.find(params[:id])
  if user_signed_in?
    gon.push(
      session_id: @room.session_id,
      api_key: 453,
      token: current_user.tokens.last.token
    )
  elsif customer_signed_in?
    gon.push(
      session_id: @room.session_id,
      api_key: 453,
      token: current_customer.tokens.last.token,
      customer_id: current_customer.id
    )
  elsif @room.price == 0.0
    @token = OT.generate_token @room.session_id
    gon.push(
      session_id: @room.session_id,
      api_key: 453,
      token: @token
    )
  else
    @customer = Customer.new
  end
end

现在我想把它移到房间模型中。我遇到的问题是,如果它是用户,客户或两者都没有,我会有一个if else。我如何将其转变为模型并仍然能够验证这一点?

2 个答案:

答案 0 :(得分:1)

我不明白为什么要将此方法移动到模型中。 (您是在代码中的不同位置使用它吗?还是只是从这个特定的地方使用它?)。

我会将此重构为以下内容:

def show
  @room = Room.find(params[:id])
  gon_args = { session_id: @room.session_id, api_key: 453, token: nil }
  if user_signed_in?
    gon_args.merge!(token: current_user.tokens.last.token)
  elsif customer_signed_in?
    gon_args.merge!(token: current_customer.tokens.last.token, customer_id: current_customer.id)
  elsif @room.price == 0.0
    gon_args.merge!(token: OT.generate_token(@room.session_id))
  else
    @customer = Customer.new
  end
  gon.push(gon_args) unless gon_args[:token].nil?
end

答案 1 :(得分:0)

您始终可以使用PORO (Plain Old Ruby Object)。它不仅可以保持干净,还可以帮助测试您的应用并在代码中保持单一责任。我相信你可以做得比下面好多了,但这只是一个起点。

class YourController
  def show
    @room = Room.find(params[:id])
    # no clue where some stuff comes from
    pusher = RoomPusher.new @room, @token, gon
    pusher.push
  end
end

class RoomPusher
  include YourHelpers
  def initialize(room, token, endpoint)
    @endpoint = endpoint
    @room = room
    @token = token
  end

  def push
    if user_signed_in?
      @endpoint.push(
        session_id: @room.session_id,
        api_key: 453,
        token: current_user.tokens.last.token
      )
    elsif customer_signed_in?
      @endpoint.push(
        session_id: @room.session_id,
        api_key: 453,
        token: current_customer.tokens.last.token,
        customer_id: current_customer.id
      )
    elsif @room.price == 0.0
      @token = OT.generate_token @room.session_id
      @endpoint.push(
        session_id: @room.session_id,
        api_key: 453,
        token: @token
      )
    else
      @customer = Customer.new
    end
  end
end