Reputation: 1499
I have a Rails model called Projects:
class Project < ActiveRecord::Base
that has a variety of toggle switches, such as active, started, paid, etc.
I then have a method to return the status in human readable format:
def status
return 'Pending' if self.pending?
return 'Started' if self.started
return 'In Review' if self.in_review?
return 'Approved' if self.approved
return 'Active' if self.active
end
Right now I have another method called status!
that returns the same information but in symbol form, which is inefficient in my mind:
def status
return :pending if self.pending?
return :started if self.started
return :awarded if self.awarded
return :in_review if self.in_review?
return :approved if self.approved
return :active if self.active
end
What I would obviously like to do is something more like status.to_sym
but can't figure out how to make that happen.
Any thoughts?
Upvotes: 0
Views: 80
Reputation: 24815
At first I highly double these methods are efficient.
These methods are to define a certain status at a workflow. In common sense they are mutually exclusive. That is, a project "in pending" could not be a project "active", or "in review", or any other status in this group.
Based on above, why don't you set all of these status as an Enum attribute "status" in this model? This attribute value could be any one within "pending, active, started..." By this you use one field to replace 5 fields.
Then it's easy to get the status in human readable format directly in view, even without a controller method.
<strong>Status: </strong><%= @project.status.titleize %>
Upvotes: 0
Reputation: 4880
How about this:
def status
return 'Pending' if self.pending?
return 'Started' if self.started
return 'In Review' if self.in_review?
return 'Approved' if self.approved
return 'Active' if self.active
end
def status!
# added gsub otherwise 'In Review' is returned as ':in review'
status.gsub(/\s+/, "_").downcase.to_sym
# status.parameterize.underscore.to_sym <- another option, Rails only
end
Upvotes: 1