Reputation: 1608
So I'm running into some issues that I'm not aware of how to solve when I'm improving my code.
Currently in my controller#show I have this ugly piece of code:
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
now I would like to move this into the rooms model. The issue that I'm having is that I'm having an if else based on if it's a user, customer or neither. How would I go about moving this into a model and still be able to validate this?
Upvotes: 1
Views: 39
Reputation: 791
You could always use a PORO (Plain Old Ruby Object). Not only does it keep stuff clean, it helps a bunch in testing your app and keeping single responsibilities across your code. I'm sure you can do much better than below but this is just a starting point.
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
Upvotes: 0
Reputation: 54882
I don't see why you would like to move this method to the model. (Are you using it from different places in your code? or just from this specific place?).
I would refactor this to the following:
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
Upvotes: 1