ruby - How would you refactor this "complex method" for codeclimate? -
i'm trying figure out how refactor code based on codeclimate telling me, far seems method longer 5 lines or has if statement "complex". in instance im trying create event calendar based off of meeting record, here event model:
class event < activerecord::base validates :title, :eventcolor_id, presence: true belongs_to :meeting belongs_to :eventcolor def self.create_from_meeting(meeting, eventcolor) meeting.meeting_date_end ||= meeting.meeting_date_start event.find_or_initialize_by(meeting_id: meeting.id) |e| e.title = meeting.title e.datetime_start = time.zone.local_to_utc(meeting.meeting_date_start) e.datetime_end = time.zone.local_to_utc(meeting.meeting_date_end) e.location = meeting.location e.address1 = meeting.address1 e.address2 = meeting.address2 e.city = meeting.city e.state = meeting.state e.zip = meeting.zip e.description = (!meeting.description.blank?) ? meeting.description : '' e.eventcolor_id = eventcolor e.save e.committees << meeting.committee if !meeting.committee.nil? end end end
which called meetings_controller line:
event.create_from_meeting(meeting, params[:eventcolors_select])
why need duplicate meeting
attributes in event
? have belongs_to
relationship here, there doesn't seem need such duplication. yes, loading meeting
along event
involve join
type query, bet performance benefit duplicating data close zero.
instead suggest doing this:
class event < activerecord::base validates :eventcolor_id, presence: true belongs_to :meeting belongs_to :eventcolor # if need access these attributes on event directly delegate :title, :location, :etc, to: :meeting, prefix: false # note: improved further, don't know # committees association, have left def self.create_from_meeting(meeting, eventcolor) event.find_or_initialize_by(meeting_id: meeting.id) |e| e.eventcolor_id = eventcolor e.save e.committees << meeting.committee if !meeting.committee.nil? end end # items require manipulation, create custom methods # these pretty cheap manipulations, can cache them if def datetime_start @datetime_start ||= time.zone.local_to_utc(meeting.meeting_date_start) end def description meeting.description || '' end end
ar cache meeting object on event first time loaded. if worried performance cost, , if going accessing meeting-based attributes every request, set (on event
):
default_scope { includes(:meeting) }
Comments
Post a Comment