Skip to content

Instantly share code, notes, and snippets.

@antonfefilov
Last active August 29, 2015 14:07
Show Gist options
  • Save antonfefilov/e7d9543b3e535ee08888 to your computer and use it in GitHub Desktop.
Save antonfefilov/e7d9543b3e535ee08888 to your computer and use it in GitHub Desktop.
Refactored long method
ActiveAdmin.register SchedulingConstraint, as: 'Capacity' do
menu priority: 7, label: 'Ride Later Capacity'
config.sort_order = 'starting_at_asc,ending_at_asc'
NO_CONFLICT = -1
CONFLICT = -2
collection_action :capacities, method: :get do
respond_to do |format|
format.json { render json: events }
end
end
index do
column :id
column :starting_at
column :ending_at
column :ride_later_capacity
default_actions
render 'admin/capacities'
end
form do |f|
f.inputs do
f.semantic_errors
f.input :starting_at, as: :just_datetime_picker_am_pm
f.input :ending_at, as: :just_datetime_picker_am_pm
f.input :ride_later_capacity
f.buttons
end
end
end
def events
events = Array.new
capacities.each do |e|
events << build_new_event(e)
end
events
end
def capacities
# Select all capacities to display past ones.
capacities_attrs = SchedulingConstraint.all.map { |c| OpenStruct.new(c.attributes) }
(Date.today .. 30.days.from_now.to_date).each do |day|
capacities_attrs << OpenStruct.new(SchedulingConstraint.default_for_date(day).attributes)
capacities_attrs << OpenStruct.new(id: build_id(day), ride_later_capacity: -1, starting_at: day.to_time )
end
capacities_attrs
end
def build_id(day)
scheduler = RideScheduler.new
scheduler.check_date_schedulability(day) ? NO_CONFLICT : CONFLICT
end
def build_new_event(e)
color = e.starting_at.to_date < Date.today ? 'grey' : 'blue'
return nil_event(e, color) if e.id.nil?
return no_conflict_event(e) if e.id == NO_CONFLICT
return conflict_event(e) if e.id == CONFLICT
normal_event(e, color)
end
def nil_event(e, color)
{
id: nil,
title: "capacity: #{e.ride_later_capacity}\n[default]",
start: e.starting_at,
end: e.ending_at,
color: color,
editable: false,
allDay: false
}
end
def no_conflict_event(e)
{
id: nil,
title: "OK",
start: e.starting_at,
color: 'green',
editable: false,
allDay: true
}
end
def conflict_event(e)
{
id: nil,
title: "CONFLICT",
start: e.starting_at,
color: 'red',
editable: false,
allDay: true
}
end
def normal_event(e, color)
{
id: e.id,
title: "capacity: #{e.ride_later_capacity}\nid: #{e.id}",
start: e.starting_at,
end: e.ending_at,
color: color,
editable: false,
allDay: false
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment