# coding: utf-8 require 'sinatra/base' require 'haml' require 'chartkick' require 'recorder/db' require 'recorder/data' module Recorder class Application < Sinatra::Base use Rack::MethodOverride set :haml, escape_html: true enable :prefixed_redirects configure do DB.prepare end configure :development do require 'sinatra/reloader' register Sinatra::Reloader end get '/' do redirect 'chart' end get '/data' do @data = Data.order('created_at DESC') haml :index end get '/data/new' do @data = Data.new haml :new end get '/data/:id/edit' do @data = Data.find(params[:id]) haml :edit end put '/data/:id' do begin data = Data.find(params[:id]) data.update_attributes!( weight: params[:weight], bodyfat: params[:bodyfat], date: params[:date], memo: params[:memo] ) redirect '/' rescue ActiveRecord::RecordInvalid => e @data = e.record haml :edit end end post '/data' do begin date0 = Time.now.strftime('%Y/%m/%d %H:%M') Data.create!(weight: params[:weight], bodyfat: params[:bodyfat], date: date0, memo: params[:memo] ) redirect '/' rescue ActiveRecord::RecordInvalid => e @data = e.record haml :new end end delete '/data/:id' do data = Data.find(params[:id]) data.destroy redirect '/' end get '/chart' do @weight_options = {min: 84, max: 90} @bodyfat_options = {min: 15, max: 30} @weight_data,@bodyfat_data = get_data() haml :chart end get '/chart_week' do @weight_options = {min: 84, max: 90} @bodyfat_options = {min: 15, max: 30} @weight_data,@bodyfat_data = get_data(:week) haml :chart end get '/chart_month' do @weight_options = {min: 84, max: 90} @bodyfat_options = {min: 15, max: 30} @weight_data,@bodyfat_data = get_data(:month) haml :chart end require 'date' require 'time' def get_data(period=:all) @data = Data.order('created_at DESC') weight_data,bodyfat_data=[],[] today = Date.today week_before=Time.parse((today-7).strftime) month_before=Time.parse((today-28).strftime) @data.each{|d| case period when :all when :week next if d.date < week_before when :month next if d.date < month_before end weight_data << [d.date,d.weight] bodyfat_data << [d.date,d.bodyfat] } return weight_data,bodyfat_data end end end