repo
string
commit
string
message
string
diff
string
ThomasPedersen/mattespill
0b7a5c95e7e22d5d8bf23e01a707de3a6c369c7f
Hard tabs 4 lyfe
diff --git a/main/forms.py b/main/forms.py index f498879..90551c4 100644 --- a/main/forms.py +++ b/main/forms.py @@ -1,34 +1,34 @@ from django.contrib.auth.models import User from django import forms class SignupForm(forms.Form): - Brukernavn = forms.CharField(max_length=30) - Epost = forms.EmailField(); - Passord = forms.CharField(max_length=30, - widget=forms.PasswordInput(render_value=False)) - Bekreft_Passord = forms.CharField(max_length=30, - widget=forms.PasswordInput(render_value=False)) - Fornavn = forms.CharField(max_length=30) - Etternavn = forms.CharField(max_length=30) - - def clean_username(self): - try: - User.objects.get(username=self.cleaned_data['Brukernavn']) - except User.DoesNotExist: - return self.cleaned_data['Brukernavn'] - raise forms.ValidationError("Dette brukernavnet er allerede tatt.") - - def clean(self): - if 'Passord' in self.changed_data and 'Bekreft_Passord' in self.changed_data: - if self.cleaned_data['Passord'] != self.cleaned_data['Bekreft_Passord']: - raise forms.ValidationError("Passordene er ikke like") - return self.cleaned_data - - def save(self): - new_user = User.objects.create_user(username=self.cleaned_data['Brukernavn'], - email=self.cleaned_data['Epost'], - password=self.cleaned_data['Passord']) - new_user.first_name = self.cleaned_data['Fornavn'] - new_user.last_name = self.cleaned_data['Etternavn'] - new_user.save() - return new_user + Brukernavn = forms.CharField(max_length=30) + Epost = forms.EmailField(); + Passord = forms.CharField(max_length=30, + widget=forms.PasswordInput(render_value=False)) + Bekreft_Passord = forms.CharField(max_length=30, + widget=forms.PasswordInput(render_value=False)) + Fornavn = forms.CharField(max_length=30) + Etternavn = forms.CharField(max_length=30) + + def clean_username(self): + try: + User.objects.get(username=self.cleaned_data['Brukernavn']) + except User.DoesNotExist: + return self.cleaned_data['Brukernavn'] + raise forms.ValidationError("Dette brukernavnet er allerede tatt.") + + def clean(self): + if 'Passord' in self.changed_data and 'Bekreft_Passord' in self.changed_data: + if self.cleaned_data['Passord'] != self.cleaned_data['Bekreft_Passord']: + raise forms.ValidationError("Passordene er ikke like") + return self.cleaned_data + + def save(self): + new_user = User.objects.create_user(username=self.cleaned_data['Brukernavn'], + email=self.cleaned_data['Epost'], + password=self.cleaned_data['Passord']) + new_user.first_name = self.cleaned_data['Fornavn'] + new_user.last_name = self.cleaned_data['Etternavn'] + new_user.save() + return new_user diff --git a/main/views.py b/main/views.py index 2e00151..f0dec52 100644 --- a/main/views.py +++ b/main/views.py @@ -1,170 +1,170 @@ # -*- coding: utf-8 -*- from django.template import RequestContext, Context, loader from django.utils import simplejson from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden from django.shortcuts import render_to_response, get_object_or_404 from django.contrib import auth from django.contrib.auth.decorators import login_required from django.core import serializers from datetime import datetime from mattespill.main.models import Question, Room, Turn, Result, UserProfile, Hint from mattespill.main.forms import SignupForm import json login_url = '/login/' def index(request): if request.user.is_authenticated(): rooms = Room.objects.all() return render_to_response('home.html', {'user': request.user, 'home': True, \ 'rooms': rooms}) else: return HttpResponseRedirect(login_url) def room(request, room_id): if request.user.is_authenticated(): sess_room_id = request.session.get('room_id', None) if not sess_room_id or sess_room_id != room_id: room = get_object_or_404(Room, pk=room_id) else: room = get_object_or_404(Room, pk=sess_room_id) # If user does not have enough points to access room, # we redirect to index if request.user.get_profile().points < room.required_points: return HttpResponseRedirect('/') request.session['room_id'] = room_id turn_exists = False try: t = Turn.objects.get(room=room, user=request.user, complete=False) turn_exists = True except Turn.DoesNotExist: t = Turn(date_start=datetime.now(), date_end=None, user=request.user, room=room) t.save() # Fetch 10 random questions for the given room questions = Question.objects.filter(room=room).order_by('?')[:10] # Add Result objects (question and answer pairs) for each question i = 1 # Sequence number for each question for q in questions: result = Result(question=q, turn=t, index=i) result.save() i += 1 previous_turns = Turn.objects.filter(room=room, user=request.user, complete=True).\ order_by('-date_start').order_by('-total_points').all() return render_to_response('room.html', {'turn_exists': turn_exists, 'turn': t, \ 'user': request.user, 'previous_turns': previous_turns}) else: return HttpResponseRedirect(login_url) def logout(request): auth.logout(request) return HttpResponseRedirect('/') def buyhint(request): if request.user.is_authenticated(): # Get a random hint room_id = request.session.get('room_id', None) if room_id: hint = Hint.objects.filter(room=room_id).order_by('?')[:1] # Check if user has enough points profile = request.user.get_profile() cost = hint[0].cost if profile.points - cost < 1: return HttpResponse(json.dumps({'points': profile.points, \ 'hint': None}), mimetype='application/json') else: profile.points -= cost profile.save() # Return json response return HttpResponse(json.dumps({'points': profile.points, 'hint': hint[0].text}), \ mimetype='application/json') else: return HttpResponseForbidden() def stats(request): - if request.user.is_authenticated(): - # Get max 10 users ordered by points desc - users = UserProfile.objects.order_by('-points')[:10] - return render_to_response('stats.html', {'user': request.user, 'users': users}) - else: - return HttpResponseRedirect(login_url) + if request.user.is_authenticated(): + # Get max 10 users ordered by points desc + users = UserProfile.objects.order_by('-points')[:10] + return render_to_response('stats.html', {'user': request.user, 'users': users}) + else: + return HttpResponseRedirect(login_url) def question(request): if request.user.is_authenticated(): room_id = request.session.get('room_id', None) if room_id: try: turn = Turn.objects.get(room=room_id, user=request.user, complete=False) except Turn.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) try: # The Meta.ordering defined in model will sort # the result ascending on Result.index result = Result.objects.filter(turn=turn, answer='')[:1] if not result: return render_to_response('room.html', {'turn': turn, 'user': request.user}) num_questions = Result.objects.filter(turn=turn).count() return render_to_response('question.html', {'user': request.user,'turn': turn, 'result': result[0], \ 'num_questions': num_questions, 'room_id': room_id}) except Result.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) else: return HttpResponseRedirect(login_url) def answer(request): if request.user.is_authenticated() and request.method == 'POST': room_id = request.session.get('room_id', None) if room_id and 'answer' in request.POST: given_answer = request.POST['answer'].strip() user = request.user t = get_object_or_404(Turn, room=room_id, user=user, complete=False) count = Result.objects.filter(turn=t).count() result = Result.objects.filter(turn=t, answer='')[0] try: if result.index < count: index = result.index + 1 question = Result.objects.get(turn=t, index=index).question.question else: index = -1 # No more questions question = None t.complete = True t.save() correct = given_answer == result.question.real_answer if correct: # Give user some points user.get_profile().points += result.question.points t.total_points += result.question.points else: # For wrong answer users lose (question points / 2) penalty = result.question.points / 2 user.get_profile().points -= penalty t.total_points -= penalty t.save() user.get_profile().save() result.answer = given_answer result.save() return HttpResponse(json.dumps({'correct': correct, 'index': index, \ 'question': question, 'points': user.get_profile().points}), \ mimetype='application/json') except Result.DoesNotExist as e: return HttpResponse(e) else: return HttpResponseRedirect(login_url) def signup(request): if request.method == 'POST': form = SignupForm(data=request.POST) if form.is_valid(): form.save(); return HttpResponseRedirect('/') else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request)) else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request))
ThomasPedersen/mattespill
b4dd9496e9805127aad040267e72aa2172282014
hook test
diff --git a/main/media/home.js b/main/media/home.js index c3122f3..8fbc63a 100644 --- a/main/media/home.js +++ b/main/media/home.js @@ -1,7 +1,7 @@ $(function() { $('.restricted_room_msg').parent().hover(function() { - $(this).find('.restricted_room_msg').fadeIn(300); + $(this).find('.restricted_room_msg').fadeIn(100); }, function() { $(this).find('.restricted_room_msg').fadeOut(300); }); }); \ No newline at end of file
ThomasPedersen/mattespill
0531cfa852d4cfa76582f8f5957d400624876dfa
Added some tests for room view.
diff --git a/main/tests.py b/main/tests.py index c9a9793..0cb6bb8 100644 --- a/main/tests.py +++ b/main/tests.py @@ -1,20 +1,44 @@ from django.test import TestCase from django.test.client import Client +from main.models import Turn class ViewsTest(TestCase): + def test_login(self): + response = self.client.post('/login/', {'username': 'foo', 'password': 'foo'}) + self.assertEqual(response.status_code, 302) + response = self.client.post('/login/', {'username': 'invaliduser', 'password': \ + 'invalidpassword'}) + self.assertEqual(response.status_code, 200) + def test_index(self): # Should redirect if we're not logged in response = self.client.get('/') - self.failUnlessEqual(response.status_code, 302) + self.assertEqual(response.status_code, 302) # Log in - response = self.client.post('/login/', {'username': 'testuser', 'password': 'testuser'}) - self.failUnlessEqual(response.status_code, 302) # Redirects on success + self.client.login(username='foo', password='foo') # Get index response = self.client.get('/') - self.failUnlessEqual(response.status_code, 200) + self.assertEqual(response.status_code, 200) - def test_login(self): - response = self.client.post('/login/', {'username': 'testuser', 'password': 'testuser'}) - self.failUnlessEqual(response.status_code, 302) + def test_room(self): + # No auth should result in redirect + response = self.client.get('/room/1/') + self.assertEqual(response.status_code, 302) + # Log in + self.client.login(username='foo', password='foo') + # User foo does not have enough points to access this room + response = self.client.get('/room/2/') + self.assertEqual(response.status_code, 302) + # ..should be enough for this room though + response = self.client.get('/room/1/') + self.assertEqual(response.status_code, 200) + # Session should now contain the room id + session = self.client.session + self.assertEqual(session['room_id'], '1') + # Check if a turn was created + turns = Turn.objects.filter(user=1) + self.assertEqual(turns.count(), 1) + # Check if turn contains atleast one Result object + self.assertTrue(turns[0].result_set.count() > 1)
ThomasPedersen/mattespill
020192b98a4eabcd37dcb22107ce456a5b8ff202
Added some basic tests for index and login.
diff --git a/main/tests.py b/main/tests.py index f9983c3..c9a9793 100644 --- a/main/tests.py +++ b/main/tests.py @@ -1,23 +1,20 @@ -""" -This file demonstrates two different styles of tests (one doctest and one -unittest). These will both pass when you run "manage.py test". - -Replace these with more appropriate tests for your application. -""" - from django.test import TestCase +from django.test.client import Client -class SimpleTest(TestCase): - def test_basic_addition(self): - """ - Tests that 1 + 1 always equals 2. - """ - self.failUnlessEqual(1 + 1, 2) +class ViewsTest(TestCase): -__test__ = {"doctest": """ -Another way to test that 1 + 1 is equal to 2. + def test_index(self): + # Should redirect if we're not logged in + response = self.client.get('/') + self.failUnlessEqual(response.status_code, 302) + # Log in + response = self.client.post('/login/', {'username': 'testuser', 'password': 'testuser'}) + self.failUnlessEqual(response.status_code, 302) # Redirects on success + # Get index + response = self.client.get('/') + self.failUnlessEqual(response.status_code, 200) ->>> 1 + 1 == 2 -True -"""} + def test_login(self): + response = self.client.post('/login/', {'username': 'testuser', 'password': 'testuser'}) + self.failUnlessEqual(response.status_code, 302)
ThomasPedersen/mattespill
3f9488a89ce91005cd824a125fd4e62992eec552
Order questions by difficulty (points).
diff --git a/main/views.py b/main/views.py index 2e00151..8384343 100644 --- a/main/views.py +++ b/main/views.py @@ -1,170 +1,170 @@ # -*- coding: utf-8 -*- from django.template import RequestContext, Context, loader from django.utils import simplejson from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden from django.shortcuts import render_to_response, get_object_or_404 from django.contrib import auth from django.contrib.auth.decorators import login_required from django.core import serializers from datetime import datetime from mattespill.main.models import Question, Room, Turn, Result, UserProfile, Hint from mattespill.main.forms import SignupForm import json login_url = '/login/' def index(request): if request.user.is_authenticated(): rooms = Room.objects.all() return render_to_response('home.html', {'user': request.user, 'home': True, \ 'rooms': rooms}) else: return HttpResponseRedirect(login_url) def room(request, room_id): if request.user.is_authenticated(): sess_room_id = request.session.get('room_id', None) if not sess_room_id or sess_room_id != room_id: room = get_object_or_404(Room, pk=room_id) else: room = get_object_or_404(Room, pk=sess_room_id) # If user does not have enough points to access room, # we redirect to index if request.user.get_profile().points < room.required_points: return HttpResponseRedirect('/') request.session['room_id'] = room_id turn_exists = False try: t = Turn.objects.get(room=room, user=request.user, complete=False) turn_exists = True except Turn.DoesNotExist: t = Turn(date_start=datetime.now(), date_end=None, user=request.user, room=room) t.save() - # Fetch 10 random questions for the given room - questions = Question.objects.filter(room=room).order_by('?')[:10] + # Fetch 10 random questions for the given room (sorted by points/difficulty) + questions = Question.objects.filter(room=room).order_by('?').order_by('points')[:10] # Add Result objects (question and answer pairs) for each question i = 1 # Sequence number for each question for q in questions: result = Result(question=q, turn=t, index=i) result.save() i += 1 previous_turns = Turn.objects.filter(room=room, user=request.user, complete=True).\ order_by('-date_start').order_by('-total_points').all() return render_to_response('room.html', {'turn_exists': turn_exists, 'turn': t, \ 'user': request.user, 'previous_turns': previous_turns}) else: return HttpResponseRedirect(login_url) def logout(request): auth.logout(request) return HttpResponseRedirect('/') def buyhint(request): if request.user.is_authenticated(): # Get a random hint room_id = request.session.get('room_id', None) if room_id: hint = Hint.objects.filter(room=room_id).order_by('?')[:1] # Check if user has enough points profile = request.user.get_profile() cost = hint[0].cost if profile.points - cost < 1: return HttpResponse(json.dumps({'points': profile.points, \ 'hint': None}), mimetype='application/json') else: profile.points -= cost profile.save() # Return json response return HttpResponse(json.dumps({'points': profile.points, 'hint': hint[0].text}), \ mimetype='application/json') else: return HttpResponseForbidden() def stats(request): if request.user.is_authenticated(): # Get max 10 users ordered by points desc users = UserProfile.objects.order_by('-points')[:10] return render_to_response('stats.html', {'user': request.user, 'users': users}) else: return HttpResponseRedirect(login_url) def question(request): if request.user.is_authenticated(): room_id = request.session.get('room_id', None) if room_id: try: turn = Turn.objects.get(room=room_id, user=request.user, complete=False) except Turn.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) try: # The Meta.ordering defined in model will sort # the result ascending on Result.index result = Result.objects.filter(turn=turn, answer='')[:1] if not result: return render_to_response('room.html', {'turn': turn, 'user': request.user}) num_questions = Result.objects.filter(turn=turn).count() return render_to_response('question.html', {'user': request.user,'turn': turn, 'result': result[0], \ 'num_questions': num_questions, 'room_id': room_id}) except Result.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) else: return HttpResponseRedirect(login_url) def answer(request): if request.user.is_authenticated() and request.method == 'POST': room_id = request.session.get('room_id', None) if room_id and 'answer' in request.POST: given_answer = request.POST['answer'].strip() user = request.user t = get_object_or_404(Turn, room=room_id, user=user, complete=False) count = Result.objects.filter(turn=t).count() result = Result.objects.filter(turn=t, answer='')[0] try: if result.index < count: index = result.index + 1 question = Result.objects.get(turn=t, index=index).question.question else: index = -1 # No more questions question = None t.complete = True t.save() correct = given_answer == result.question.real_answer if correct: # Give user some points user.get_profile().points += result.question.points t.total_points += result.question.points else: # For wrong answer users lose (question points / 2) penalty = result.question.points / 2 user.get_profile().points -= penalty t.total_points -= penalty t.save() user.get_profile().save() result.answer = given_answer result.save() return HttpResponse(json.dumps({'correct': correct, 'index': index, \ 'question': question, 'points': user.get_profile().points}), \ mimetype='application/json') except Result.DoesNotExist as e: return HttpResponse(e) else: return HttpResponseRedirect(login_url) def signup(request): if request.method == 'POST': form = SignupForm(data=request.POST) if form.is_valid(): form.save(); return HttpResponseRedirect('/') else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request)) else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request))
ThomasPedersen/mattespill
7cb2486d306164d32e25a9d8993141ef3318f5e4
Added errorface image.
diff --git a/main/media/images/errorface.gif b/main/media/images/errorface.gif new file mode 100644 index 0000000..7da4e2a Binary files /dev/null and b/main/media/images/errorface.gif differ
ThomasPedersen/mattespill
87492a2c69a6b14f5ed15a241a008aa600b0fef6
fixed a pedobear bug
diff --git a/main/media/question.js b/main/media/question.js index 7b41671..8884795 100644 --- a/main/media/question.js +++ b/main/media/question.js @@ -1,99 +1,101 @@ var bearTimer; function showBear() { $('#hintbear').css('cursor', 'pointer').click(function() { $.ajax({ type: 'POST', url: '/buyhint/', dataType: 'json', - success: function(data, textStatus) { + complete: function() { $('#hintbear').unbind('click').css('cursor', 'auto'); + }, + success: function(data, textStatus) { $('#num_points').text(data.points); if (data.hint == null) { $('#hintbear .dialogbox').text('Du har nok for lite penger!'); setTimeout(stopBear, 2000); } else $('#hintbear .dialogbox').text(data.hint); }, error: function(XMLHttpRequest, textStatus) { alert('Det oppstod en feil'); } }); }); $('#hintbear .dialogbox').html('Har du lyst p&aring; hjelp?<br />Klikk p&aring; meg!'); $('#hintbear').show().animate({ opacity: 1, marginRight: '0em' }, 1000, function() { $('#hintbear .dialogbox').fadeIn(500); }); } function startBear() { bearTimer = setTimeout(showBear, 5000); } function stopBear() { if (bearTimer != null) clearTimeout(bearTimer); $('#hintbear').animate({ opacity: 0, marginRight: '-7em' }, 400, $('#hintbear').hide); } $(function() { $('.start_button').click(function() { - stopBear(); - if ($.trim($('input[name=answer]').val()) == '') { alert('Du må skrive inn noe!'); $('input[name=answer]').val(''); return; } + stopBear(); + $.ajax({ type: 'POST', url: '/answer/', dataType: 'json', data: {answer: $('input[name=answer]').val()}, success: function(data, textStatus) { $('#num_points').text(data.points); if (data.correct) { $('#wrong_answer').hide(); $('#correct_answer').fadeIn(); } else { $('#correct_answer').hide(); $('#wrong_answer').fadeIn(); } if (data.index < 0) { $('#question_wrapper').remove(); $('#finished_wrapper').show(); } else { $('input[name=answer]').val('').focus(); $('#question_index').text(data.index); $('#question_text').text(data.question); startBear(); } }, error: function(XMLHttpRequest, textStatus) { alert('Det oppstod en feil'); } }); }); $('#answer_form').submit(function() { $('.simple_button').click(); return false; }); $('input[name=answer]').focus(); startBear(); }); \ No newline at end of file
ThomasPedersen/mattespill
dfd0198d84abbc66b455100ca8f0a929094d8525
moar bear fix
diff --git a/main/media/question.js b/main/media/question.js index b84317b..7b41671 100644 --- a/main/media/question.js +++ b/main/media/question.js @@ -1,97 +1,99 @@ var bearTimer; function showBear() { $('#hintbear').css('cursor', 'pointer').click(function() { $.ajax({ type: 'POST', url: '/buyhint/', dataType: 'json', success: function(data, textStatus) { $('#hintbear').unbind('click').css('cursor', 'auto'); $('#num_points').text(data.points); - if (data.hint == null) + if (data.hint == null) { $('#hintbear .dialogbox').text('Du har nok for lite penger!'); + setTimeout(stopBear, 2000); + } else $('#hintbear .dialogbox').text(data.hint); }, error: function(XMLHttpRequest, textStatus) { alert('Det oppstod en feil'); } }); }); $('#hintbear .dialogbox').html('Har du lyst p&aring; hjelp?<br />Klikk p&aring; meg!'); $('#hintbear').show().animate({ opacity: 1, marginRight: '0em' }, 1000, function() { $('#hintbear .dialogbox').fadeIn(500); }); } function startBear() { bearTimer = setTimeout(showBear, 5000); } function stopBear() { if (bearTimer != null) clearTimeout(bearTimer); $('#hintbear').animate({ opacity: 0, marginRight: '-7em' }, 400, $('#hintbear').hide); } $(function() { $('.start_button').click(function() { stopBear(); if ($.trim($('input[name=answer]').val()) == '') { alert('Du må skrive inn noe!'); $('input[name=answer]').val(''); return; } $.ajax({ type: 'POST', url: '/answer/', dataType: 'json', data: {answer: $('input[name=answer]').val()}, success: function(data, textStatus) { $('#num_points').text(data.points); if (data.correct) { $('#wrong_answer').hide(); $('#correct_answer').fadeIn(); } else { $('#correct_answer').hide(); $('#wrong_answer').fadeIn(); } if (data.index < 0) { $('#question_wrapper').remove(); $('#finished_wrapper').show(); } else { $('input[name=answer]').val('').focus(); $('#question_index').text(data.index); $('#question_text').text(data.question); startBear(); } }, error: function(XMLHttpRequest, textStatus) { alert('Det oppstod en feil'); } }); }); $('#answer_form').submit(function() { $('.simple_button').click(); return false; }); $('input[name=answer]').focus(); startBear(); }); \ No newline at end of file
ThomasPedersen/mattespill
0d1866ea87ad81b830da4ef6bd389111107d680c
moar bear fix
diff --git a/main/media/question.js b/main/media/question.js index 9f90f2d..b84317b 100644 --- a/main/media/question.js +++ b/main/media/question.js @@ -1,100 +1,97 @@ var bearTimer; function showBear() { $('#hintbear').css('cursor', 'pointer').click(function() { $.ajax({ type: 'POST', url: '/buyhint/', dataType: 'json', success: function(data, textStatus) { $('#hintbear').unbind('click').css('cursor', 'auto'); + $('#num_points').text(data.points); - if (data.hint == null) { + if (data.hint == null) + $('#hintbear .dialogbox').text('Du har nok for lite penger!'); + else $('#hintbear .dialogbox').text(data.hint); - return; - } - - $('#hintbear .dialogbox').text(data.hint); - - $('#num_points').text(data.points); }, error: function(XMLHttpRequest, textStatus) { alert('Det oppstod en feil'); } }); }); $('#hintbear .dialogbox').html('Har du lyst p&aring; hjelp?<br />Klikk p&aring; meg!'); $('#hintbear').show().animate({ opacity: 1, marginRight: '0em' }, 1000, function() { $('#hintbear .dialogbox').fadeIn(500); }); } function startBear() { bearTimer = setTimeout(showBear, 5000); } function stopBear() { if (bearTimer != null) clearTimeout(bearTimer); $('#hintbear').animate({ opacity: 0, marginRight: '-7em' }, 400, $('#hintbear').hide); } $(function() { $('.start_button').click(function() { stopBear(); if ($.trim($('input[name=answer]').val()) == '') { alert('Du må skrive inn noe!'); $('input[name=answer]').val(''); return; } $.ajax({ type: 'POST', url: '/answer/', dataType: 'json', data: {answer: $('input[name=answer]').val()}, success: function(data, textStatus) { $('#num_points').text(data.points); if (data.correct) { $('#wrong_answer').hide(); $('#correct_answer').fadeIn(); } else { $('#correct_answer').hide(); $('#wrong_answer').fadeIn(); } if (data.index < 0) { $('#question_wrapper').remove(); $('#finished_wrapper').show(); } else { $('input[name=answer]').val('').focus(); $('#question_index').text(data.index); $('#question_text').text(data.question); startBear(); } }, error: function(XMLHttpRequest, textStatus) { alert('Det oppstod en feil'); } }); }); $('#answer_form').submit(function() { $('.simple_button').click(); return false; }); $('input[name=answer]').focus(); startBear(); }); \ No newline at end of file
ThomasPedersen/mattespill
ac912febb81413aeb1bfbda0f673a31c076cf4b7
bear 2 fix
diff --git a/main/media/peekbear.js b/main/media/peekbear.js index 46d9ac4..d5bdcd8 100644 --- a/main/media/peekbear.js +++ b/main/media/peekbear.js @@ -1,57 +1,57 @@ var peekbearImages = ['peekbearbottom.png', 'peekbearright.png', 'peekbearleft.png']; function showPeekbear() { var i = Math.floor(Math.random()*(peekbearImages.length)); var element = $('<img src="/media/images/' + peekbearImages[i] + '" alt="Tittei" />'). css('position', 'fixed'); var bearSize = '3em'; switch (i) { case 0: element.css('height', bearSize).css('bottom', '-' + bearSize). css('left', Math.floor(5 + Math.random()*(80-5)) + '%').animate({ bottom: '0em' }, 2000, function() { $(this).animate({ bottom: '-' + bearSize }, 300, function() { - $('body').remove(this); + $(this).remove(); }); }); break; case 1: element.css('width', bearSize).css('right', '-' + bearSize). css('bottom', Math.floor(5 + Math.random()*(80-5)) + '%').animate({ right: '0em' }, 2000, function() { $(this).animate({ right: '-' + bearSize }, 300, function() { - $('body').remove(this); + $(this).remove(); }); }); break; case 2: element.css('width', bearSize).css('left', '-' + bearSize). css('bottom', Math.floor(5 + Math.random()*(80-5)) + '%').animate({ left: '0em' }, 2000, function() { $(this).animate({ left: '-' + bearSize }, 300, function() { - $('body').remove(this); + $(this).remove(); }); }); break; default: return; } $('body').append(element); } $(function() { setInterval(showPeekbear, 7000); showPeekbear(); }); diff --git a/main/media/question.js b/main/media/question.js index aaa9558..9f90f2d 100644 --- a/main/media/question.js +++ b/main/media/question.js @@ -1,92 +1,100 @@ var bearTimer; function showBear() { - $('#hintbear').html('Har du lyst p&aring; hjelp?<br />Klikk p&aring; meg!').show().animate({ + $('#hintbear').css('cursor', 'pointer').click(function() { + $.ajax({ + type: 'POST', + url: '/buyhint/', + dataType: 'json', + success: function(data, textStatus) { + $('#hintbear').unbind('click').css('cursor', 'auto'); + + if (data.hint == null) { + $('#hintbear .dialogbox').text(data.hint); + return; + } + + $('#hintbear .dialogbox').text(data.hint); + + $('#num_points').text(data.points); + }, + error: function(XMLHttpRequest, textStatus) { + alert('Det oppstod en feil'); + } + }); + }); + + $('#hintbear .dialogbox').html('Har du lyst p&aring; hjelp?<br />Klikk p&aring; meg!'); + $('#hintbear').show().animate({ opacity: 1, - marginRight: '0em', + marginRight: '0em' }, 1000, function() { $('#hintbear .dialogbox').fadeIn(500); }); } function startBear() { bearTimer = setTimeout(showBear, 5000); } function stopBear() { if (bearTimer != null) clearTimeout(bearTimer); $('#hintbear').animate({ opacity: 0, marginRight: '-7em' - }, 1000, $('#hintbear').hide); + }, 400, $('#hintbear').hide); } $(function() { $('.start_button').click(function() { stopBear(); if ($.trim($('input[name=answer]').val()) == '') { alert('Du må skrive inn noe!'); $('input[name=answer]').val(''); return; } - startBear(); - $.ajax({ type: 'POST', url: '/answer/', dataType: 'json', data: {answer: $('input[name=answer]').val()}, success: function(data, textStatus) { $('#num_points').text(data.points); if (data.correct) { $('#wrong_answer').hide(); $('#correct_answer').fadeIn(); } else { $('#correct_answer').hide(); $('#wrong_answer').fadeIn(); } if (data.index < 0) { $('#question_wrapper').remove(); $('#finished_wrapper').show(); } else { $('input[name=answer]').val('').focus(); $('#question_index').text(data.index); $('#question_text').text(data.question); + + startBear(); } }, error: function(XMLHttpRequest, textStatus) { alert('Det oppstod en feil'); } }); }); $('#answer_form').submit(function() { $('.simple_button').click(); return false; }); - $('#hintbear').click(function() { - $.ajax({ - type: 'POST', - url: '/buyhint/', - dataType: 'json', - success: function(data, textStatus) { - $('#hintbear .dialogbox').text(data.hint); - $('#num_points').text(data.points); - $('#hintbear').unbind('click').css('cursor', 'auto'); - }, - error: function(XMLHttpRequest, textStatus) { - alert('Det oppstod en feil'); - } - }); - }); - $('input[name=answer]').focus(); startBear(); }); \ No newline at end of file
ThomasPedersen/mattespill
fd2e7bf41720a32233878dd272dc969a6082227f
bear normal speed
diff --git a/main/media/peekbear.js b/main/media/peekbear.js index 28139f1..46d9ac4 100644 --- a/main/media/peekbear.js +++ b/main/media/peekbear.js @@ -1,57 +1,57 @@ var peekbearImages = ['peekbearbottom.png', 'peekbearright.png', 'peekbearleft.png']; function showPeekbear() { var i = Math.floor(Math.random()*(peekbearImages.length)); var element = $('<img src="/media/images/' + peekbearImages[i] + '" alt="Tittei" />'). css('position', 'fixed'); var bearSize = '3em'; switch (i) { case 0: element.css('height', bearSize).css('bottom', '-' + bearSize). css('left', Math.floor(5 + Math.random()*(80-5)) + '%').animate({ bottom: '0em' }, 2000, function() { $(this).animate({ bottom: '-' + bearSize }, 300, function() { $('body').remove(this); }); }); break; case 1: element.css('width', bearSize).css('right', '-' + bearSize). css('bottom', Math.floor(5 + Math.random()*(80-5)) + '%').animate({ right: '0em' }, 2000, function() { $(this).animate({ right: '-' + bearSize }, 300, function() { $('body').remove(this); }); }); break; case 2: element.css('width', bearSize).css('left', '-' + bearSize). css('bottom', Math.floor(5 + Math.random()*(80-5)) + '%').animate({ left: '0em' }, 2000, function() { $(this).animate({ left: '-' + bearSize }, 300, function() { $('body').remove(this); }); }); break; default: return; } $('body').append(element); } $(function() { - setInterval(showPeekbear, 100); + setInterval(showPeekbear, 7000); showPeekbear(); });
ThomasPedersen/mattespill
b2a594ff6fc61b6b20420f760f078d2507b058e7
bear at home
diff --git a/main/media/peekbear.js b/main/media/peekbear.js index 46d9ac4..28139f1 100644 --- a/main/media/peekbear.js +++ b/main/media/peekbear.js @@ -1,57 +1,57 @@ var peekbearImages = ['peekbearbottom.png', 'peekbearright.png', 'peekbearleft.png']; function showPeekbear() { var i = Math.floor(Math.random()*(peekbearImages.length)); var element = $('<img src="/media/images/' + peekbearImages[i] + '" alt="Tittei" />'). css('position', 'fixed'); var bearSize = '3em'; switch (i) { case 0: element.css('height', bearSize).css('bottom', '-' + bearSize). css('left', Math.floor(5 + Math.random()*(80-5)) + '%').animate({ bottom: '0em' }, 2000, function() { $(this).animate({ bottom: '-' + bearSize }, 300, function() { $('body').remove(this); }); }); break; case 1: element.css('width', bearSize).css('right', '-' + bearSize). css('bottom', Math.floor(5 + Math.random()*(80-5)) + '%').animate({ right: '0em' }, 2000, function() { $(this).animate({ right: '-' + bearSize }, 300, function() { $('body').remove(this); }); }); break; case 2: element.css('width', bearSize).css('left', '-' + bearSize). css('bottom', Math.floor(5 + Math.random()*(80-5)) + '%').animate({ left: '0em' }, 2000, function() { $(this).animate({ left: '-' + bearSize }, 300, function() { $('body').remove(this); }); }); break; default: return; } $('body').append(element); } $(function() { - setInterval(showPeekbear, 7000); + setInterval(showPeekbear, 100); showPeekbear(); });
ThomasPedersen/mattespill
14badba7a8a7ccbcfddacd45e4945b344d2c97b5
bear at home
diff --git a/main/media/peekbear.js b/main/media/peekbear.js index d5995df..46d9ac4 100644 --- a/main/media/peekbear.js +++ b/main/media/peekbear.js @@ -1,57 +1,57 @@ var peekbearImages = ['peekbearbottom.png', 'peekbearright.png', 'peekbearleft.png']; function showPeekbear() { var i = Math.floor(Math.random()*(peekbearImages.length)); var element = $('<img src="/media/images/' + peekbearImages[i] + '" alt="Tittei" />'). css('position', 'fixed'); var bearSize = '3em'; switch (i) { case 0: element.css('height', bearSize).css('bottom', '-' + bearSize). css('left', Math.floor(5 + Math.random()*(80-5)) + '%').animate({ bottom: '0em' }, 2000, function() { $(this).animate({ bottom: '-' + bearSize }, 300, function() { $('body').remove(this); }); }); break; case 1: element.css('width', bearSize).css('right', '-' + bearSize). css('bottom', Math.floor(5 + Math.random()*(80-5)) + '%').animate({ right: '0em' }, 2000, function() { $(this).animate({ right: '-' + bearSize }, 300, function() { $('body').remove(this); }); }); break; case 2: element.css('width', bearSize).css('left', '-' + bearSize). css('bottom', Math.floor(5 + Math.random()*(80-5)) + '%').animate({ left: '0em' }, 2000, function() { $(this).animate({ left: '-' + bearSize }, 300, function() { $('body').remove(this); }); }); break; default: return; } $('body').append(element); } $(function() { - setInterval(showPeekbear, 3000); + setInterval(showPeekbear, 7000); showPeekbear(); }); diff --git a/main/templates/home.html b/main/templates/home.html index 9ea61ae..6994f8f 100644 --- a/main/templates/home.html +++ b/main/templates/home.html @@ -1,124 +1,126 @@ {% extends "outer.html" %} {% block head %} <script src="/media/home.js" type="text/javascript"></script> +<script src="/media/peekbear.js" type="text/javascript"></script> + <style type="text/css"> #right_content { /*background-color: #eaeaea; border: .3em solid #ddd;*/ padding: 1em 2em; text-align: center; float: right; } #left_content { padding: .5em 0em; } img#treasure_chest { width: 10em; } #room_box_container a:hover { text-decoration: none; } #room_box_container { width: 27em; height: 27em; } #room_box_container p { color: #fff; text-decoration: none; } #addition_box { background-color: #76ce76; border: .5em solid #60a860; } #subtraction_box { background-color: #dddd51; border: .5em solid #c2c247; float: right; } #multiplication_box { margin-top: 1em; background-color: #eca657; border: .5em solid #c28847; } #division_box { margin-top: 1em; background-color: #ec5757; border: .5em solid #c94a4a; float: right; } .room_box { -moz-border-radius: 1.5em; -webkit-border-radius: 1.5em; border-radius: 1.5em; width: 12em; height: 12em; position: relative; } .restricted_room_msg { position: absolute; bottom: 0; left: 0; right: 0; text-align: center; padding: .4em; color: #fff; -text-shadow: #fff 0 0 1px; background: rgba(0, 0, 0, 0.2); display: none; -moz-border-radius: 1em; -webkit-border-radius: 1em; border-radius: 1em; } .restricted_room_msg > div { opacity: 1; } .room_sign { /*margin-top: -.1em;*/ text-align: center; font-weight: bold; font-size: 10em; color: #fff; } .room_sign a { color: inherit; text-decoration: none; } /* http://robertnyman.com/2010/01/11/css-background-transparency-without-affecting-child-elements-through-rgba-and-filters/ */ </style> {% endblock %} {% block content %} <div id="right_content"> <p class="chest_header">Skattekiste</p> <img id="treasure_chest" src="/media/images/treasurechest.png" alt="skattekiste" /> <p class="gold_coins">Du har <span class="gold_text"> {{ user.get_profile.points }} </span> gullmynter</p> <p><a href="/stats/">Vis liste over de beste spillerne</a></p> </div> <div id="left_content"> <h1>Velg ditt rom</h1> <div id="room_box_container"> <div id="subtraction_box" class="room_box"> {% if user.get_profile.points < rooms.1.required_points %}<div class="restricted_room_msg"><div><b>Krav:<br />{{ rooms.1.required_points}} gullmynter!</b></div></div>{% endif %} <div class="room_sign">{% if user.get_profile.points >= rooms.1.required_points %}<a href="/room/2/">{% endif %}&minus;{% if user.get_profile.points >= rooms.1.required_points %}</a>{% endif %}</div> </div></a> <div id="addition_box" class="room_box"> {% if user.get_profile.points < rooms.0.required_points %}<div class="restricted_room_msg"><div><b>Krav:<br />{{ rooms.0.required_points }} gullmynter!</b></div></div>{% endif %} <div class="room_sign">{% if user.get_profile.points >= rooms.0.required_points %}<a href="/room/1/">{% endif %}+{% if user.get_profile.points >= rooms.0.required_points %}</a>{% endif %}</div> </div></a> <div id="division_box" class="room_box"> {% if user.get_profile.points < rooms.3.required_points %}<div class="restricted_room_msg"><div><b>Krav:<br />{{ rooms.3.required_points }} gullmynter!</b></div></div>{% endif %} <div class="room_sign">{% if user.get_profile.points >= rooms.3.required_points %}<a href="/room/4/">{% endif %}&divide;{% if user.get_profile.points >= rooms.3.required_points %}</a>{% endif %}</div> </div></a> <div id="multiplication_box" class="room_box"> {% if user.get_profile.points < rooms.2.required_points %}<div class="restricted_room_msg"><div><b>Krav:<br />{{ rooms.2.required_points }} gullmynter!</b></div></div>{% endif %} <div class="room_sign">{% if user.get_profile.points >= rooms.2.required_points %}<a href="/room/3/">{% endif %}&times;{% if user.get_profile.points >= rooms.2.required_points %}</a>{% endif %}</div> </div></a> </div> </div> <p id="logout_reminder">Husk &aring; <a href="/logout">avslutte spillet</a> n&aring;r du er ferdig!</p> {% endblock %}
ThomasPedersen/mattespill
11aba6235df983e5df93ebb02bf7b85f90ca13dd
pnghelvete
diff --git a/main/media/peekbear.js b/main/media/peekbear.js index ce72e87..d5995df 100644 --- a/main/media/peekbear.js +++ b/main/media/peekbear.js @@ -1,53 +1,57 @@ var peekbearImages = ['peekbearbottom.png', 'peekbearright.png', 'peekbearleft.png']; function showPeekbear() { - var i = Math.floor(Math.random()*(peekbearImages.length+1)); + var i = Math.floor(Math.random()*(peekbearImages.length)); var element = $('<img src="/media/images/' + peekbearImages[i] + '" alt="Tittei" />'). css('position', 'fixed'); + var bearSize = '3em'; + switch (i) { case 0: - element.css('height', '5em').css('bottom', '-5em'). + element.css('height', bearSize).css('bottom', '-' + bearSize). css('left', Math.floor(5 + Math.random()*(80-5)) + '%').animate({ bottom: '0em' }, 2000, function() { $(this).animate({ - bottom: '-5em' + bottom: '-' + bearSize }, 300, function() { $('body').remove(this); }); }); break; case 1: - element.css('width', '5em').css('right', '-5em'). - css('top', Math.floor(5 + Math.random()*(80-5)) + '%').animate({ + element.css('width', bearSize).css('right', '-' + bearSize). + css('bottom', Math.floor(5 + Math.random()*(80-5)) + '%').animate({ right: '0em' }, 2000, function() { $(this).animate({ - right: '-5em' + right: '-' + bearSize }, 300, function() { $('body').remove(this); }); }); break; case 2: - element.css('width', '5em').css('left', '-5em'). - css('top', Math.floor(5 + Math.random()*(80-5)) + '%').animate({ + element.css('width', bearSize).css('left', '-' + bearSize). + css('bottom', Math.floor(5 + Math.random()*(80-5)) + '%').animate({ left: '0em' }, 2000, function() { $(this).animate({ - left: '-5em' + left: '-' + bearSize }, 300, function() { $('body').remove(this); }); }); break; + default: + return; } $('body').append(element); } $(function() { setInterval(showPeekbear, 3000); showPeekbear(); });
ThomasPedersen/mattespill
05aaf028779bc75864f4132f31d0d25b7e88a21d
pnghelvete
diff --git a/main/media/peekbear.js b/main/media/peekbear.js new file mode 100644 index 0000000..ce72e87 --- /dev/null +++ b/main/media/peekbear.js @@ -0,0 +1,53 @@ +var peekbearImages = ['peekbearbottom.png', 'peekbearright.png', 'peekbearleft.png']; + +function showPeekbear() { + var i = Math.floor(Math.random()*(peekbearImages.length+1)); + var element = $('<img src="/media/images/' + peekbearImages[i] + '" alt="Tittei" />'). + css('position', 'fixed'); + + switch (i) { + case 0: + element.css('height', '5em').css('bottom', '-5em'). + css('left', Math.floor(5 + Math.random()*(80-5)) + '%').animate({ + bottom: '0em' + }, 2000, function() { + $(this).animate({ + bottom: '-5em' + }, 300, function() { + $('body').remove(this); + }); + }); + break; + case 1: + element.css('width', '5em').css('right', '-5em'). + css('top', Math.floor(5 + Math.random()*(80-5)) + '%').animate({ + right: '0em' + }, 2000, function() { + $(this).animate({ + right: '-5em' + }, 300, function() { + $('body').remove(this); + }); + }); + break; + case 2: + element.css('width', '5em').css('left', '-5em'). + css('top', Math.floor(5 + Math.random()*(80-5)) + '%').animate({ + left: '0em' + }, 2000, function() { + $(this).animate({ + left: '-5em' + }, 300, function() { + $('body').remove(this); + }); + }); + break; + } + + $('body').append(element); +} + +$(function() { + setInterval(showPeekbear, 3000); + showPeekbear(); +}); diff --git a/main/templates/registration/login.html b/main/templates/registration/login.html index 5581e6d..22a9f71 100644 --- a/main/templates/registration/login.html +++ b/main/templates/registration/login.html @@ -1,24 +1,29 @@ {% extends "outer.html" %} + +{% block head %} +<script src="/media/peekbear.js" type="text/javascript"></script> +{% endblock %} + {% block content %} {% if user.username %} <h1>Allerede logget inn</h1> <p>Trykk <a href="/">her</a> for å gå til mattespillet.</p> {% else %} <h1>Logg inn</h1> <form action="{% url django.contrib.auth.views.login %}" method="post"> {% csrf_token %} <table> <tr> <td>Brukernavn:</td> <td><input type="text" name="username" /></td> </tr> <tr> <td>Passord:</td> <td><input type="password" name="password" /></td> </tr> </table> <input type="submit" value="Logg inn" /> </form> {% endif %} {% endblock %}
ThomasPedersen/mattespill
e4da85936083e285c982ff4f33618fcecf8db741
Added the peekbear so he can pop up from every angel. Awesomeness is awesome.
diff --git a/main/media/hintbearhead.png b/main/media/images/peekbearbottom.png similarity index 100% rename from main/media/hintbearhead.png rename to main/media/images/peekbearbottom.png diff --git a/main/media/images/peekbearleft.png b/main/media/images/peekbearleft.png new file mode 100644 index 0000000..3dff8e6 Binary files /dev/null and b/main/media/images/peekbearleft.png differ diff --git a/main/media/images/peekbearright.png b/main/media/images/peekbearright.png new file mode 100644 index 0000000..c726109 Binary files /dev/null and b/main/media/images/peekbearright.png differ diff --git a/main/media/images/peekbeartop.png b/main/media/images/peekbeartop.png new file mode 100644 index 0000000..50ac1fc Binary files /dev/null and b/main/media/images/peekbeartop.png differ
ThomasPedersen/mattespill
94cfb3c360839acdf9a046a4b965a5ff3100cf7b
Added the favicon to outer.html
diff --git a/main/templates/outer.html b/main/templates/outer.html index cd08431..8af1e7d 100644 --- a/main/templates/outer.html +++ b/main/templates/outer.html @@ -1,82 +1,83 @@ <!DOCTYPE html> <html lang="no"> <head> <meta charset="utf-8" /> <title>Mattespill</title> + <link href="/media/favicon.ico" rel="icon" type="image/x-icon"> <link rel="stylesheet" href="/media/main.css" type="text/css" /> <!-- http://graphicmaniacs.com/note/cross-browser-border-radius-solution-with-example/ --> <!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]--> <!--[if lte IE 7]><script src="js/IE8.js" type="text/javascript"></script><![endif]--> <!--[if lt IE 7]><link rel="stylesheet" type="text/css" media="all" href="css/ie6.css"/><![endif]--> <script src="/media/jquery-1.4.2.min.js" type="text/javascript"></script> <script src="/media/main.js" type="text/javascript"></script> <style type="text/css"> #header { {% if turn.room.id == 1 %} background-color: #76ce76; border-bottom: .15em solid #60A860; {% else %} {% if turn.room.id == 2 %} background-color: #dddd51; border-bottom: .15em solid #C2C247; {% else %} {% if turn.room.id == 3 %} background-color: #eca657; border-bottom: .15em solid #C28847; {% else %} {% if turn.room.id == 4 %} background-color: #ec5757; border-bottom: .15em solid #C94A4A; {% else %} background-color: #627AAD; border-bottom: .15em solid #1D4088; {% endif %} {% endif %} {% endif %} {% endif %} } #page_content { {% if turn.room.id == 1 %} border: .5em solid #60A860; {% else %} {% if turn.room.id == 2 %} border: .5em solid #C2C247; {% else %} {% if turn.room.id == 3 %} border: .5em solid #C28847; {% else %} {% if turn.room.id == 4 %} border: .5em solid #C94A4A; {% else %} border: .5em solid #1D4088; {% endif %}{% endif %}{% endif %}{% endif %} border-top: none; } </style> {% block head %}{% endblock %} </head> <body> <div id="wrapper"> <div id="header"> <table id="headertable"> <tr> {% if user.is_authenticated %} <td>{{ user.first_name }} {{ user.last_name }} ({{ user.username }}) {% for g in user.get_profile.groups %} - {{ g.name }} {% endfor %} </td> <td class="align_center">Gullmynter: <span id="num_points">{{ user.get_profile.points }}</span></td> <td class="align_right"><a href="/logout">Avslutt spillet</a></td> {% else %} <td class="align_center">Logg inn for å spille mattespillet.</td> {% endif %} </tr> </table> </div> <div id="page_content"> {% block content %}{% endblock %} </div> </div> </body> </html>
ThomasPedersen/mattespill
812bfaeddc79591ec68139de472f85c5237b5336
Added favicon and peakbear in true hintbear style\!
diff --git a/main/media/favicon.ico b/main/media/favicon.ico new file mode 100644 index 0000000..b96d48f Binary files /dev/null and b/main/media/favicon.ico differ diff --git a/main/media/hintbearhead.png b/main/media/hintbearhead.png new file mode 100644 index 0000000..4830372 Binary files /dev/null and b/main/media/hintbearhead.png differ diff --git a/main/templates/signup.html b/main/templates/signup.html index 2ba84e1..0e63baa 100644 --- a/main/templates/signup.html +++ b/main/templates/signup.html @@ -1,13 +1,13 @@ {% extends "outer.html" %} {% block content %} {% if user.username %} <h1>Allerede logget inn</h1> <p>Trykk <a href="/">her</a> for Ã¥ gÃ¥ til mattespillet.</p> {% else %} <h1>Registrer bruker</h1> <form action="/signup/" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> {% endif %} -{% endblock %} \ No newline at end of file +{% endblock %} diff --git a/modelviz.8.py b/modelviz.8.py new file mode 100644 index 0000000..76d14f6 --- /dev/null +++ b/modelviz.8.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python +"""Django model to DOT (Graphviz) converter +by Antonio Cavedoni <[email protected]> + +Make sure your DJANGO_SETTINGS_MODULE is set to your project or +place this script in the same directory of the project and call +the script like this: + +$ python modelviz.py [-h] [-d] [-i <model_names>] [-e <model_names>] <app_label> ... <app_label> > <filename>.dot +$ dot <filename>.dot -Tpng -o <filename>.png + +options: + -h, --help + show this help message and exit. + + -d, --disable_fields + don't show the class member fields. + + -i, --include_models=User,Person,Car + only include selected models in graph. + + -e, --exclude_models=User,Person,Car + only include selected models in graph. +""" +__version__ = "0.8" +__svnid__ = "$Id$" +__license__ = "Python" +__author__ = "Antonio Cavedoni <http://cavedoni.com/>" +__contributors__ = [ + "Stefano J. Attardi <http://attardi.org/>", + "limodou <http://www.donews.net/limodou/>", + "Carlo C8E Miron", + "Andre Campos <[email protected]>", + "Justin Findlay <[email protected]>", + "Alexander Houben <[email protected]>", + "Christopher Schmidt <[email protected]>", + "Dane Springmeyer <[email protected]>" + ] + +import getopt, sys + +from django.core.management import setup_environ + +try: + import settings +except ImportError: + pass +else: + setup_environ(settings) + +from django.template import Template, Context +from django.db import models +from django.db.models import get_models +from django.db.models.fields.related import \ + ForeignKey, OneToOneField, ManyToManyField + +from django.contrib.gis.db.models.fields import GeometryField + +try: + from django.db.models.fields.generic import GenericRelation +except ImportError: + from django.contrib.contenttypes.generic import GenericRelation + +head_template = """ +digraph name { + fontname = "Helvetica" + fontsize = 8 + + node [ + fontname = "Helvetica" + fontsize = 8 + shape = "plaintext" + ] + edge [ + fontname = "Helvetica" + fontsize = 8 + ] + +""" + +body_template = """ + {% for model in models %} + {% for relation in model.relations %} + {{ relation.target }} [label=< + <TABLE BGCOLOR="palegoldenrod" BORDER="0" CELLBORDER="0" CELLSPACING="0"> + <TR><TD COLSPAN="2" CELLPADDING="4" ALIGN="CENTER" BGCOLOR="olivedrab4" + ><FONT FACE="Helvetica Bold" COLOR="white" + >{{ relation.target }}</FONT></TD></TR> + </TABLE> + >] + {{ model.name }} -> {{ relation.target }} + [label="{{ relation.name }}"] {{ relation.arrows }}; + {% endfor %} + {% endfor %} + + {% for model in models %} + {{ model.name }} [label=< + <TABLE BGCOLOR="palegoldenrod" BORDER="0" CELLBORDER="0" CELLSPACING="0"> + <TR><TD COLSPAN="2" CELLPADDING="4" ALIGN="CENTER" BGCOLOR="olivedrab4" + ><FONT FACE="Helvetica Bold" COLOR="white" + >{{ model.name }}</FONT></TD></TR> + + {% if not disable_fields %} + {% for field in model.fields %} + <TR><TD ALIGN="LEFT" BORDER="0" + ><FONT {% if field.blank %}COLOR="#7B7B7B" {% endif %}FACE="Helvetica Bold">{{ field.name }}</FONT + ></TD> + <TD ALIGN="LEFT" + ><FONT {% if field.blank %}COLOR="#7B7B7B" {% endif %}FACE="Helvetica Bold">{{ field.type }}</FONT + ></TD></TR> + {% endfor %} + {% endif %} + </TABLE> + >] + {% endfor %} +""" + +tail_template = """ +} +""" + +def generate_dot(app_labels, **kwargs): + disable_fields = kwargs.get('disable_fields', False) + include_models = kwargs.get('include_models', []) + exclude_models = kwargs.get('exclude_models', []) + + dot = head_template + + for app_label in app_labels: + app = models.get_app(app_label) + graph = Context({ + 'name': '"%s"' % app.__name__, + 'disable_fields': disable_fields, + 'models': [] + }) + + for appmodel in get_models(app): + + # consider given model name ? + def consider(model_name): + return (not include_models or model_name in include_models) and (not model_name in exclude_models) + + if not consider(appmodel._meta.object_name): + continue + + model = { + 'name': appmodel.__name__, + 'fields': [], + 'relations': [] + } + + # model attributes + def add_attributes(): + model['fields'].append({ + 'name': field.name, + 'type': type(field).__name__, + 'blank': field.blank + }) + + for field in appmodel._meta.fields: + add_attributes() + + if appmodel._meta.many_to_many: + for field in appmodel._meta.many_to_many: + add_attributes() + + # relations + def add_relation(extras=""): + _rel = { + 'target': field.rel.to.__name__, + 'type': type(field).__name__, + 'name': field.name, + 'arrows': extras + } + if _rel not in model['relations'] and consider(_rel['target']): + model['relations'].append(_rel) + + def add_geo_relation(target,relation,extras=""): + _rel = { + 'target': target, + 'type': type(field).__name__, + 'name': relation, + 'arrows': extras + } + if _rel not in model['relations'] and consider(_rel['target']): + model['relations'].append(_rel) + + for field in appmodel._meta.fields: + if isinstance(field, ForeignKey): + add_relation() + elif isinstance(field, OneToOneField): + add_relation("[arrowhead=none arrowtail=none]") + elif isinstance(field, GeometryField): + #import pdb; pdb.set_trace() + add_geo_relation('SpatialRefSys',field._srid,"[arrowhead=normal arrowtail=none]") + add_geo_relation('GeometryColumns',field._geom,"[arrowhead=normal arrowtail=none]") + + if appmodel._meta.many_to_many: + for field in appmodel._meta.many_to_many: + if isinstance(field, ManyToManyField): + add_relation("[arrowhead=normal arrowtail=normal]") + elif isinstance(field, GenericRelation): + add_relation( + '[style="dotted"] [arrowhead=normal arrowtail=normal]') + graph['models'].append(model) + + t = Template(body_template) + dot += '\n' + t.render(graph) + + dot += '\n' + tail_template + + return dot + +def main(): + try: + opts, args = getopt.getopt(sys.argv[1:], "hdi:e:", + ["help", "disable_fields", "include_models=", "exclude_models="]) + except getopt.GetoptError, error: + print __doc__ + sys.exit(error) + else: + if not args: + print __doc__ + sys.exit() + + kwargs = {} + for opt, arg in opts: + if opt in ("-h", "--help"): + print __doc__ + sys.exit() + if opt in ("-d", "--disable_fields"): + kwargs['disable_fields'] = True + if opt in ("-i", "--include_models"): + kwargs['include_models'] = arg.split(',') + if opt in ("-e", "--exclude_models"): + kwargs['exclude_models'] = arg.split(',') + print generate_dot(args, **kwargs) + +if __name__ == "__main__": + main() diff --git a/test.png b/test.png new file mode 100644 index 0000000..1b07f7a Binary files /dev/null and b/test.png differ diff --git a/test2.png b/test2.png new file mode 100644 index 0000000..1b07f7a Binary files /dev/null and b/test2.png differ
ThomasPedersen/mattespill
cedca281491d2c894e4e636d8fea286bda716607
Forgot mimetype in JSON view.
diff --git a/main/views.py b/main/views.py index c13f512..2e00151 100644 --- a/main/views.py +++ b/main/views.py @@ -1,170 +1,170 @@ # -*- coding: utf-8 -*- from django.template import RequestContext, Context, loader from django.utils import simplejson from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden from django.shortcuts import render_to_response, get_object_or_404 from django.contrib import auth from django.contrib.auth.decorators import login_required from django.core import serializers from datetime import datetime from mattespill.main.models import Question, Room, Turn, Result, UserProfile, Hint from mattespill.main.forms import SignupForm import json login_url = '/login/' def index(request): if request.user.is_authenticated(): rooms = Room.objects.all() return render_to_response('home.html', {'user': request.user, 'home': True, \ 'rooms': rooms}) else: return HttpResponseRedirect(login_url) def room(request, room_id): if request.user.is_authenticated(): sess_room_id = request.session.get('room_id', None) if not sess_room_id or sess_room_id != room_id: room = get_object_or_404(Room, pk=room_id) else: room = get_object_or_404(Room, pk=sess_room_id) # If user does not have enough points to access room, # we redirect to index if request.user.get_profile().points < room.required_points: return HttpResponseRedirect('/') request.session['room_id'] = room_id turn_exists = False try: t = Turn.objects.get(room=room, user=request.user, complete=False) turn_exists = True except Turn.DoesNotExist: t = Turn(date_start=datetime.now(), date_end=None, user=request.user, room=room) t.save() # Fetch 10 random questions for the given room questions = Question.objects.filter(room=room).order_by('?')[:10] # Add Result objects (question and answer pairs) for each question i = 1 # Sequence number for each question for q in questions: result = Result(question=q, turn=t, index=i) result.save() i += 1 previous_turns = Turn.objects.filter(room=room, user=request.user, complete=True).\ order_by('-date_start').order_by('-total_points').all() return render_to_response('room.html', {'turn_exists': turn_exists, 'turn': t, \ 'user': request.user, 'previous_turns': previous_turns}) else: return HttpResponseRedirect(login_url) def logout(request): auth.logout(request) return HttpResponseRedirect('/') def buyhint(request): if request.user.is_authenticated(): # Get a random hint room_id = request.session.get('room_id', None) if room_id: hint = Hint.objects.filter(room=room_id).order_by('?')[:1] # Check if user has enough points profile = request.user.get_profile() cost = hint[0].cost if profile.points - cost < 1: return HttpResponse(json.dumps({'points': profile.points, \ - 'hint': None})) + 'hint': None}), mimetype='application/json') else: profile.points -= cost profile.save() # Return json response return HttpResponse(json.dumps({'points': profile.points, 'hint': hint[0].text}), \ mimetype='application/json') else: return HttpResponseForbidden() def stats(request): if request.user.is_authenticated(): # Get max 10 users ordered by points desc users = UserProfile.objects.order_by('-points')[:10] return render_to_response('stats.html', {'user': request.user, 'users': users}) else: return HttpResponseRedirect(login_url) def question(request): if request.user.is_authenticated(): room_id = request.session.get('room_id', None) if room_id: try: turn = Turn.objects.get(room=room_id, user=request.user, complete=False) except Turn.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) try: # The Meta.ordering defined in model will sort # the result ascending on Result.index result = Result.objects.filter(turn=turn, answer='')[:1] if not result: return render_to_response('room.html', {'turn': turn, 'user': request.user}) num_questions = Result.objects.filter(turn=turn).count() return render_to_response('question.html', {'user': request.user,'turn': turn, 'result': result[0], \ 'num_questions': num_questions, 'room_id': room_id}) except Result.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) else: return HttpResponseRedirect(login_url) def answer(request): if request.user.is_authenticated() and request.method == 'POST': room_id = request.session.get('room_id', None) if room_id and 'answer' in request.POST: given_answer = request.POST['answer'].strip() user = request.user t = get_object_or_404(Turn, room=room_id, user=user, complete=False) count = Result.objects.filter(turn=t).count() result = Result.objects.filter(turn=t, answer='')[0] try: if result.index < count: index = result.index + 1 question = Result.objects.get(turn=t, index=index).question.question else: index = -1 # No more questions question = None t.complete = True t.save() correct = given_answer == result.question.real_answer if correct: # Give user some points user.get_profile().points += result.question.points t.total_points += result.question.points else: # For wrong answer users lose (question points / 2) penalty = result.question.points / 2 user.get_profile().points -= penalty t.total_points -= penalty t.save() user.get_profile().save() result.answer = given_answer result.save() return HttpResponse(json.dumps({'correct': correct, 'index': index, \ 'question': question, 'points': user.get_profile().points}), \ mimetype='application/json') except Result.DoesNotExist as e: return HttpResponse(e) else: return HttpResponseRedirect(login_url) def signup(request): if request.method == 'POST': form = SignupForm(data=request.POST) if form.is_valid(): form.save(); return HttpResponseRedirect('/') else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request)) else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request))
ThomasPedersen/mattespill
47c15d7d3e079909f1490fe46de48efc06e96d57
Disallow buying of hints if user doesn't have enough points.
diff --git a/main/views.py b/main/views.py index 3c2eb95..c13f512 100644 --- a/main/views.py +++ b/main/views.py @@ -1,165 +1,170 @@ # -*- coding: utf-8 -*- from django.template import RequestContext, Context, loader from django.utils import simplejson from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden from django.shortcuts import render_to_response, get_object_or_404 from django.contrib import auth from django.contrib.auth.decorators import login_required from django.core import serializers from datetime import datetime from mattespill.main.models import Question, Room, Turn, Result, UserProfile, Hint from mattespill.main.forms import SignupForm import json login_url = '/login/' def index(request): if request.user.is_authenticated(): rooms = Room.objects.all() return render_to_response('home.html', {'user': request.user, 'home': True, \ 'rooms': rooms}) else: return HttpResponseRedirect(login_url) def room(request, room_id): if request.user.is_authenticated(): sess_room_id = request.session.get('room_id', None) if not sess_room_id or sess_room_id != room_id: room = get_object_or_404(Room, pk=room_id) else: room = get_object_or_404(Room, pk=sess_room_id) # If user does not have enough points to access room, # we redirect to index if request.user.get_profile().points < room.required_points: return HttpResponseRedirect('/') request.session['room_id'] = room_id turn_exists = False try: t = Turn.objects.get(room=room, user=request.user, complete=False) turn_exists = True except Turn.DoesNotExist: t = Turn(date_start=datetime.now(), date_end=None, user=request.user, room=room) t.save() # Fetch 10 random questions for the given room questions = Question.objects.filter(room=room).order_by('?')[:10] # Add Result objects (question and answer pairs) for each question i = 1 # Sequence number for each question for q in questions: result = Result(question=q, turn=t, index=i) result.save() i += 1 previous_turns = Turn.objects.filter(room=room, user=request.user, complete=True).\ order_by('-date_start').order_by('-total_points').all() return render_to_response('room.html', {'turn_exists': turn_exists, 'turn': t, \ 'user': request.user, 'previous_turns': previous_turns}) else: return HttpResponseRedirect(login_url) def logout(request): auth.logout(request) return HttpResponseRedirect('/') def buyhint(request): if request.user.is_authenticated(): # Get a random hint room_id = request.session.get('room_id', None) if room_id: hint = Hint.objects.filter(room=room_id).order_by('?')[:1] - # Subtract points from user + # Check if user has enough points profile = request.user.get_profile() - profile.points -= hint[0].cost - profile.save() - # Return json response - return HttpResponse(json.dumps({'points': profile.points, 'hint': hint[0].text}), \ - mimetype='application/json') + cost = hint[0].cost + if profile.points - cost < 1: + return HttpResponse(json.dumps({'points': profile.points, \ + 'hint': None})) + else: + profile.points -= cost + profile.save() + # Return json response + return HttpResponse(json.dumps({'points': profile.points, 'hint': hint[0].text}), \ + mimetype='application/json') else: return HttpResponseForbidden() def stats(request): if request.user.is_authenticated(): # Get max 10 users ordered by points desc users = UserProfile.objects.order_by('-points')[:10] return render_to_response('stats.html', {'user': request.user, 'users': users}) else: return HttpResponseRedirect(login_url) def question(request): if request.user.is_authenticated(): room_id = request.session.get('room_id', None) if room_id: try: turn = Turn.objects.get(room=room_id, user=request.user, complete=False) except Turn.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) try: # The Meta.ordering defined in model will sort # the result ascending on Result.index result = Result.objects.filter(turn=turn, answer='')[:1] if not result: return render_to_response('room.html', {'turn': turn, 'user': request.user}) num_questions = Result.objects.filter(turn=turn).count() return render_to_response('question.html', {'user': request.user,'turn': turn, 'result': result[0], \ 'num_questions': num_questions, 'room_id': room_id}) except Result.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) else: return HttpResponseRedirect(login_url) def answer(request): if request.user.is_authenticated() and request.method == 'POST': room_id = request.session.get('room_id', None) if room_id and 'answer' in request.POST: given_answer = request.POST['answer'].strip() user = request.user t = get_object_or_404(Turn, room=room_id, user=user, complete=False) count = Result.objects.filter(turn=t).count() result = Result.objects.filter(turn=t, answer='')[0] try: if result.index < count: index = result.index + 1 question = Result.objects.get(turn=t, index=index).question.question else: index = -1 # No more questions question = None t.complete = True t.save() correct = given_answer == result.question.real_answer if correct: # Give user some points user.get_profile().points += result.question.points t.total_points += result.question.points else: # For wrong answer users lose (question points / 2) penalty = result.question.points / 2 user.get_profile().points -= penalty t.total_points -= penalty t.save() user.get_profile().save() result.answer = given_answer result.save() return HttpResponse(json.dumps({'correct': correct, 'index': index, \ 'question': question, 'points': user.get_profile().points}), \ mimetype='application/json') except Result.DoesNotExist as e: return HttpResponse(e) else: return HttpResponseRedirect(login_url) def signup(request): if request.method == 'POST': form = SignupForm(data=request.POST) if form.is_valid(): form.save(); return HttpResponseRedirect('/') else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request)) else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request))
ThomasPedersen/mattespill
39b6d036341b77842531bfd4c7324561a3b343cf
liten fix
diff --git a/main/media/question.js b/main/media/question.js index ef7a5e6..aaa9558 100644 --- a/main/media/question.js +++ b/main/media/question.js @@ -1,92 +1,92 @@ var bearTimer; function showBear() { - $('#hintbear').show().animate({ + $('#hintbear').html('Har du lyst p&aring; hjelp?<br />Klikk p&aring; meg!').show().animate({ opacity: 1, marginRight: '0em', }, 1000, function() { - $('#hintbear .dialogbox').html('Har du lyst p&aring; hjelp?<br />Klikk p&aring; meg!').fadeIn(500); + $('#hintbear .dialogbox').fadeIn(500); }); } function startBear() { bearTimer = setTimeout(showBear, 5000); } function stopBear() { if (bearTimer != null) clearTimeout(bearTimer); $('#hintbear').animate({ opacity: 0, marginRight: '-7em' }, 1000, $('#hintbear').hide); } $(function() { $('.start_button').click(function() { stopBear(); if ($.trim($('input[name=answer]').val()) == '') { alert('Du må skrive inn noe!'); $('input[name=answer]').val(''); return; } startBear(); $.ajax({ type: 'POST', url: '/answer/', dataType: 'json', data: {answer: $('input[name=answer]').val()}, success: function(data, textStatus) { $('#num_points').text(data.points); if (data.correct) { $('#wrong_answer').hide(); $('#correct_answer').fadeIn(); } else { $('#correct_answer').hide(); $('#wrong_answer').fadeIn(); } if (data.index < 0) { $('#question_wrapper').remove(); $('#finished_wrapper').show(); } else { $('input[name=answer]').val('').focus(); $('#question_index').text(data.index); $('#question_text').text(data.question); } }, error: function(XMLHttpRequest, textStatus) { alert('Det oppstod en feil'); } }); }); $('#answer_form').submit(function() { $('.simple_button').click(); return false; }); $('#hintbear').click(function() { $.ajax({ type: 'POST', url: '/buyhint/', dataType: 'json', success: function(data, textStatus) { $('#hintbear .dialogbox').text(data.hint); $('#num_points').text(data.points); $('#hintbear').unbind('click').css('cursor', 'auto'); }, error: function(XMLHttpRequest, textStatus) { alert('Det oppstod en feil'); } }); }); $('input[name=answer]').focus(); startBear(); }); \ No newline at end of file
ThomasPedersen/mattespill
da749364b213094c0ade1e882b5490798e7d9353
pedo bear + css separation question.html
diff --git a/main/media/main.css b/main/media/main.css index 85ebe6a..f986169 100644 --- a/main/media/main.css +++ b/main/media/main.css @@ -1,167 +1,167 @@ @font-face { font-family: Aller; font-weight: normal; src: url('fonts/Aller_Rg.ttf'); } @font-face { font-family: Aller; font-weight: bold; src: url('fonts/Aller_Bd.ttf'); } body { font-family: Aller, sans-serif; margin: 0; padding: 0; background: url(images/stripes.png); } *:focus { outline: none; } h1 { font-size: 1.8em; margin-top: 0; } h2 { font-size: 1.4em; color: #666; } .chest_header { margin-top: 0; font-size: 150%; font-weight: bold; /*text-shadow: #1D4088 1.5px 1.5px 1.5px;*/ } h1, .chest_header { color: #1D4088; /*color: #9342ad;*/ /*color: #dbda00;*/ /*text-shadow: #aaa 1.5px 1.5px 0px;*/ } #header a { color: #fff; } a, a:visited a:active { text-decoration: none; color: #0000aa; } a:hover { text-decoration: underline; color: #434358; } #wrapper { margin: 0; /*background-color: #dadada;*/ } #header { /*border-bottom: 2px solid #777;*/ color: #fff; padding: .8em 1.5em .6em 1em; font-weight: bold; } #headertable { width: 100%; } #headertable td { width: 33%; } .align_center { text-align: center; } .align_right { text-align: right; } #page_content { margin: 0 8em; padding: 1em; padding-bottom: 2em; background-color: #fff; -moz-border-radius-bottomleft: 1.5em; -webkit-bottom-left-border-radius: 1.5em; border-bottom-left-radius: 1.5em; -moz-border-radius-bottomright: 1.5em; -webkit-border-bottom-right-radius: 1.5em; border-bottom-right-radius: 1.5em; -webkit-box-shadow: 0 0 2em #bbb; -moz-box-shadow: 0 0 2em #bbb; box-shadow: 0 0 2em #bbb; margin-bottom: 3em; } .gold_coins { padding-bottom: .4em; padding-left: .5em; padding-right: .5em; background-color: #e5e5e5; -moz-border-radius: .7em; -webkit-border-radius: .7em; border-radius: .7em; } .gold_text { vertical-align: bottom; font-size: 140%; color: #ff0; font-weight: bold; text-shadow: #000 0 0 5px; } #logout_reminder { font-size: 150%; color: #4b844b; } .simple_button { cursor: pointer; - padding: .5em; + padding: .5em 1.5em; background-color: #627AAD; color: #fff; font-weight: bold; font-size: 1.3em; border: .2em solid #325193; /*-webkit-box-shadow: 0 0 2em #bbb; -moz-box-shadow: 0 0 2em #bbb; box-shadow: 0 0 2em #bbb;*/ -moz-border-radius: .6em; -webkit-border-radius: .6em; border-radius: .6em; } .simple_button a { color: inherit; } .back_button { margin-top: 4em; } table.styled { text-align: left; border-collapse: collapse; border: 2px solid #b7d4f4; } table.styled th { background-color: #eaf0f6; border: 1px solid #d1e3f6; } table.styled td { background-color: #f7f7f7; border: 1px solid #dadada; } table.styled tr:nth-child(even) td { background-color: white; } table.styled td, table.styled th { padding: .3em .4em; } \ No newline at end of file diff --git a/main/media/question.css b/main/media/question.css new file mode 100644 index 0000000..2a0c879 --- /dev/null +++ b/main/media/question.css @@ -0,0 +1,65 @@ +#correct_answer { + background-color: #afa; +} +#wrong_answer { + background-color: #fcc; +} +#correct_answer, #wrong_answer { + display: none; + padding: .3em; + -moz-border-radius: .3em; + -webkit-border-radius: .3em; + border-radius: .3em; +} +#question_text { + font-size: 1.5em; +} +#finished_wrapper { + display: none; +} +input[name=answer] { + font-size: 1.5em; + padding: .5em; + border: .2em solid #325193; + background-color: #f2f2f2; + margin: .5em 0; + + -moz-border-radius: .5em; + -webkit-border-radius: .5em; + border-radius: .5em; + + -text-shadow: #bbb 1px 1px 3px; + + -webkit-box-shadow: 0 0 .7em #bbb; + -moz-box-shadow: 0 0 .7em #bbb; + box-shadow: 0 0 .7em #bbb; +} +#hintbear { + cursor: pointer; + float: right; + position: relative; + + display: none; + opacity: 0; + margin-right: -7em; +} +#hintbear img { + width: 10em; +} +#hintbear .dialogbox { + display: none; + position: absolute; + left: -9em; + top: 0em; + max-width: 20em; + + padding: .5em; + border: .2em solid #000; + background-color: #fff; + -webkit-box-shadow: 0 0 1em #888; + -moz-box-shadow: 0 0 1em #888; + box-shadow: 0 0 1em #888; + -moz-border-radius: 1em; + -webkit-border-radius: 1em; + border-radius: 1em; +} diff --git a/main/media/question.js b/main/media/question.js index 44f7928..ef7a5e6 100644 --- a/main/media/question.js +++ b/main/media/question.js @@ -1,73 +1,92 @@ var bearTimer; function showBear() { $('#hintbear').show().animate({ opacity: 1, marginRight: '0em', }, 1000, function() { - $('#hintbear .dialogbox').fadeIn(500); + $('#hintbear .dialogbox').html('Har du lyst p&aring; hjelp?<br />Klikk p&aring; meg!').fadeIn(500); }); } function startBear() { - bearTimer = setTimeout(showBear, 1000); + bearTimer = setTimeout(showBear, 5000); } function stopBear() { if (bearTimer != null) clearTimeout(bearTimer); + + $('#hintbear').animate({ + opacity: 0, + marginRight: '-7em' + }, 1000, $('#hintbear').hide); } $(function() { $('.start_button').click(function() { + stopBear(); + if ($.trim($('input[name=answer]').val()) == '') { alert('Du må skrive inn noe!'); $('input[name=answer]').val(''); return; } startBear(); $.ajax({ type: 'POST', url: '/answer/', dataType: 'json', data: {answer: $('input[name=answer]').val()}, success: function(data, textStatus) { $('#num_points').text(data.points); if (data.correct) { $('#wrong_answer').hide(); $('#correct_answer').fadeIn(); } else { $('#correct_answer').hide(); $('#wrong_answer').fadeIn(); } if (data.index < 0) { $('#question_wrapper').remove(); $('#finished_wrapper').show(); } else { $('input[name=answer]').val('').focus(); $('#question_index').text(data.index); $('#question_text').text(data.question); } }, error: function(XMLHttpRequest, textStatus) { alert('Det oppstod en feil'); } }); }); $('#answer_form').submit(function() { $('.simple_button').click(); return false; }); - $('input[name=answer]').focus(); - startBear(); - $('#hintbear').click(function() { - alert('aaaaahh'); + $.ajax({ + type: 'POST', + url: '/buyhint/', + dataType: 'json', + success: function(data, textStatus) { + $('#hintbear .dialogbox').text(data.hint); + $('#num_points').text(data.points); + $('#hintbear').unbind('click').css('cursor', 'auto'); + }, + error: function(XMLHttpRequest, textStatus) { + alert('Det oppstod en feil'); + } + }); }); + + $('input[name=answer]').focus(); + startBear(); }); \ No newline at end of file diff --git a/main/templates/question.html b/main/templates/question.html index 7c5fd62..49b053e 100644 --- a/main/templates/question.html +++ b/main/templates/question.html @@ -1,98 +1,33 @@ {% extends "outer.html" %} {% block head %} -<style type="text/css"> -#correct_answer { - background-color: #afa; -} -#wrong_answer { - background-color: #fcc; -} -#correct_answer, #wrong_answer { - display: none; - padding: .3em; - -moz-border-radius: .3em; - -webkit-border-radius: .3em; - border-radius: .3em; -} -#question_text { - font-size: 1.5em; -} -#finished_wrapper { - display: none; -} -input[name=answer] { - font-size: 1.5em; - padding: .5em; - border: .2em solid #325193; - background-color: #f2f2f2; - margin: .5em 0; - - -moz-border-radius: .5em; - -webkit-border-radius: .5em; - border-radius: .5em; - - -text-shadow: #bbb 1px 1px 3px; - - -webkit-box-shadow: 0 0 .7em #bbb; - -moz-box-shadow: 0 0 .7em #bbb; - box-shadow: 0 0 .7em #bbb; -} -#hintbear { - cursor: pointer; - float: right; - position: relative; - - display: none; - opacity: 0; - margin-right: -7em; -} -#hintbear img { - width: 10em; -} -#hintbear .dialogbox { - display: none; - position: absolute; - left: -9em; - top: 0em; - - padding: .5em; - border: .2em solid #000; - background-color: #fff; - -webkit-box-shadow: 0 0 1em #888; - -moz-box-shadow: 0 0 1em #888; - box-shadow: 0 0 1em #888; - -moz-border-radius: 1em; - -webkit-border-radius: 1em; - border-radius: 1em; -} -</style> +<link rel="stylesheet" href="/media/question.css" type="text/css" /> <script src="/media/question.js" type="text/javascript"></script> {% endblock %} {% block content %} -<div id="hintbear"><div class="dialogbox">Har du lyst p&aring; hjelp?<br />Klikk p&aring; meg!</div><img alt="Hintbj&oslash;rnen" src="/media/images/hintbear.png" /></div> +<div id="hintbear"><div class="dialogbox"></div><img alt="Hintbj&oslash;rnen" src="/media/images/hintbear.png" /></div> <h1>Sp&oslash;rsm&aring;l <span id="question_index">{{ result.index }}</span> av {{ num_questions }}</h1> <p id="correct_answer">Du svarte riktig p&aring; forrige oppgave.</p> <p id="wrong_answer">Feil svar p&aring; forrige oppgave.</p> <div id="question_wrapper"> <p id="question_text">{{ result.question.question}}</p> <form id="answer_form" action="" method="post"> <input type="text" name="answer" autocomplete="off" /> - <p class="start_button_container"><span class="start_button simple_button">Svar</span></p></p> + <p class="button_container"><span class="start_button simple_button">Svar</span></p></p> </form> <p class="back_button"><a href="/room/{{ room_id }}/">G&aring; tilbake til rommet</a></p> </div> <div id="finished_wrapper"> <p>Du er ferdig med dette fors&oslash;ket!</p> - <p class="start_button_container"><span class="simple_button"><a href="/room/{{ room_id }}/">Tilbake til rommet!</a></span></p> + <p class="button_container"><span class="simple_button"><a href="/room/{{ room_id }}/">Tilbake til rommet!</a></span></p> </div> {% endblock %}
ThomasPedersen/mattespill
1df4c95719d0196337ccc1a29ba18191ee4a2e0e
Fixed initial data. Needed --exclude=contenttypes for dumpdata.
diff --git a/initial_data.json b/initial_data.json index 1ab322c..e693889 100644 --- a/initial_data.json +++ b/initial_data.json @@ -1 +1 @@ -[{"pk": 5, "model": "contenttypes.contenttype", "fields": {"model": "contenttype", "name": "content type", "app_label": "contenttypes"}}, {"pk": 2, "model": "contenttypes.contenttype", "fields": {"model": "group", "name": "group", "app_label": "auth"}}, {"pk": 14, "model": "contenttypes.contenttype", "fields": {"model": "hint", "name": "hint", "app_label": "main"}}, {"pk": 8, "model": "contenttypes.contenttype", "fields": {"model": "logentry", "name": "log entry", "app_label": "admin"}}, {"pk": 4, "model": "contenttypes.contenttype", "fields": {"model": "message", "name": "message", "app_label": "auth"}}, {"pk": 1, "model": "contenttypes.contenttype", "fields": {"model": "permission", "name": "permission", "app_label": "auth"}}, {"pk": 11, "model": "contenttypes.contenttype", "fields": {"model": "question", "name": "question", "app_label": "main"}}, {"pk": 13, "model": "contenttypes.contenttype", "fields": {"model": "result", "name": "result", "app_label": "main"}}, {"pk": 10, "model": "contenttypes.contenttype", "fields": {"model": "room", "name": "room", "app_label": "main"}}, {"pk": 6, "model": "contenttypes.contenttype", "fields": {"model": "session", "name": "session", "app_label": "sessions"}}, {"pk": 7, "model": "contenttypes.contenttype", "fields": {"model": "site", "name": "site", "app_label": "sites"}}, {"pk": 12, "model": "contenttypes.contenttype", "fields": {"model": "turn", "name": "turn", "app_label": "main"}}, {"pk": 3, "model": "contenttypes.contenttype", "fields": {"model": "user", "name": "user", "app_label": "auth"}}, {"pk": 9, "model": "contenttypes.contenttype", "fields": {"model": "userprofile", "name": "user profile", "app_label": "main"}}, {"pk": "5a51edfd2da6fd1442ecfebe170564ac", "model": "sessions.session", "fields": {"expire_date": "2010-10-29 12:36:30", "session_data": "gAJ9cQEoVQdyb29tX2lkcQJYAQAAADFVEl9hdXRoX3VzZXJfYmFja2VuZHEDVSlkamFuZ28uY29u\ndHJpYi5hdXRoLmJhY2tlbmRzLk1vZGVsQmFja2VuZHEEVQ1fYXV0aF91c2VyX2lkcQVLAXUuYThl\nZjM4YTUyZGIzOTQ4ODE1NzM0MTU1NTc0OWYxZWM=\n"}}, {"pk": "82d8dd22044d3c538a2dfe6dd7a8581e", "model": "sessions.session", "fields": {"expire_date": "2010-10-29 13:56:34", "session_data": "gAJ9cQEoVRJfYXV0aF91c2VyX2JhY2tlbmRxAlUpZGphbmdvLmNvbnRyaWIuYXV0aC5iYWNrZW5k\ncy5Nb2RlbEJhY2tlbmRxA1UNX2F1dGhfdXNlcl9pZHEESwF1LmNhYTgxNjQ5YjIxNjUzMzMyOGQw\nODJlNGY0MDEyZDAy\n"}}, {"pk": "a9e85fb1644846c7cb311646c210fccb", "model": "sessions.session", "fields": {"expire_date": "2010-10-29 14:53:57", "session_data": "gAJ9cQEoVQdyb29tX2lkcQJYAQAAADFVDV9hdXRoX3VzZXJfaWRxA0sBVRJfYXV0aF91c2VyX2Jh\nY2tlbmRxBFUpZGphbmdvLmNvbnRyaWIuYXV0aC5iYWNrZW5kcy5Nb2RlbEJhY2tlbmRxBXUuOWFm\nYjQ4ZmZhZmZmOTM0MjgzYTVmMmE2YWFhZGMzNzY=\n"}}, {"pk": "9144be769c27a17b96e5d9afedea04a7", "model": "sessions.session", "fields": {"expire_date": "2010-11-15 12:05:21", "session_data": "gAJ9cQEoVQdyb29tX2lkcQJYAQAAADFVDV9hdXRoX3VzZXJfaWRxA0sBVRJfYXV0aF91c2VyX2Jh\nY2tlbmRxBFUpZGphbmdvLmNvbnRyaWIuYXV0aC5iYWNrZW5kcy5Nb2RlbEJhY2tlbmRxBXUuOWFm\nYjQ4ZmZhZmZmOTM0MjgzYTVmMmE2YWFhZGMzNzY=\n"}}, {"pk": "4e710015a910ac114305d3df1ff63869", "model": "sessions.session", "fields": {"expire_date": "2010-10-29 14:37:57", "session_data": "gAJ9cQEoVQdyb29tX2lkcQJYAQAAADFVDV9hdXRoX3VzZXJfaWRxA0sBVRJfYXV0aF91c2VyX2Jh\nY2tlbmRxBFUpZGphbmdvLmNvbnRyaWIuYXV0aC5iYWNrZW5kcy5Nb2RlbEJhY2tlbmRxBXUuOWFm\nYjQ4ZmZhZmZmOTM0MjgzYTVmMmE2YWFhZGMzNzY=\n"}}, {"pk": "5c13f19fb0e878c1eae9a43049b738c1", "model": "sessions.session", "fields": {"expire_date": "2010-11-15 11:57:01", "session_data": "gAJ9cQEoVQdyb29tX2lkcQJYAQAAADFVEl9hdXRoX3VzZXJfYmFja2VuZHEDVSlkamFuZ28uY29u\ndHJpYi5hdXRoLmJhY2tlbmRzLk1vZGVsQmFja2VuZHEEVQ1fYXV0aF91c2VyX2lkcQVLAXUuYThl\nZjM4YTUyZGIzOTQ4ODE1NzM0MTU1NTc0OWYxZWM=\n"}}, {"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}, {"pk": 90, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-11-01 12:06:00", "object_repr": "[Addisjon, 2010-11-01 11:29:34] test", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 89, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-11-01 12:00:31", "object_repr": "[Addisjon] How do you like them apples?", "object_id": "2", "change_message": "", "user": 1, "content_type": 14}}, {"pk": 88, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-11-01 11:56:00", "object_repr": "test2", "object_id": "3", "change_message": "Endret username.", "user": 1, "content_type": 3}}, {"pk": 87, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-11-01 11:55:54", "object_repr": "test", "object_id": "1", "change_message": "Endret username.", "user": 1, "content_type": 3}}, {"pk": 86, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-11-01 11:54:50", "object_repr": "[Addisjon] Forestill deg to epler blablabla FFFFFFFFFUUUUU", "object_id": "1", "change_message": "Endret cost.", "user": 1, "content_type": 14}}, {"pk": 84, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-11-01 11:17:45", "object_repr": "[Addisjon, 2010-10-15 14:56:35] ericc", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 85, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-11-01 11:17:45", "object_repr": "[Addisjon, 2010-10-15 14:55:50] ericc", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 80, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-11-01 11:17:44", "object_repr": "[Subtraksjon, 2010-10-19 17:31:02] ericc", "object_id": "6", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 81, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-11-01 11:17:44", "object_repr": "[Addisjon, 2010-10-19 17:30:49] ericc", "object_id": "5", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 82, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-11-01 11:17:44", "object_repr": "[Addisjon, 2010-10-15 14:58:10] ericc", "object_id": "4", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 83, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-11-01 11:17:44", "object_repr": "[Subtraksjon, 2010-10-15 14:56:39] ericc", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 79, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-11-01 11:17:17", "object_repr": "ericc's profile", "object_id": "1", "change_message": "Endret points.", "user": 1, "content_type": 9}}, {"pk": 78, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-11-01 11:16:35", "object_repr": "kennym", "object_id": "3", "change_message": "Endret username, first_name, last_name og email.", "user": 1, "content_type": 3}}, {"pk": 77, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-11-01 11:15:49", "object_repr": "ericc", "object_id": "1", "change_message": "Endret username.", "user": 1, "content_type": 3}}, {"pk": 76, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-11-01 11:15:35", "object_repr": "vegardoj", "object_id": "2", "change_message": "", "user": 1, "content_type": 3}}, {"pk": 75, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-11-01 11:13:40", "object_repr": "[Addisjon] Forestill deg to epler blablabla FFFFFFFFFUUUUU", "object_id": "1", "change_message": "", "user": 1, "content_type": 14}}, {"pk": 74, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-11-01 09:15:57", "object_repr": "test2", "object_id": "3", "change_message": "", "user": 1, "content_type": 3}}, {"pk": 73, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:54:55", "object_repr": "vegardoj's profile", "object_id": "2", "change_message": "", "user": 1, "content_type": 9}}, {"pk": 72, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 14:54:48", "object_repr": "test's profile", "object_id": "1", "change_message": "Endret points.", "user": 1, "content_type": 9}}, {"pk": 71, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:54:25", "object_repr": "[Addisjon, 2010-10-15 14:37:13] test", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 70, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:54:24", "object_repr": "[Addisjon, 2010-10-15 14:53:56] test", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 69, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:37:05", "object_repr": "[Addisjon, 2010-10-15 14:31:24] test", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 68, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:37:04", "object_repr": "[Addisjon, 2010-10-15 14:33:15] test", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 67, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:31:12", "object_repr": "[Subtraksjon, 2010-10-15 14:27:18] test", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 66, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:31:11", "object_repr": "[Addisjon, 2010-10-15 14:29:27] test", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 65, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:12", "object_repr": "[Subtraksjon, 2010-10-15 12:57:40] test", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 57, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Divisjon, 2010-10-15 12:58:59] test", "object_id": "9", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 58, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Divisjon, 2010-10-15 12:58:50] test", "object_id": "8", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 59, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Divisjon, 2010-10-15 12:58:42] test", "object_id": "7", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 60, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Divisjon, 2010-10-15 12:58:34] test", "object_id": "6", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 61, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Divisjon, 2010-10-15 12:58:21] test", "object_id": "5", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 62, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Multiplikasjon, 2010-10-15 12:58:14] test", "object_id": "4", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 63, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Multiplikasjon, 2010-10-15 12:58:02] test", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 64, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Subtraksjon, 2010-10-15 12:57:53] test", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 53, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:10", "object_repr": "[Addisjon, 2010-10-15 14:25:12] test", "object_id": "13", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 54, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:10", "object_repr": "[Addisjon, 2010-10-15 13:50:34] vegardoj", "object_id": "12", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 55, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:10", "object_repr": "[Addisjon, 2010-10-15 13:50:19] vegardoj", "object_id": "11", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 56, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:10", "object_repr": "[Divisjon, 2010-10-15 12:59:04] test", "object_id": "10", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 48, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:19:10", "object_repr": "[Addisjon] Maria har 5 bananer og Per har 3 bananer. Hvor mange bananer har Maria og Per til sammen?", "object_id": "22", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 47, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:14:03", "object_repr": "[Multiplikasjon] Andre trinn p\u00e5 Notodden skole best\u00e5r av tre klasser. Det g\u00e5r 21 elever i hver klasse. Hvor mange elever er det i alt p\u00e5 andre trinn?", "object_id": "21", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 46, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:12:09", "object_repr": "[Divisjon] En klasse p\u00e5 32 elever skal deles i fire. Hvor mange blir det p\u00e5 hver gruppe?", "object_id": "20", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 45, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:10:47", "object_repr": "[Multiplikasjon] Petter f\u00e5r 50 kroner i ukel\u00f8nn. Hvor mye penger f\u00e5r han i l\u00f8pet av 5 uker?", "object_id": "19", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 44, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:09:36", "object_repr": "[Divisjon] Tre venner har ni epler. Hvor mange f\u00e5r de hver?", "object_id": "18", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 43, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:06:34", "object_repr": "[Addisjon] \u00c5ge har 5 epler. Han f\u00e5r 3 epler av Ingrid. Hvor mange epler har \u00c5ge til sammen?", "object_id": "17", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 42, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:05:36", "object_repr": "[Addisjon] En gutt har en valp. S\u00e5 f\u00e5r han en til. Hvor mange valper har han n\u00e5?", "object_id": "16", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 41, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:04:59", "object_repr": "[Subtraksjon] Per har 90 kroner og Lise har 50 kroner. De kj\u00f8per seg en CD til 80 kroner. Hvor mye har de igjen tilsammen?", "object_id": "15", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 40, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:02:08", "object_repr": "[Subtraksjon] Marthe har 35 kaker. Hun gir bort 10 til Elias. Hvor mange kaker har hun igjen?", "object_id": "14", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 39, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:01:37", "object_repr": "[Subtraksjon] Hilde har 54 kroner, og Magnus har 57 kroner. Hvor mange kroner mindre har Hilde enn Magnus?", "object_id": "13", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 52, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 13:59:12", "object_repr": "test's profile", "object_id": "1", "change_message": "Endret points.", "user": 1, "content_type": 9}}, {"pk": 49, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 13:16:53", "object_repr": "test | 2010-10-15 12:51:20.907567 | Divisjon", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 50, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 13:16:53", "object_repr": "test | 2010-10-15 12:50:03.041886 | Divisjon", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 51, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 13:16:53", "object_repr": "test | 2010-10-15 12:49:59.962029 | Addisjon", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 38, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:49:09", "object_repr": "Hva er 9 / 3?", "object_id": "12", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 37, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:48:48", "object_repr": "Hva er 8 / 4?", "object_id": "11", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 36, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:48:27", "object_repr": "Hva er 4 / 2?", "object_id": "10", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 35, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:48:08", "object_repr": "Hva er 10 * 10?", "object_id": "9", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 34, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:47:12", "object_repr": "Hva er 2 * 9?", "object_id": "8", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 33, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:46:59", "object_repr": "Hva er 4 * 4?", "object_id": "7", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 32, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:46:01", "object_repr": "example.com", "object_id": "1", "change_message": "", "user": 1, "content_type": 7}}, {"pk": 26, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 11:04:16.476584 | Addisjon", "object_id": "6", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 27, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:59:38.586859 | Addisjon", "object_id": "5", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 28, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:59:11.658703 | Addisjon", "object_id": "4", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 29, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:58:25.267152 | Addisjon", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 30, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:57:45.110544 | Addisjon", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 31, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:57:16.340061 | Addisjon", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 19, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 12:40:51.846371 | Addisjon", "object_id": "13", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 20, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 12:36:11.859253 | Addisjon", "object_id": "12", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 21, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 12:24:23.680071 | Subtraksjon", "object_id": "11", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 22, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:49:13.174200 | Addisjon", "object_id": "10", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 23, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:06:46.026789 | Addisjon", "object_id": "9", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 24, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:05:58.137954 | Addisjon", "object_id": "8", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 25, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:04:57.168726 | Addisjon", "object_id": "7", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 18, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 12:45:14", "object_repr": "test", "object_id": "1", "change_message": "Endret first_name og last_name.", "user": 1, "content_type": 3}}, {"pk": 17, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 12:44:51", "object_repr": "test", "object_id": "1", "change_message": "Endret first_name og last_name.", "user": 1, "content_type": 3}}, {"pk": 16, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:25:25", "object_repr": "Hva 34-5?", "object_id": "6", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 15, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:25:09", "object_repr": "Hva er 200-100", "object_id": "5", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 14, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:25:00", "object_repr": "Hva 10 - 3?", "object_id": "4", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 9, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:45:55.770004 | Addisjon", "object_id": "5", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 10, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:45:25.432687 | Addisjon", "object_id": "4", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 11, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:43:06.129923 | Addisjon", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 12, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:40:22.639628 | Addisjon", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 13, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:38:05 | Addisjon", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 8, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 10:39:54", "object_repr": "test | 2010-10-15 10:38:05 | Addisjon", "object_id": "1", "change_message": "Endret date_end og complete.", "user": 1, "content_type": 12}}, {"pk": 7, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:37:50", "object_repr": "Hva er 125+125?", "object_id": "3", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 6, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:37:30", "object_repr": "Hva er 50+23?", "object_id": "2", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 5, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:37:14", "object_repr": "Hva er 2 + 2?", "object_id": "1", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 4, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:54", "object_repr": "Divisjon", "object_id": "4", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 3, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:47", "object_repr": "Multiplikasjon", "object_id": "3", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 2, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:37", "object_repr": "Subtraksjon", "object_id": "2", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 1, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:25", "object_repr": "Addisjon", "object_id": "1", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 1, "model": "main.userprofile", "fields": {"points": 15, "user": 1}}, {"pk": 2, "model": "main.userprofile", "fields": {"points": 50, "user": 3}}, {"pk": 1, "model": "main.room", "fields": {"required_points": 0, "name": "Addisjon", "description": "Addere tall"}}, {"pk": 2, "model": "main.room", "fields": {"required_points": 100, "name": "Subtraksjon", "description": "Subtrahere tall"}}, {"pk": 3, "model": "main.room", "fields": {"required_points": 200, "name": "Multiplikasjon", "description": "Multiplisere tall"}}, {"pk": 4, "model": "main.room", "fields": {"required_points": 300, "name": "Divisjon", "description": "Dividere tall"}}, {"pk": 1, "model": "main.hint", "fields": {"text": "Forestill deg to epler blablabla FFFFFFFFFUUUUU", "cost": 30, "room": 1}}, {"pk": 2, "model": "main.hint", "fields": {"text": "How do you like them apples?", "cost": 25, "room": 1}}, {"pk": 1, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "Hva er 2 + 2?", "real_answer": "4", "points": 10, "date_created": "2010-10-15 10:37:14"}}, {"pk": 2, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "Hva er 50+23?", "real_answer": "73", "points": 14, "date_created": "2010-10-15 10:37:30"}}, {"pk": 3, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "Hva er 125+125?", "real_answer": "250", "points": 16, "date_created": "2010-10-15 10:37:50"}}, {"pk": 4, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Hva 10 - 3?", "real_answer": "7", "points": 21, "date_created": "2010-10-15 12:25:00"}}, {"pk": 5, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Hva er 200-100", "real_answer": "100", "points": 26, "date_created": "2010-10-15 12:25:09"}}, {"pk": 6, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Hva 34-5?", "real_answer": "29", "points": 28, "date_created": "2010-10-15 12:25:25"}}, {"pk": 7, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Hva er 4 * 4?", "real_answer": "16", "points": 32, "date_created": "2010-10-15 12:46:59"}}, {"pk": 8, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Hva er 2 * 9?", "real_answer": "18", "points": 25, "date_created": "2010-10-15 12:47:12"}}, {"pk": 9, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Hva er 10 * 10?", "real_answer": "100", "points": 27, "date_created": "2010-10-15 12:48:08"}}, {"pk": 10, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "Hva er 4 / 2?", "real_answer": "2", "points": 42, "date_created": "2010-10-15 12:48:27"}}, {"pk": 11, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "Hva er 8 / 4?", "real_answer": "2", "points": 46, "date_created": "2010-10-15 12:48:48"}}, {"pk": 12, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "Hva er 9 / 3?", "real_answer": "3", "points": 48, "date_created": "2010-10-15 12:49:09"}}, {"pk": 13, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Hilde har 54 kroner, og Magnus har 57 kroner. Hvor mange kroner mindre har Hilde enn Magnus?", "real_answer": "3", "points": 10, "date_created": "2010-10-15 14:01:37"}}, {"pk": 14, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Marthe har 35 kaker. Hun gir bort 10 til Elias. Hvor mange kaker har hun igjen?", "real_answer": "25", "points": 10, "date_created": "2010-10-15 14:02:08"}}, {"pk": 15, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Per har 90 kroner og Lise har 50 kroner. De kj\u00f8per seg en CD til 80 kroner. Hvor mye har de igjen tilsammen?", "real_answer": "60", "points": 20, "date_created": "2010-10-15 14:04:59"}}, {"pk": 16, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "En gutt har en valp. S\u00e5 f\u00e5r han en til. Hvor mange valper har han n\u00e5?", "real_answer": "2", "points": 5, "date_created": "2010-10-15 14:05:36"}}, {"pk": 17, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "\u00c5ge har 5 epler. Han f\u00e5r 3 epler av Ingrid. Hvor mange epler har \u00c5ge til sammen?", "real_answer": "8", "points": 10, "date_created": "2010-10-15 14:06:34"}}, {"pk": 18, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "Tre venner har ni epler. Hvor mange f\u00e5r de hver?", "real_answer": "3", "points": 25, "date_created": "2010-10-15 14:09:36"}}, {"pk": 19, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Petter f\u00e5r 50 kroner i ukel\u00f8nn. Hvor mye penger f\u00e5r han i l\u00f8pet av 5 uker?", "real_answer": "250", "points": 20, "date_created": "2010-10-15 14:10:47"}}, {"pk": 20, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "En klasse p\u00e5 32 elever skal deles i fire. Hvor mange blir det p\u00e5 hver gruppe?", "real_answer": "8", "points": 30, "date_created": "2010-10-15 14:12:09"}}, {"pk": 21, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Andre trinn p\u00e5 Notodden skole best\u00e5r av tre klasser. Det g\u00e5r 21 elever i hver klasse. Hvor mange elever er det i alt p\u00e5 andre trinn?", "real_answer": "63", "points": 25, "date_created": "2010-10-15 14:14:03"}}, {"pk": 22, "model": "auth.permission", "fields": {"codename": "add_logentry", "name": "Can add log entry", "content_type": 8}}, {"pk": 23, "model": "auth.permission", "fields": {"codename": "change_logentry", "name": "Can change log entry", "content_type": 8}}, {"pk": 24, "model": "auth.permission", "fields": {"codename": "delete_logentry", "name": "Can delete log entry", "content_type": 8}}, {"pk": 4, "model": "auth.permission", "fields": {"codename": "add_group", "name": "Can add group", "content_type": 2}}, {"pk": 5, "model": "auth.permission", "fields": {"codename": "change_group", "name": "Can change group", "content_type": 2}}, {"pk": 6, "model": "auth.permission", "fields": {"codename": "delete_group", "name": "Can delete group", "content_type": 2}}, {"pk": 10, "model": "auth.permission", "fields": {"codename": "add_message", "name": "Can add message", "content_type": 4}}, {"pk": 11, "model": "auth.permission", "fields": {"codename": "change_message", "name": "Can change message", "content_type": 4}}, {"pk": 12, "model": "auth.permission", "fields": {"codename": "delete_message", "name": "Can delete message", "content_type": 4}}, {"pk": 1, "model": "auth.permission", "fields": {"codename": "add_permission", "name": "Can add permission", "content_type": 1}}, {"pk": 2, "model": "auth.permission", "fields": {"codename": "change_permission", "name": "Can change permission", "content_type": 1}}, {"pk": 3, "model": "auth.permission", "fields": {"codename": "delete_permission", "name": "Can delete permission", "content_type": 1}}, {"pk": 7, "model": "auth.permission", "fields": {"codename": "add_user", "name": "Can add user", "content_type": 3}}, {"pk": 8, "model": "auth.permission", "fields": {"codename": "change_user", "name": "Can change user", "content_type": 3}}, {"pk": 9, "model": "auth.permission", "fields": {"codename": "delete_user", "name": "Can delete user", "content_type": 3}}, {"pk": 13, "model": "auth.permission", "fields": {"codename": "add_contenttype", "name": "Can add content type", "content_type": 5}}, {"pk": 14, "model": "auth.permission", "fields": {"codename": "change_contenttype", "name": "Can change content type", "content_type": 5}}, {"pk": 15, "model": "auth.permission", "fields": {"codename": "delete_contenttype", "name": "Can delete content type", "content_type": 5}}, {"pk": 40, "model": "auth.permission", "fields": {"codename": "add_hint", "name": "Can add hint", "content_type": 14}}, {"pk": 41, "model": "auth.permission", "fields": {"codename": "change_hint", "name": "Can change hint", "content_type": 14}}, {"pk": 42, "model": "auth.permission", "fields": {"codename": "delete_hint", "name": "Can delete hint", "content_type": 14}}, {"pk": 31, "model": "auth.permission", "fields": {"codename": "add_question", "name": "Can add question", "content_type": 11}}, {"pk": 32, "model": "auth.permission", "fields": {"codename": "change_question", "name": "Can change question", "content_type": 11}}, {"pk": 33, "model": "auth.permission", "fields": {"codename": "delete_question", "name": "Can delete question", "content_type": 11}}, {"pk": 37, "model": "auth.permission", "fields": {"codename": "add_result", "name": "Can add result", "content_type": 13}}, {"pk": 38, "model": "auth.permission", "fields": {"codename": "change_result", "name": "Can change result", "content_type": 13}}, {"pk": 39, "model": "auth.permission", "fields": {"codename": "delete_result", "name": "Can delete result", "content_type": 13}}, {"pk": 28, "model": "auth.permission", "fields": {"codename": "add_room", "name": "Can add room", "content_type": 10}}, {"pk": 29, "model": "auth.permission", "fields": {"codename": "change_room", "name": "Can change room", "content_type": 10}}, {"pk": 30, "model": "auth.permission", "fields": {"codename": "delete_room", "name": "Can delete room", "content_type": 10}}, {"pk": 34, "model": "auth.permission", "fields": {"codename": "add_turn", "name": "Can add turn", "content_type": 12}}, {"pk": 35, "model": "auth.permission", "fields": {"codename": "change_turn", "name": "Can change turn", "content_type": 12}}, {"pk": 36, "model": "auth.permission", "fields": {"codename": "delete_turn", "name": "Can delete turn", "content_type": 12}}, {"pk": 25, "model": "auth.permission", "fields": {"codename": "add_userprofile", "name": "Can add user profile", "content_type": 9}}, {"pk": 26, "model": "auth.permission", "fields": {"codename": "change_userprofile", "name": "Can change user profile", "content_type": 9}}, {"pk": 27, "model": "auth.permission", "fields": {"codename": "delete_userprofile", "name": "Can delete user profile", "content_type": 9}}, {"pk": 16, "model": "auth.permission", "fields": {"codename": "add_session", "name": "Can add session", "content_type": 6}}, {"pk": 17, "model": "auth.permission", "fields": {"codename": "change_session", "name": "Can change session", "content_type": 6}}, {"pk": 18, "model": "auth.permission", "fields": {"codename": "delete_session", "name": "Can delete session", "content_type": 6}}, {"pk": 19, "model": "auth.permission", "fields": {"codename": "add_site", "name": "Can add site", "content_type": 7}}, {"pk": 20, "model": "auth.permission", "fields": {"codename": "change_site", "name": "Can change site", "content_type": 7}}, {"pk": 21, "model": "auth.permission", "fields": {"codename": "delete_site", "name": "Can delete site", "content_type": 7}}, {"pk": 1, "model": "auth.user", "fields": {"username": "test", "first_name": "Eric", "last_name": "Cartman", "is_active": true, "is_superuser": true, "is_staff": true, "last_login": "2010-11-01 11:55:26", "groups": [], "user_permissions": [], "password": "sha1$59aea$c0f29c76f430fb25c1f93856b104a222232a1324", "email": "[email protected]", "date_joined": "2010-10-15 10:35:58"}}, {"pk": 3, "model": "auth.user", "fields": {"username": "test2", "first_name": "Kenny", "last_name": "McCormick", "is_active": true, "is_superuser": false, "is_staff": false, "last_login": "2010-11-01 09:15:57", "groups": [], "user_permissions": [], "password": "sha1$16b8e$dfbb0e995fee7d96474b15d46e4329c60ee1d045", "email": "[email protected]", "date_joined": "2010-11-01 09:15:57"}}] \ No newline at end of file +[{"pk": 22, "model": "auth.permission", "fields": {"codename": "add_logentry", "name": "Can add log entry", "content_type": 8}}, {"pk": 23, "model": "auth.permission", "fields": {"codename": "change_logentry", "name": "Can change log entry", "content_type": 8}}, {"pk": 24, "model": "auth.permission", "fields": {"codename": "delete_logentry", "name": "Can delete log entry", "content_type": 8}}, {"pk": 4, "model": "auth.permission", "fields": {"codename": "add_group", "name": "Can add group", "content_type": 2}}, {"pk": 5, "model": "auth.permission", "fields": {"codename": "change_group", "name": "Can change group", "content_type": 2}}, {"pk": 6, "model": "auth.permission", "fields": {"codename": "delete_group", "name": "Can delete group", "content_type": 2}}, {"pk": 10, "model": "auth.permission", "fields": {"codename": "add_message", "name": "Can add message", "content_type": 4}}, {"pk": 11, "model": "auth.permission", "fields": {"codename": "change_message", "name": "Can change message", "content_type": 4}}, {"pk": 12, "model": "auth.permission", "fields": {"codename": "delete_message", "name": "Can delete message", "content_type": 4}}, {"pk": 1, "model": "auth.permission", "fields": {"codename": "add_permission", "name": "Can add permission", "content_type": 1}}, {"pk": 2, "model": "auth.permission", "fields": {"codename": "change_permission", "name": "Can change permission", "content_type": 1}}, {"pk": 3, "model": "auth.permission", "fields": {"codename": "delete_permission", "name": "Can delete permission", "content_type": 1}}, {"pk": 7, "model": "auth.permission", "fields": {"codename": "add_user", "name": "Can add user", "content_type": 3}}, {"pk": 8, "model": "auth.permission", "fields": {"codename": "change_user", "name": "Can change user", "content_type": 3}}, {"pk": 9, "model": "auth.permission", "fields": {"codename": "delete_user", "name": "Can delete user", "content_type": 3}}, {"pk": 13, "model": "auth.permission", "fields": {"codename": "add_contenttype", "name": "Can add content type", "content_type": 5}}, {"pk": 14, "model": "auth.permission", "fields": {"codename": "change_contenttype", "name": "Can change content type", "content_type": 5}}, {"pk": 15, "model": "auth.permission", "fields": {"codename": "delete_contenttype", "name": "Can delete content type", "content_type": 5}}, {"pk": 40, "model": "auth.permission", "fields": {"codename": "add_hint", "name": "Can add hint", "content_type": 14}}, {"pk": 41, "model": "auth.permission", "fields": {"codename": "change_hint", "name": "Can change hint", "content_type": 14}}, {"pk": 42, "model": "auth.permission", "fields": {"codename": "delete_hint", "name": "Can delete hint", "content_type": 14}}, {"pk": 31, "model": "auth.permission", "fields": {"codename": "add_question", "name": "Can add question", "content_type": 11}}, {"pk": 32, "model": "auth.permission", "fields": {"codename": "change_question", "name": "Can change question", "content_type": 11}}, {"pk": 33, "model": "auth.permission", "fields": {"codename": "delete_question", "name": "Can delete question", "content_type": 11}}, {"pk": 37, "model": "auth.permission", "fields": {"codename": "add_result", "name": "Can add result", "content_type": 13}}, {"pk": 38, "model": "auth.permission", "fields": {"codename": "change_result", "name": "Can change result", "content_type": 13}}, {"pk": 39, "model": "auth.permission", "fields": {"codename": "delete_result", "name": "Can delete result", "content_type": 13}}, {"pk": 28, "model": "auth.permission", "fields": {"codename": "add_room", "name": "Can add room", "content_type": 10}}, {"pk": 29, "model": "auth.permission", "fields": {"codename": "change_room", "name": "Can change room", "content_type": 10}}, {"pk": 30, "model": "auth.permission", "fields": {"codename": "delete_room", "name": "Can delete room", "content_type": 10}}, {"pk": 34, "model": "auth.permission", "fields": {"codename": "add_turn", "name": "Can add turn", "content_type": 12}}, {"pk": 35, "model": "auth.permission", "fields": {"codename": "change_turn", "name": "Can change turn", "content_type": 12}}, {"pk": 36, "model": "auth.permission", "fields": {"codename": "delete_turn", "name": "Can delete turn", "content_type": 12}}, {"pk": 25, "model": "auth.permission", "fields": {"codename": "add_userprofile", "name": "Can add user profile", "content_type": 9}}, {"pk": 26, "model": "auth.permission", "fields": {"codename": "change_userprofile", "name": "Can change user profile", "content_type": 9}}, {"pk": 27, "model": "auth.permission", "fields": {"codename": "delete_userprofile", "name": "Can delete user profile", "content_type": 9}}, {"pk": 16, "model": "auth.permission", "fields": {"codename": "add_session", "name": "Can add session", "content_type": 6}}, {"pk": 17, "model": "auth.permission", "fields": {"codename": "change_session", "name": "Can change session", "content_type": 6}}, {"pk": 18, "model": "auth.permission", "fields": {"codename": "delete_session", "name": "Can delete session", "content_type": 6}}, {"pk": 19, "model": "auth.permission", "fields": {"codename": "add_site", "name": "Can add site", "content_type": 7}}, {"pk": 20, "model": "auth.permission", "fields": {"codename": "change_site", "name": "Can change site", "content_type": 7}}, {"pk": 21, "model": "auth.permission", "fields": {"codename": "delete_site", "name": "Can delete site", "content_type": 7}}, {"pk": 1, "model": "auth.user", "fields": {"username": "test", "first_name": "Eric", "last_name": "Cartman", "is_active": true, "is_superuser": true, "is_staff": true, "last_login": "2010-11-01 11:55:26", "groups": [], "user_permissions": [], "password": "sha1$59aea$c0f29c76f430fb25c1f93856b104a222232a1324", "email": "[email protected]", "date_joined": "2010-10-15 10:35:58"}}, {"pk": 3, "model": "auth.user", "fields": {"username": "test2", "first_name": "Kenny", "last_name": "McCormick", "is_active": true, "is_superuser": false, "is_staff": false, "last_login": "2010-11-01 09:15:57", "groups": [], "user_permissions": [], "password": "sha1$16b8e$dfbb0e995fee7d96474b15d46e4329c60ee1d045", "email": "[email protected]", "date_joined": "2010-11-01 09:15:57"}}, {"pk": "5a51edfd2da6fd1442ecfebe170564ac", "model": "sessions.session", "fields": {"expire_date": "2010-10-29 12:36:30", "session_data": "gAJ9cQEoVQdyb29tX2lkcQJYAQAAADFVEl9hdXRoX3VzZXJfYmFja2VuZHEDVSlkamFuZ28uY29u\ndHJpYi5hdXRoLmJhY2tlbmRzLk1vZGVsQmFja2VuZHEEVQ1fYXV0aF91c2VyX2lkcQVLAXUuYThl\nZjM4YTUyZGIzOTQ4ODE1NzM0MTU1NTc0OWYxZWM=\n"}}, {"pk": "82d8dd22044d3c538a2dfe6dd7a8581e", "model": "sessions.session", "fields": {"expire_date": "2010-10-29 13:56:34", "session_data": "gAJ9cQEoVRJfYXV0aF91c2VyX2JhY2tlbmRxAlUpZGphbmdvLmNvbnRyaWIuYXV0aC5iYWNrZW5k\ncy5Nb2RlbEJhY2tlbmRxA1UNX2F1dGhfdXNlcl9pZHEESwF1LmNhYTgxNjQ5YjIxNjUzMzMyOGQw\nODJlNGY0MDEyZDAy\n"}}, {"pk": "a9e85fb1644846c7cb311646c210fccb", "model": "sessions.session", "fields": {"expire_date": "2010-10-29 14:53:57", "session_data": "gAJ9cQEoVQdyb29tX2lkcQJYAQAAADFVDV9hdXRoX3VzZXJfaWRxA0sBVRJfYXV0aF91c2VyX2Jh\nY2tlbmRxBFUpZGphbmdvLmNvbnRyaWIuYXV0aC5iYWNrZW5kcy5Nb2RlbEJhY2tlbmRxBXUuOWFm\nYjQ4ZmZhZmZmOTM0MjgzYTVmMmE2YWFhZGMzNzY=\n"}}, {"pk": "9144be769c27a17b96e5d9afedea04a7", "model": "sessions.session", "fields": {"expire_date": "2010-11-15 12:05:21", "session_data": "gAJ9cQEoVQdyb29tX2lkcQJYAQAAADFVDV9hdXRoX3VzZXJfaWRxA0sBVRJfYXV0aF91c2VyX2Jh\nY2tlbmRxBFUpZGphbmdvLmNvbnRyaWIuYXV0aC5iYWNrZW5kcy5Nb2RlbEJhY2tlbmRxBXUuOWFm\nYjQ4ZmZhZmZmOTM0MjgzYTVmMmE2YWFhZGMzNzY=\n"}}, {"pk": "4e710015a910ac114305d3df1ff63869", "model": "sessions.session", "fields": {"expire_date": "2010-10-29 14:37:57", "session_data": "gAJ9cQEoVQdyb29tX2lkcQJYAQAAADFVDV9hdXRoX3VzZXJfaWRxA0sBVRJfYXV0aF91c2VyX2Jh\nY2tlbmRxBFUpZGphbmdvLmNvbnRyaWIuYXV0aC5iYWNrZW5kcy5Nb2RlbEJhY2tlbmRxBXUuOWFm\nYjQ4ZmZhZmZmOTM0MjgzYTVmMmE2YWFhZGMzNzY=\n"}}, {"pk": "5c13f19fb0e878c1eae9a43049b738c1", "model": "sessions.session", "fields": {"expire_date": "2010-11-15 11:57:01", "session_data": "gAJ9cQEoVQdyb29tX2lkcQJYAQAAADFVEl9hdXRoX3VzZXJfYmFja2VuZHEDVSlkamFuZ28uY29u\ndHJpYi5hdXRoLmJhY2tlbmRzLk1vZGVsQmFja2VuZHEEVQ1fYXV0aF91c2VyX2lkcQVLAXUuYThl\nZjM4YTUyZGIzOTQ4ODE1NzM0MTU1NTc0OWYxZWM=\n"}}, {"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}, {"pk": 90, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-11-01 12:06:00", "object_repr": "[Addisjon, 2010-11-01 11:29:34] test", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 89, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-11-01 12:00:31", "object_repr": "[Addisjon] How do you like them apples?", "object_id": "2", "change_message": "", "user": 1, "content_type": 14}}, {"pk": 88, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-11-01 11:56:00", "object_repr": "test2", "object_id": "3", "change_message": "Endret username.", "user": 1, "content_type": 3}}, {"pk": 87, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-11-01 11:55:54", "object_repr": "test", "object_id": "1", "change_message": "Endret username.", "user": 1, "content_type": 3}}, {"pk": 86, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-11-01 11:54:50", "object_repr": "[Addisjon] Forestill deg to epler blablabla FFFFFFFFFUUUUU", "object_id": "1", "change_message": "Endret cost.", "user": 1, "content_type": 14}}, {"pk": 84, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-11-01 11:17:45", "object_repr": "[Addisjon, 2010-10-15 14:56:35] ericc", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 85, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-11-01 11:17:45", "object_repr": "[Addisjon, 2010-10-15 14:55:50] ericc", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 80, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-11-01 11:17:44", "object_repr": "[Subtraksjon, 2010-10-19 17:31:02] ericc", "object_id": "6", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 81, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-11-01 11:17:44", "object_repr": "[Addisjon, 2010-10-19 17:30:49] ericc", "object_id": "5", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 82, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-11-01 11:17:44", "object_repr": "[Addisjon, 2010-10-15 14:58:10] ericc", "object_id": "4", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 83, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-11-01 11:17:44", "object_repr": "[Subtraksjon, 2010-10-15 14:56:39] ericc", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 79, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-11-01 11:17:17", "object_repr": "ericc's profile", "object_id": "1", "change_message": "Endret points.", "user": 1, "content_type": 9}}, {"pk": 78, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-11-01 11:16:35", "object_repr": "kennym", "object_id": "3", "change_message": "Endret username, first_name, last_name og email.", "user": 1, "content_type": 3}}, {"pk": 77, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-11-01 11:15:49", "object_repr": "ericc", "object_id": "1", "change_message": "Endret username.", "user": 1, "content_type": 3}}, {"pk": 76, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-11-01 11:15:35", "object_repr": "vegardoj", "object_id": "2", "change_message": "", "user": 1, "content_type": 3}}, {"pk": 75, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-11-01 11:13:40", "object_repr": "[Addisjon] Forestill deg to epler blablabla FFFFFFFFFUUUUU", "object_id": "1", "change_message": "", "user": 1, "content_type": 14}}, {"pk": 74, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-11-01 09:15:57", "object_repr": "test2", "object_id": "3", "change_message": "", "user": 1, "content_type": 3}}, {"pk": 73, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:54:55", "object_repr": "vegardoj's profile", "object_id": "2", "change_message": "", "user": 1, "content_type": 9}}, {"pk": 72, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 14:54:48", "object_repr": "test's profile", "object_id": "1", "change_message": "Endret points.", "user": 1, "content_type": 9}}, {"pk": 71, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:54:25", "object_repr": "[Addisjon, 2010-10-15 14:37:13] test", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 70, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:54:24", "object_repr": "[Addisjon, 2010-10-15 14:53:56] test", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 69, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:37:05", "object_repr": "[Addisjon, 2010-10-15 14:31:24] test", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 68, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:37:04", "object_repr": "[Addisjon, 2010-10-15 14:33:15] test", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 67, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:31:12", "object_repr": "[Subtraksjon, 2010-10-15 14:27:18] test", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 66, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:31:11", "object_repr": "[Addisjon, 2010-10-15 14:29:27] test", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 65, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:12", "object_repr": "[Subtraksjon, 2010-10-15 12:57:40] test", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 57, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Divisjon, 2010-10-15 12:58:59] test", "object_id": "9", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 58, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Divisjon, 2010-10-15 12:58:50] test", "object_id": "8", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 59, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Divisjon, 2010-10-15 12:58:42] test", "object_id": "7", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 60, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Divisjon, 2010-10-15 12:58:34] test", "object_id": "6", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 61, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Divisjon, 2010-10-15 12:58:21] test", "object_id": "5", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 62, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Multiplikasjon, 2010-10-15 12:58:14] test", "object_id": "4", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 63, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Multiplikasjon, 2010-10-15 12:58:02] test", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 64, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Subtraksjon, 2010-10-15 12:57:53] test", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 53, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:10", "object_repr": "[Addisjon, 2010-10-15 14:25:12] test", "object_id": "13", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 54, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:10", "object_repr": "[Addisjon, 2010-10-15 13:50:34] vegardoj", "object_id": "12", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 55, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:10", "object_repr": "[Addisjon, 2010-10-15 13:50:19] vegardoj", "object_id": "11", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 56, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:10", "object_repr": "[Divisjon, 2010-10-15 12:59:04] test", "object_id": "10", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 48, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:19:10", "object_repr": "[Addisjon] Maria har 5 bananer og Per har 3 bananer. Hvor mange bananer har Maria og Per til sammen?", "object_id": "22", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 47, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:14:03", "object_repr": "[Multiplikasjon] Andre trinn p\u00e5 Notodden skole best\u00e5r av tre klasser. Det g\u00e5r 21 elever i hver klasse. Hvor mange elever er det i alt p\u00e5 andre trinn?", "object_id": "21", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 46, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:12:09", "object_repr": "[Divisjon] En klasse p\u00e5 32 elever skal deles i fire. Hvor mange blir det p\u00e5 hver gruppe?", "object_id": "20", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 45, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:10:47", "object_repr": "[Multiplikasjon] Petter f\u00e5r 50 kroner i ukel\u00f8nn. Hvor mye penger f\u00e5r han i l\u00f8pet av 5 uker?", "object_id": "19", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 44, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:09:36", "object_repr": "[Divisjon] Tre venner har ni epler. Hvor mange f\u00e5r de hver?", "object_id": "18", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 43, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:06:34", "object_repr": "[Addisjon] \u00c5ge har 5 epler. Han f\u00e5r 3 epler av Ingrid. Hvor mange epler har \u00c5ge til sammen?", "object_id": "17", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 42, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:05:36", "object_repr": "[Addisjon] En gutt har en valp. S\u00e5 f\u00e5r han en til. Hvor mange valper har han n\u00e5?", "object_id": "16", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 41, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:04:59", "object_repr": "[Subtraksjon] Per har 90 kroner og Lise har 50 kroner. De kj\u00f8per seg en CD til 80 kroner. Hvor mye har de igjen tilsammen?", "object_id": "15", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 40, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:02:08", "object_repr": "[Subtraksjon] Marthe har 35 kaker. Hun gir bort 10 til Elias. Hvor mange kaker har hun igjen?", "object_id": "14", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 39, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:01:37", "object_repr": "[Subtraksjon] Hilde har 54 kroner, og Magnus har 57 kroner. Hvor mange kroner mindre har Hilde enn Magnus?", "object_id": "13", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 52, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 13:59:12", "object_repr": "test's profile", "object_id": "1", "change_message": "Endret points.", "user": 1, "content_type": 9}}, {"pk": 49, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 13:16:53", "object_repr": "test | 2010-10-15 12:51:20.907567 | Divisjon", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 50, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 13:16:53", "object_repr": "test | 2010-10-15 12:50:03.041886 | Divisjon", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 51, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 13:16:53", "object_repr": "test | 2010-10-15 12:49:59.962029 | Addisjon", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 38, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:49:09", "object_repr": "Hva er 9 / 3?", "object_id": "12", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 37, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:48:48", "object_repr": "Hva er 8 / 4?", "object_id": "11", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 36, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:48:27", "object_repr": "Hva er 4 / 2?", "object_id": "10", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 35, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:48:08", "object_repr": "Hva er 10 * 10?", "object_id": "9", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 34, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:47:12", "object_repr": "Hva er 2 * 9?", "object_id": "8", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 33, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:46:59", "object_repr": "Hva er 4 * 4?", "object_id": "7", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 32, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:46:01", "object_repr": "example.com", "object_id": "1", "change_message": "", "user": 1, "content_type": 7}}, {"pk": 26, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 11:04:16.476584 | Addisjon", "object_id": "6", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 27, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:59:38.586859 | Addisjon", "object_id": "5", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 28, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:59:11.658703 | Addisjon", "object_id": "4", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 29, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:58:25.267152 | Addisjon", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 30, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:57:45.110544 | Addisjon", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 31, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:57:16.340061 | Addisjon", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 19, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 12:40:51.846371 | Addisjon", "object_id": "13", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 20, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 12:36:11.859253 | Addisjon", "object_id": "12", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 21, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 12:24:23.680071 | Subtraksjon", "object_id": "11", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 22, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:49:13.174200 | Addisjon", "object_id": "10", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 23, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:06:46.026789 | Addisjon", "object_id": "9", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 24, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:05:58.137954 | Addisjon", "object_id": "8", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 25, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:04:57.168726 | Addisjon", "object_id": "7", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 18, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 12:45:14", "object_repr": "test", "object_id": "1", "change_message": "Endret first_name og last_name.", "user": 1, "content_type": 3}}, {"pk": 17, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 12:44:51", "object_repr": "test", "object_id": "1", "change_message": "Endret first_name og last_name.", "user": 1, "content_type": 3}}, {"pk": 16, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:25:25", "object_repr": "Hva 34-5?", "object_id": "6", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 15, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:25:09", "object_repr": "Hva er 200-100", "object_id": "5", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 14, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:25:00", "object_repr": "Hva 10 - 3?", "object_id": "4", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 9, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:45:55.770004 | Addisjon", "object_id": "5", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 10, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:45:25.432687 | Addisjon", "object_id": "4", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 11, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:43:06.129923 | Addisjon", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 12, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:40:22.639628 | Addisjon", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 13, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:38:05 | Addisjon", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 8, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 10:39:54", "object_repr": "test | 2010-10-15 10:38:05 | Addisjon", "object_id": "1", "change_message": "Endret date_end og complete.", "user": 1, "content_type": 12}}, {"pk": 7, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:37:50", "object_repr": "Hva er 125+125?", "object_id": "3", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 6, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:37:30", "object_repr": "Hva er 50+23?", "object_id": "2", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 5, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:37:14", "object_repr": "Hva er 2 + 2?", "object_id": "1", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 4, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:54", "object_repr": "Divisjon", "object_id": "4", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 3, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:47", "object_repr": "Multiplikasjon", "object_id": "3", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 2, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:37", "object_repr": "Subtraksjon", "object_id": "2", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 1, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:25", "object_repr": "Addisjon", "object_id": "1", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 1, "model": "main.userprofile", "fields": {"points": 15, "user": 1}}, {"pk": 2, "model": "main.userprofile", "fields": {"points": 50, "user": 3}}, {"pk": 1, "model": "main.room", "fields": {"required_points": 0, "name": "Addisjon", "description": "Addere tall"}}, {"pk": 2, "model": "main.room", "fields": {"required_points": 100, "name": "Subtraksjon", "description": "Subtrahere tall"}}, {"pk": 3, "model": "main.room", "fields": {"required_points": 200, "name": "Multiplikasjon", "description": "Multiplisere tall"}}, {"pk": 4, "model": "main.room", "fields": {"required_points": 300, "name": "Divisjon", "description": "Dividere tall"}}, {"pk": 1, "model": "main.hint", "fields": {"text": "Forestill deg to epler blablabla FFFFFFFFFUUUUU", "cost": 30, "room": 1}}, {"pk": 2, "model": "main.hint", "fields": {"text": "How do you like them apples?", "cost": 25, "room": 1}}, {"pk": 1, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "Hva er 2 + 2?", "real_answer": "4", "points": 10, "date_created": "2010-10-15 10:37:14"}}, {"pk": 2, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "Hva er 50+23?", "real_answer": "73", "points": 14, "date_created": "2010-10-15 10:37:30"}}, {"pk": 3, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "Hva er 125+125?", "real_answer": "250", "points": 16, "date_created": "2010-10-15 10:37:50"}}, {"pk": 4, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Hva 10 - 3?", "real_answer": "7", "points": 21, "date_created": "2010-10-15 12:25:00"}}, {"pk": 5, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Hva er 200-100", "real_answer": "100", "points": 26, "date_created": "2010-10-15 12:25:09"}}, {"pk": 6, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Hva 34-5?", "real_answer": "29", "points": 28, "date_created": "2010-10-15 12:25:25"}}, {"pk": 7, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Hva er 4 * 4?", "real_answer": "16", "points": 32, "date_created": "2010-10-15 12:46:59"}}, {"pk": 8, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Hva er 2 * 9?", "real_answer": "18", "points": 25, "date_created": "2010-10-15 12:47:12"}}, {"pk": 9, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Hva er 10 * 10?", "real_answer": "100", "points": 27, "date_created": "2010-10-15 12:48:08"}}, {"pk": 10, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "Hva er 4 / 2?", "real_answer": "2", "points": 42, "date_created": "2010-10-15 12:48:27"}}, {"pk": 11, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "Hva er 8 / 4?", "real_answer": "2", "points": 46, "date_created": "2010-10-15 12:48:48"}}, {"pk": 12, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "Hva er 9 / 3?", "real_answer": "3", "points": 48, "date_created": "2010-10-15 12:49:09"}}, {"pk": 13, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Hilde har 54 kroner, og Magnus har 57 kroner. Hvor mange kroner mindre har Hilde enn Magnus?", "real_answer": "3", "points": 10, "date_created": "2010-10-15 14:01:37"}}, {"pk": 14, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Marthe har 35 kaker. Hun gir bort 10 til Elias. Hvor mange kaker har hun igjen?", "real_answer": "25", "points": 10, "date_created": "2010-10-15 14:02:08"}}, {"pk": 15, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Per har 90 kroner og Lise har 50 kroner. De kj\u00f8per seg en CD til 80 kroner. Hvor mye har de igjen tilsammen?", "real_answer": "60", "points": 20, "date_created": "2010-10-15 14:04:59"}}, {"pk": 16, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "En gutt har en valp. S\u00e5 f\u00e5r han en til. Hvor mange valper har han n\u00e5?", "real_answer": "2", "points": 5, "date_created": "2010-10-15 14:05:36"}}, {"pk": 17, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "\u00c5ge har 5 epler. Han f\u00e5r 3 epler av Ingrid. Hvor mange epler har \u00c5ge til sammen?", "real_answer": "8", "points": 10, "date_created": "2010-10-15 14:06:34"}}, {"pk": 18, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "Tre venner har ni epler. Hvor mange f\u00e5r de hver?", "real_answer": "3", "points": 25, "date_created": "2010-10-15 14:09:36"}}, {"pk": 19, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Petter f\u00e5r 50 kroner i ukel\u00f8nn. Hvor mye penger f\u00e5r han i l\u00f8pet av 5 uker?", "real_answer": "250", "points": 20, "date_created": "2010-10-15 14:10:47"}}, {"pk": 20, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "En klasse p\u00e5 32 elever skal deles i fire. Hvor mange blir det p\u00e5 hver gruppe?", "real_answer": "8", "points": 30, "date_created": "2010-10-15 14:12:09"}}, {"pk": 21, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Andre trinn p\u00e5 Notodden skole best\u00e5r av tre klasser. Det g\u00e5r 21 elever i hver klasse. Hvor mange elever er det i alt p\u00e5 andre trinn?", "real_answer": "63", "points": 25, "date_created": "2010-10-15 14:14:03"}}] \ No newline at end of file
ThomasPedersen/mattespill
6123fbde5bf3edf3753c86862c4164c8490cd8ca
Added view for buying hints.
diff --git a/main/models.py b/main/models.py index 916d985..22bdc3c 100644 --- a/main/models.py +++ b/main/models.py @@ -1,69 +1,69 @@ from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) points = models.IntegerField(default=50, null=True) def __unicode__(self): return "%s's profile" % self.user def groups(self): return self.user.groups.all() def create_user_profile(sender, instance, created, **kwargs): if created: profile, created = UserProfile.objects.get_or_create(user=instance) post_save.connect(create_user_profile, sender=User) class Room(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=300) required_points = models.IntegerField() def __unicode__(self): return self.name class Hint(models.Model): text = models.TextField() - cost = models.IntegerField() + cost = models.IntegerField(default=0) room = models.ForeignKey(Room) def __unicode__(self): return '[%s] %s' % (self.room, self.text) class Question(models.Model): question = models.CharField(max_length=200) # Set to current date when object is created date_created = models.DateTimeField(auto_now_add=True) real_answer = models.CharField(max_length=100) author = models.ForeignKey(User) room = models.ForeignKey(Room) points = models.IntegerField() def __unicode__(self): return '[%s] %s' % (self.room, self.question) class Turn(models.Model): date_start = models.DateTimeField() date_end = models.DateTimeField(null=True) user = models.ForeignKey(User) room = models.ForeignKey(Room) complete = models.BooleanField(default=False) total_points = models.IntegerField(default=0) # Use result_set here to access associated # results def __unicode__(self): return '[%s, %s] %s' % (self.room, self.date_start.strftime('%Y-%m-%d %H:%M:%S'), self.user.username) class Result(models.Model): index = models.IntegerField() question = models.ForeignKey(Question) answer = models.CharField(max_length=200, blank=True) turn = models.ForeignKey(Turn) # Order by index field class Meta: ordering = ('index', ) diff --git a/main/views.py b/main/views.py index 14f7957..3c2eb95 100644 --- a/main/views.py +++ b/main/views.py @@ -1,165 +1,165 @@ # -*- coding: utf-8 -*- from django.template import RequestContext, Context, loader from django.utils import simplejson from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden from django.shortcuts import render_to_response, get_object_or_404 from django.contrib import auth from django.contrib.auth.decorators import login_required from django.core import serializers from datetime import datetime from mattespill.main.models import Question, Room, Turn, Result, UserProfile, Hint from mattespill.main.forms import SignupForm import json login_url = '/login/' def index(request): if request.user.is_authenticated(): rooms = Room.objects.all() return render_to_response('home.html', {'user': request.user, 'home': True, \ 'rooms': rooms}) else: return HttpResponseRedirect(login_url) def room(request, room_id): if request.user.is_authenticated(): sess_room_id = request.session.get('room_id', None) if not sess_room_id or sess_room_id != room_id: room = get_object_or_404(Room, pk=room_id) else: room = get_object_or_404(Room, pk=sess_room_id) # If user does not have enough points to access room, # we redirect to index if request.user.get_profile().points < room.required_points: return HttpResponseRedirect('/') request.session['room_id'] = room_id turn_exists = False try: t = Turn.objects.get(room=room, user=request.user, complete=False) turn_exists = True except Turn.DoesNotExist: t = Turn(date_start=datetime.now(), date_end=None, user=request.user, room=room) t.save() # Fetch 10 random questions for the given room questions = Question.objects.filter(room=room).order_by('?')[:10] # Add Result objects (question and answer pairs) for each question i = 1 # Sequence number for each question for q in questions: result = Result(question=q, turn=t, index=i) result.save() i += 1 previous_turns = Turn.objects.filter(room=room, user=request.user, complete=True).\ order_by('-date_start').order_by('-total_points').all() return render_to_response('room.html', {'turn_exists': turn_exists, 'turn': t, \ 'user': request.user, 'previous_turns': previous_turns}) else: return HttpResponseRedirect(login_url) def logout(request): auth.logout(request) return HttpResponseRedirect('/') def buyhint(request): if request.user.is_authenticated(): # Get a random hint room_id = request.session.get('room_id', None) if room_id: hint = Hint.objects.filter(room=room_id).order_by('?')[:1] # Subtract points from user profile = request.user.get_profile() - profile.points -= hint.cost + profile.points -= hint[0].cost profile.save() # Return json response - return HttpResponse(json.dumps({'points': profile.points, 'hint': hint.text}), \ + return HttpResponse(json.dumps({'points': profile.points, 'hint': hint[0].text}), \ mimetype='application/json') else: return HttpResponseForbidden() def stats(request): if request.user.is_authenticated(): # Get max 10 users ordered by points desc users = UserProfile.objects.order_by('-points')[:10] return render_to_response('stats.html', {'user': request.user, 'users': users}) else: return HttpResponseRedirect(login_url) def question(request): if request.user.is_authenticated(): room_id = request.session.get('room_id', None) if room_id: try: turn = Turn.objects.get(room=room_id, user=request.user, complete=False) except Turn.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) try: # The Meta.ordering defined in model will sort # the result ascending on Result.index result = Result.objects.filter(turn=turn, answer='')[:1] if not result: return render_to_response('room.html', {'turn': turn, 'user': request.user}) num_questions = Result.objects.filter(turn=turn).count() return render_to_response('question.html', {'user': request.user,'turn': turn, 'result': result[0], \ 'num_questions': num_questions, 'room_id': room_id}) except Result.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) else: return HttpResponseRedirect(login_url) def answer(request): if request.user.is_authenticated() and request.method == 'POST': room_id = request.session.get('room_id', None) if room_id and 'answer' in request.POST: given_answer = request.POST['answer'].strip() user = request.user t = get_object_or_404(Turn, room=room_id, user=user, complete=False) count = Result.objects.filter(turn=t).count() result = Result.objects.filter(turn=t, answer='')[0] try: if result.index < count: index = result.index + 1 question = Result.objects.get(turn=t, index=index).question.question else: index = -1 # No more questions question = None t.complete = True t.save() correct = given_answer == result.question.real_answer if correct: # Give user some points user.get_profile().points += result.question.points t.total_points += result.question.points else: # For wrong answer users lose (question points / 2) penalty = result.question.points / 2 user.get_profile().points -= penalty t.total_points -= penalty t.save() user.get_profile().save() result.answer = given_answer result.save() return HttpResponse(json.dumps({'correct': correct, 'index': index, \ 'question': question, 'points': user.get_profile().points}), \ mimetype='application/json') except Result.DoesNotExist as e: return HttpResponse(e) else: return HttpResponseRedirect(login_url) def signup(request): if request.method == 'POST': form = SignupForm(data=request.POST) if form.is_valid(): form.save(); return HttpResponseRedirect('/') else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request)) else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request)) diff --git a/urls.py b/urls.py index 46bc9aa..b76ab1c 100644 --- a/urls.py +++ b/urls.py @@ -1,24 +1,25 @@ from django.conf.urls.defaults import * from django.conf import settings # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^$', 'mattespill.main.views.index'), #(r'^question/(?P<question_id>\d+)/$', 'mattespill.main.views.questions'), (r'^login/$', 'django.contrib.auth.views.login'), (r'^logout/$', 'mattespill.main.views.logout'), (r'^room/(?P<room_id>\d+)/$', 'mattespill.main.views.room'), (r'^question/$', 'mattespill.main.views.question'), (r'^answer/$', 'mattespill.main.views.answer'), (r'^signup/$', 'mattespill.main.views.signup'), (r'^stats/$', 'mattespill.main.views.stats'), + (r'^buyhint/$', 'mattespill.main.views.buyhint'), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), # Hack to server static files (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_DOC_ROOT}), )
ThomasPedersen/mattespill
53cceafa9a8d611352a729be346f611a89743572
Added view for buying hints. Added cost to hint model
diff --git a/main/models.py b/main/models.py index 2fb7637..916d985 100644 --- a/main/models.py +++ b/main/models.py @@ -1,68 +1,69 @@ from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) points = models.IntegerField(default=50, null=True) def __unicode__(self): return "%s's profile" % self.user def groups(self): return self.user.groups.all() def create_user_profile(sender, instance, created, **kwargs): if created: profile, created = UserProfile.objects.get_or_create(user=instance) post_save.connect(create_user_profile, sender=User) class Room(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=300) required_points = models.IntegerField() def __unicode__(self): return self.name class Hint(models.Model): text = models.TextField() + cost = models.IntegerField() room = models.ForeignKey(Room) def __unicode__(self): return '[%s] %s' % (self.room, self.text) class Question(models.Model): question = models.CharField(max_length=200) # Set to current date when object is created date_created = models.DateTimeField(auto_now_add=True) real_answer = models.CharField(max_length=100) author = models.ForeignKey(User) room = models.ForeignKey(Room) points = models.IntegerField() def __unicode__(self): return '[%s] %s' % (self.room, self.question) class Turn(models.Model): date_start = models.DateTimeField() date_end = models.DateTimeField(null=True) user = models.ForeignKey(User) room = models.ForeignKey(Room) complete = models.BooleanField(default=False) total_points = models.IntegerField(default=0) # Use result_set here to access associated # results def __unicode__(self): return '[%s, %s] %s' % (self.room, self.date_start.strftime('%Y-%m-%d %H:%M:%S'), self.user.username) class Result(models.Model): index = models.IntegerField() question = models.ForeignKey(Question) answer = models.CharField(max_length=200, blank=True) turn = models.ForeignKey(Turn) # Order by index field class Meta: ordering = ('index', ) diff --git a/main/views.py b/main/views.py index 17eadca..14f7957 100644 --- a/main/views.py +++ b/main/views.py @@ -1,149 +1,165 @@ # -*- coding: utf-8 -*- from django.template import RequestContext, Context, loader from django.utils import simplejson -from django.http import HttpResponse -from django.http import HttpResponseRedirect +from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden from django.shortcuts import render_to_response, get_object_or_404 from django.contrib import auth from django.contrib.auth.decorators import login_required from django.core import serializers from datetime import datetime -from mattespill.main.models import Question, Room, Turn, Result, UserProfile +from mattespill.main.models import Question, Room, Turn, Result, UserProfile, Hint from mattespill.main.forms import SignupForm import json login_url = '/login/' def index(request): if request.user.is_authenticated(): rooms = Room.objects.all() return render_to_response('home.html', {'user': request.user, 'home': True, \ 'rooms': rooms}) else: return HttpResponseRedirect(login_url) def room(request, room_id): if request.user.is_authenticated(): sess_room_id = request.session.get('room_id', None) if not sess_room_id or sess_room_id != room_id: room = get_object_or_404(Room, pk=room_id) else: room = get_object_or_404(Room, pk=sess_room_id) # If user does not have enough points to access room, # we redirect to index if request.user.get_profile().points < room.required_points: return HttpResponseRedirect('/') request.session['room_id'] = room_id turn_exists = False try: t = Turn.objects.get(room=room, user=request.user, complete=False) turn_exists = True except Turn.DoesNotExist: t = Turn(date_start=datetime.now(), date_end=None, user=request.user, room=room) t.save() # Fetch 10 random questions for the given room questions = Question.objects.filter(room=room).order_by('?')[:10] # Add Result objects (question and answer pairs) for each question i = 1 # Sequence number for each question for q in questions: result = Result(question=q, turn=t, index=i) result.save() i += 1 previous_turns = Turn.objects.filter(room=room, user=request.user, complete=True).\ order_by('-date_start').order_by('-total_points').all() return render_to_response('room.html', {'turn_exists': turn_exists, 'turn': t, \ 'user': request.user, 'previous_turns': previous_turns}) else: return HttpResponseRedirect(login_url) def logout(request): auth.logout(request) return HttpResponseRedirect('/') +def buyhint(request): + if request.user.is_authenticated(): + # Get a random hint + room_id = request.session.get('room_id', None) + if room_id: + hint = Hint.objects.filter(room=room_id).order_by('?')[:1] + # Subtract points from user + profile = request.user.get_profile() + profile.points -= hint.cost + profile.save() + # Return json response + return HttpResponse(json.dumps({'points': profile.points, 'hint': hint.text}), \ + mimetype='application/json') + else: + return HttpResponseForbidden() + def stats(request): if request.user.is_authenticated(): # Get max 10 users ordered by points desc users = UserProfile.objects.order_by('-points')[:10] return render_to_response('stats.html', {'user': request.user, 'users': users}) else: return HttpResponseRedirect(login_url) def question(request): if request.user.is_authenticated(): room_id = request.session.get('room_id', None) if room_id: try: turn = Turn.objects.get(room=room_id, user=request.user, complete=False) except Turn.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) try: # The Meta.ordering defined in model will sort # the result ascending on Result.index result = Result.objects.filter(turn=turn, answer='')[:1] if not result: return render_to_response('room.html', {'turn': turn, 'user': request.user}) num_questions = Result.objects.filter(turn=turn).count() return render_to_response('question.html', {'user': request.user,'turn': turn, 'result': result[0], \ 'num_questions': num_questions, 'room_id': room_id}) except Result.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) else: return HttpResponseRedirect(login_url) def answer(request): if request.user.is_authenticated() and request.method == 'POST': room_id = request.session.get('room_id', None) if room_id and 'answer' in request.POST: given_answer = request.POST['answer'].strip() user = request.user t = get_object_or_404(Turn, room=room_id, user=user, complete=False) count = Result.objects.filter(turn=t).count() result = Result.objects.filter(turn=t, answer='')[0] try: if result.index < count: index = result.index + 1 question = Result.objects.get(turn=t, index=index).question.question else: index = -1 # No more questions question = None t.complete = True t.save() correct = given_answer == result.question.real_answer if correct: # Give user some points user.get_profile().points += result.question.points t.total_points += result.question.points else: # For wrong answer users lose (question points / 2) penalty = result.question.points / 2 user.get_profile().points -= penalty t.total_points -= penalty t.save() user.get_profile().save() result.answer = given_answer result.save() return HttpResponse(json.dumps({'correct': correct, 'index': index, \ - 'question': question, 'points': user.get_profile().points})) + 'question': question, 'points': user.get_profile().points}), \ + mimetype='application/json') except Result.DoesNotExist as e: return HttpResponse(e) else: return HttpResponseRedirect(login_url) def signup(request): if request.method == 'POST': form = SignupForm(data=request.POST) if form.is_valid(): form.save(); return HttpResponseRedirect('/') else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request)) else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request))
ThomasPedersen/mattespill
fbb8a3046c02212b38d5189e4b8ffba11c9e5c95
pedobear
diff --git a/main/media/images/hintbear.png b/main/media/images/hintbear.png new file mode 100644 index 0000000..b3ccf7f Binary files /dev/null and b/main/media/images/hintbear.png differ diff --git a/main/media/question.js b/main/media/question.js index 17c46b3..44f7928 100644 --- a/main/media/question.js +++ b/main/media/question.js @@ -1,47 +1,73 @@ +var bearTimer; + +function showBear() { + $('#hintbear').show().animate({ + opacity: 1, + marginRight: '0em', + }, 1000, function() { + $('#hintbear .dialogbox').fadeIn(500); + }); +} +function startBear() { + bearTimer = setTimeout(showBear, 1000); +} +function stopBear() { + if (bearTimer != null) + clearTimeout(bearTimer); +} + $(function() { $('.start_button').click(function() { if ($.trim($('input[name=answer]').val()) == '') { alert('Du må skrive inn noe!'); $('input[name=answer]').val(''); return; } + + startBear(); + $.ajax({ type: 'POST', url: '/answer/', dataType: 'json', data: {answer: $('input[name=answer]').val()}, success: function(data, textStatus) { $('#num_points').text(data.points); if (data.correct) { $('#wrong_answer').hide(); $('#correct_answer').fadeIn(); } else { $('#correct_answer').hide(); $('#wrong_answer').fadeIn(); } if (data.index < 0) { $('#question_wrapper').remove(); $('#finished_wrapper').show(); } else { $('input[name=answer]').val('').focus(); $('#question_index').text(data.index); $('#question_text').text(data.question); } }, error: function(XMLHttpRequest, textStatus) { alert('Det oppstod en feil'); } }); }); $('#answer_form').submit(function() { $('.simple_button').click(); return false; }); $('input[name=answer]').focus(); + startBear(); + + $('#hintbear').click(function() { + alert('aaaaahh'); + }); }); \ No newline at end of file diff --git a/main/templates/outer.html b/main/templates/outer.html index f79bdda..cd08431 100644 --- a/main/templates/outer.html +++ b/main/templates/outer.html @@ -1,80 +1,82 @@ <!DOCTYPE html> <html lang="no"> <head> <meta charset="utf-8" /> <title>Mattespill</title> <link rel="stylesheet" href="/media/main.css" type="text/css" /> + <!-- http://graphicmaniacs.com/note/cross-browser-border-radius-solution-with-example/ --> + <!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]--> <!--[if lte IE 7]><script src="js/IE8.js" type="text/javascript"></script><![endif]--> <!--[if lt IE 7]><link rel="stylesheet" type="text/css" media="all" href="css/ie6.css"/><![endif]--> <script src="/media/jquery-1.4.2.min.js" type="text/javascript"></script> <script src="/media/main.js" type="text/javascript"></script> <style type="text/css"> #header { {% if turn.room.id == 1 %} background-color: #76ce76; border-bottom: .15em solid #60A860; {% else %} {% if turn.room.id == 2 %} background-color: #dddd51; border-bottom: .15em solid #C2C247; {% else %} {% if turn.room.id == 3 %} background-color: #eca657; border-bottom: .15em solid #C28847; {% else %} {% if turn.room.id == 4 %} background-color: #ec5757; border-bottom: .15em solid #C94A4A; {% else %} background-color: #627AAD; border-bottom: .15em solid #1D4088; {% endif %} {% endif %} {% endif %} {% endif %} } #page_content { {% if turn.room.id == 1 %} border: .5em solid #60A860; {% else %} {% if turn.room.id == 2 %} border: .5em solid #C2C247; {% else %} {% if turn.room.id == 3 %} border: .5em solid #C28847; {% else %} {% if turn.room.id == 4 %} border: .5em solid #C94A4A; {% else %} border: .5em solid #1D4088; {% endif %}{% endif %}{% endif %}{% endif %} border-top: none; } </style> {% block head %}{% endblock %} </head> <body> <div id="wrapper"> <div id="header"> <table id="headertable"> <tr> {% if user.is_authenticated %} <td>{{ user.first_name }} {{ user.last_name }} ({{ user.username }}) {% for g in user.get_profile.groups %} - {{ g.name }} {% endfor %} </td> <td class="align_center">Gullmynter: <span id="num_points">{{ user.get_profile.points }}</span></td> <td class="align_right"><a href="/logout">Avslutt spillet</a></td> {% else %} <td class="align_center">Logg inn for å spille mattespillet.</td> {% endif %} </tr> </table> </div> <div id="page_content"> {% block content %}{% endblock %} </div> </div> </body> </html> diff --git a/main/templates/question.html b/main/templates/question.html index c8eb651..7c5fd62 100644 --- a/main/templates/question.html +++ b/main/templates/question.html @@ -1,67 +1,98 @@ {% extends "outer.html" %} {% block head %} <style type="text/css"> #correct_answer { background-color: #afa; } #wrong_answer { background-color: #fcc; } #correct_answer, #wrong_answer { display: none; padding: .3em; -moz-border-radius: .3em; -webkit-border-radius: .3em; border-radius: .3em; } #question_text { font-size: 1.5em; } #finished_wrapper { display: none; } input[name=answer] { font-size: 1.5em; padding: .5em; border: .2em solid #325193; background-color: #f2f2f2; margin: .5em 0; -moz-border-radius: .5em; -webkit-border-radius: .5em; border-radius: .5em; -text-shadow: #bbb 1px 1px 3px; -webkit-box-shadow: 0 0 .7em #bbb; -moz-box-shadow: 0 0 .7em #bbb; box-shadow: 0 0 .7em #bbb; } +#hintbear { + cursor: pointer; + float: right; + position: relative; + + display: none; + opacity: 0; + margin-right: -7em; +} +#hintbear img { + width: 10em; +} +#hintbear .dialogbox { + display: none; + position: absolute; + left: -9em; + top: 0em; + + padding: .5em; + border: .2em solid #000; + background-color: #fff; + -webkit-box-shadow: 0 0 1em #888; + -moz-box-shadow: 0 0 1em #888; + box-shadow: 0 0 1em #888; + -moz-border-radius: 1em; + -webkit-border-radius: 1em; + border-radius: 1em; +} </style> <script src="/media/question.js" type="text/javascript"></script> {% endblock %} {% block content %} +<div id="hintbear"><div class="dialogbox">Har du lyst p&aring; hjelp?<br />Klikk p&aring; meg!</div><img alt="Hintbj&oslash;rnen" src="/media/images/hintbear.png" /></div> + + <h1>Sp&oslash;rsm&aring;l <span id="question_index">{{ result.index }}</span> av {{ num_questions }}</h1> <p id="correct_answer">Du svarte riktig p&aring; forrige oppgave.</p> <p id="wrong_answer">Feil svar p&aring; forrige oppgave.</p> <div id="question_wrapper"> <p id="question_text">{{ result.question.question}}</p> <form id="answer_form" action="" method="post"> <input type="text" name="answer" autocomplete="off" /> <p class="start_button_container"><span class="start_button simple_button">Svar</span></p></p> </form> <p class="back_button"><a href="/room/{{ room_id }}/">G&aring; tilbake til rommet</a></p> </div> <div id="finished_wrapper"> <p>Du er ferdig med dette fors&oslash;ket!</p> <p class="start_button_container"><span class="simple_button"><a href="/room/{{ room_id }}/">Tilbake til rommet!</a></span></p> </div> {% endblock %}
ThomasPedersen/mattespill
cb233ace729fae2f293c2b72ace91e6a9930138b
Cleanup (comments etc.)
diff --git a/main/views.py b/main/views.py index 82044b9..17eadca 100644 --- a/main/views.py +++ b/main/views.py @@ -1,151 +1,149 @@ # -*- coding: utf-8 -*- from django.template import RequestContext, Context, loader from django.utils import simplejson from django.http import HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import render_to_response, get_object_or_404 from django.contrib import auth from django.contrib.auth.decorators import login_required from django.core import serializers from datetime import datetime from mattespill.main.models import Question, Room, Turn, Result, UserProfile from mattespill.main.forms import SignupForm import json login_url = '/login/' def index(request): if request.user.is_authenticated(): rooms = Room.objects.all() return render_to_response('home.html', {'user': request.user, 'home': True, \ 'rooms': rooms}) else: return HttpResponseRedirect(login_url) def room(request, room_id): if request.user.is_authenticated(): sess_room_id = request.session.get('room_id', None) if not sess_room_id or sess_room_id != room_id: room = get_object_or_404(Room, pk=room_id) else: room = get_object_or_404(Room, pk=sess_room_id) # If user does not have enough points to access room, # we redirect to index if request.user.get_profile().points < room.required_points: return HttpResponseRedirect('/') request.session['room_id'] = room_id turn_exists = False try: t = Turn.objects.get(room=room, user=request.user, complete=False) turn_exists = True except Turn.DoesNotExist: t = Turn(date_start=datetime.now(), date_end=None, user=request.user, room=room) t.save() # Fetch 10 random questions for the given room questions = Question.objects.filter(room=room).order_by('?')[:10] # Add Result objects (question and answer pairs) for each question i = 1 # Sequence number for each question for q in questions: result = Result(question=q, turn=t, index=i) result.save() i += 1 previous_turns = Turn.objects.filter(room=room, user=request.user, complete=True).\ order_by('-date_start').order_by('-total_points').all() return render_to_response('room.html', {'turn_exists': turn_exists, 'turn': t, \ 'user': request.user, 'previous_turns': previous_turns}) else: return HttpResponseRedirect(login_url) def logout(request): auth.logout(request) return HttpResponseRedirect('/') def stats(request): if request.user.is_authenticated(): # Get max 10 users ordered by points desc users = UserProfile.objects.order_by('-points')[:10] return render_to_response('stats.html', {'user': request.user, 'users': users}) else: return HttpResponseRedirect(login_url) def question(request): if request.user.is_authenticated(): room_id = request.session.get('room_id', None) if room_id: try: turn = Turn.objects.get(room=room_id, user=request.user, complete=False) except Turn.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) try: # The Meta.ordering defined in model will sort # the result ascending on Result.index result = Result.objects.filter(turn=turn, answer='')[:1] if not result: return render_to_response('room.html', {'turn': turn, 'user': request.user}) num_questions = Result.objects.filter(turn=turn).count() return render_to_response('question.html', {'user': request.user,'turn': turn, 'result': result[0], \ 'num_questions': num_questions, 'room_id': room_id}) except Result.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) else: return HttpResponseRedirect(login_url) def answer(request): if request.user.is_authenticated() and request.method == 'POST': room_id = request.session.get('room_id', None) if room_id and 'answer' in request.POST: given_answer = request.POST['answer'].strip() user = request.user t = get_object_or_404(Turn, room=room_id, user=user, complete=False) count = Result.objects.filter(turn=t).count() result = Result.objects.filter(turn=t, answer='')[0] try: - #r = Result.objects.filter(turn=t, answer='') if result.index < count: index = result.index + 1 question = Result.objects.get(turn=t, index=index).question.question else: index = -1 # No more questions question = None t.complete = True t.save() correct = given_answer == result.question.real_answer if correct: # Give user some points user.get_profile().points += result.question.points t.total_points += result.question.points else: - # For wrong answer users looses question points / 2 + # For wrong answer users lose (question points / 2) penalty = result.question.points / 2 user.get_profile().points -= penalty t.total_points -= penalty t.save() user.get_profile().save() result.answer = given_answer result.save() return HttpResponse(json.dumps({'correct': correct, 'index': index, \ 'question': question, 'points': user.get_profile().points})) except Result.DoesNotExist as e: return HttpResponse(e) else: return HttpResponseRedirect(login_url) def signup(request): if request.method == 'POST': form = SignupForm(data=request.POST) if form.is_valid(): form.save(); return HttpResponseRedirect('/') else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request)) else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request)) -
ThomasPedersen/mattespill
b9bf43ea1e0f1b15b1a1e56deffb8be37f8342ea
Added model for hints. Updated initial data.
diff --git a/initial_data.json b/initial_data.json index 03a7c65..ad62339 100644 --- a/initial_data.json +++ b/initial_data.json @@ -1 +1 @@ -[{"pk": 5, "model": "contenttypes.contenttype", "fields": {"model": "contenttype", "name": "content type", "app_label": "contenttypes"}}, {"pk": 2, "model": "contenttypes.contenttype", "fields": {"model": "group", "name": "group", "app_label": "auth"}}, {"pk": 8, "model": "contenttypes.contenttype", "fields": {"model": "logentry", "name": "log entry", "app_label": "admin"}}, {"pk": 4, "model": "contenttypes.contenttype", "fields": {"model": "message", "name": "message", "app_label": "auth"}}, {"pk": 1, "model": "contenttypes.contenttype", "fields": {"model": "permission", "name": "permission", "app_label": "auth"}}, {"pk": 11, "model": "contenttypes.contenttype", "fields": {"model": "question", "name": "question", "app_label": "main"}}, {"pk": 13, "model": "contenttypes.contenttype", "fields": {"model": "result", "name": "result", "app_label": "main"}}, {"pk": 10, "model": "contenttypes.contenttype", "fields": {"model": "room", "name": "room", "app_label": "main"}}, {"pk": 6, "model": "contenttypes.contenttype", "fields": {"model": "session", "name": "session", "app_label": "sessions"}}, {"pk": 7, "model": "contenttypes.contenttype", "fields": {"model": "site", "name": "site", "app_label": "sites"}}, {"pk": 12, "model": "contenttypes.contenttype", "fields": {"model": "turn", "name": "turn", "app_label": "main"}}, {"pk": 3, "model": "contenttypes.contenttype", "fields": {"model": "user", "name": "user", "app_label": "auth"}}, {"pk": 9, "model": "contenttypes.contenttype", "fields": {"model": "userprofile", "name": "user profile", "app_label": "main"}}, {"pk": "5a51edfd2da6fd1442ecfebe170564ac", "model": "sessions.session", "fields": {"expire_date": "2010-10-29 12:36:30", "session_data": "gAJ9cQEoVQdyb29tX2lkcQJYAQAAADFVEl9hdXRoX3VzZXJfYmFja2VuZHEDVSlkamFuZ28uY29u\ndHJpYi5hdXRoLmJhY2tlbmRzLk1vZGVsQmFja2VuZHEEVQ1fYXV0aF91c2VyX2lkcQVLAXUuYThl\nZjM4YTUyZGIzOTQ4ODE1NzM0MTU1NTc0OWYxZWM=\n"}}, {"pk": "82d8dd22044d3c538a2dfe6dd7a8581e", "model": "sessions.session", "fields": {"expire_date": "2010-10-29 13:56:34", "session_data": "gAJ9cQEoVRJfYXV0aF91c2VyX2JhY2tlbmRxAlUpZGphbmdvLmNvbnRyaWIuYXV0aC5iYWNrZW5k\ncy5Nb2RlbEJhY2tlbmRxA1UNX2F1dGhfdXNlcl9pZHEESwF1LmNhYTgxNjQ5YjIxNjUzMzMyOGQw\nODJlNGY0MDEyZDAy\n"}}, {"pk": "4e710015a910ac114305d3df1ff63869", "model": "sessions.session", "fields": {"expire_date": "2010-10-29 14:37:57", "session_data": "gAJ9cQEoVQdyb29tX2lkcQJYAQAAADFVDV9hdXRoX3VzZXJfaWRxA0sBVRJfYXV0aF91c2VyX2Jh\nY2tlbmRxBFUpZGphbmdvLmNvbnRyaWIuYXV0aC5iYWNrZW5kcy5Nb2RlbEJhY2tlbmRxBXUuOWFm\nYjQ4ZmZhZmZmOTM0MjgzYTVmMmE2YWFhZGMzNzY=\n"}}, {"pk": "a9e85fb1644846c7cb311646c210fccb", "model": "sessions.session", "fields": {"expire_date": "2010-10-29 14:53:57", "session_data": "gAJ9cQEoVQdyb29tX2lkcQJYAQAAADFVDV9hdXRoX3VzZXJfaWRxA0sBVRJfYXV0aF91c2VyX2Jh\nY2tlbmRxBFUpZGphbmdvLmNvbnRyaWIuYXV0aC5iYWNrZW5kcy5Nb2RlbEJhY2tlbmRxBXUuOWFm\nYjQ4ZmZhZmZmOTM0MjgzYTVmMmE2YWFhZGMzNzY=\n"}}, {"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}, {"pk": 73, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:54:55", "object_repr": "vegardoj's profile", "object_id": "2", "change_message": "", "user": 1, "content_type": 9}}, {"pk": 72, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 14:54:48", "object_repr": "test's profile", "object_id": "1", "change_message": "Endret points.", "user": 1, "content_type": 9}}, {"pk": 71, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:54:25", "object_repr": "[Addisjon, 2010-10-15 14:37:13] test", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 70, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:54:24", "object_repr": "[Addisjon, 2010-10-15 14:53:56] test", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 69, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:37:05", "object_repr": "[Addisjon, 2010-10-15 14:31:24] test", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 68, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:37:04", "object_repr": "[Addisjon, 2010-10-15 14:33:15] test", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 67, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:31:12", "object_repr": "[Subtraksjon, 2010-10-15 14:27:18] test", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 66, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:31:11", "object_repr": "[Addisjon, 2010-10-15 14:29:27] test", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 65, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:12", "object_repr": "[Subtraksjon, 2010-10-15 12:57:40] test", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 64, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Subtraksjon, 2010-10-15 12:57:53] test", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 63, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Multiplikasjon, 2010-10-15 12:58:02] test", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 62, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Multiplikasjon, 2010-10-15 12:58:14] test", "object_id": "4", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 61, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Divisjon, 2010-10-15 12:58:21] test", "object_id": "5", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 60, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Divisjon, 2010-10-15 12:58:34] test", "object_id": "6", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 59, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Divisjon, 2010-10-15 12:58:42] test", "object_id": "7", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 58, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Divisjon, 2010-10-15 12:58:50] test", "object_id": "8", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 57, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Divisjon, 2010-10-15 12:58:59] test", "object_id": "9", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 56, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:10", "object_repr": "[Divisjon, 2010-10-15 12:59:04] test", "object_id": "10", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 55, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:10", "object_repr": "[Addisjon, 2010-10-15 13:50:19] vegardoj", "object_id": "11", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 54, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:10", "object_repr": "[Addisjon, 2010-10-15 13:50:34] vegardoj", "object_id": "12", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 53, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:10", "object_repr": "[Addisjon, 2010-10-15 14:25:12] test", "object_id": "13", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 48, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:19:10", "object_repr": "[Addisjon] Maria har 5 bananer og Per har 3 bananer. Hvor mange bananer har Maria og Per til sammen?", "object_id": "22", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 47, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:14:03", "object_repr": "[Multiplikasjon] Andre trinn p\u00e5 Notodden skole best\u00e5r av tre klasser. Det g\u00e5r 21 elever i hver klasse. Hvor mange elever er det i alt p\u00e5 andre trinn?", "object_id": "21", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 46, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:12:09", "object_repr": "[Divisjon] En klasse p\u00e5 32 elever skal deles i fire. Hvor mange blir det p\u00e5 hver gruppe?", "object_id": "20", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 45, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:10:47", "object_repr": "[Multiplikasjon] Petter f\u00e5r 50 kroner i ukel\u00f8nn. Hvor mye penger f\u00e5r han i l\u00f8pet av 5 uker?", "object_id": "19", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 44, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:09:36", "object_repr": "[Divisjon] Tre venner har ni epler. Hvor mange f\u00e5r de hver?", "object_id": "18", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 43, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:06:34", "object_repr": "[Addisjon] \u00c5ge har 5 epler. Han f\u00e5r 3 epler av Ingrid. Hvor mange epler har \u00c5ge til sammen?", "object_id": "17", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 42, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:05:36", "object_repr": "[Addisjon] En gutt har en valp. S\u00e5 f\u00e5r han en til. Hvor mange valper har han n\u00e5?", "object_id": "16", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 41, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:04:59", "object_repr": "[Subtraksjon] Per har 90 kroner og Lise har 50 kroner. De kj\u00f8per seg en CD til 80 kroner. Hvor mye har de igjen tilsammen?", "object_id": "15", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 40, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:02:08", "object_repr": "[Subtraksjon] Marthe har 35 kaker. Hun gir bort 10 til Elias. Hvor mange kaker har hun igjen?", "object_id": "14", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 39, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:01:37", "object_repr": "[Subtraksjon] Hilde har 54 kroner, og Magnus har 57 kroner. Hvor mange kroner mindre har Hilde enn Magnus?", "object_id": "13", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 52, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 13:59:12", "object_repr": "test's profile", "object_id": "1", "change_message": "Endret points.", "user": 1, "content_type": 9}}, {"pk": 51, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 13:16:53", "object_repr": "test | 2010-10-15 12:49:59.962029 | Addisjon", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 50, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 13:16:53", "object_repr": "test | 2010-10-15 12:50:03.041886 | Divisjon", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 49, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 13:16:53", "object_repr": "test | 2010-10-15 12:51:20.907567 | Divisjon", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 38, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:49:09", "object_repr": "Hva er 9 / 3?", "object_id": "12", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 37, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:48:48", "object_repr": "Hva er 8 / 4?", "object_id": "11", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 36, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:48:27", "object_repr": "Hva er 4 / 2?", "object_id": "10", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 35, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:48:08", "object_repr": "Hva er 10 * 10?", "object_id": "9", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 34, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:47:12", "object_repr": "Hva er 2 * 9?", "object_id": "8", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 33, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:46:59", "object_repr": "Hva er 4 * 4?", "object_id": "7", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 32, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:46:01", "object_repr": "example.com", "object_id": "1", "change_message": "", "user": 1, "content_type": 7}}, {"pk": 26, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 11:04:16.476584 | Addisjon", "object_id": "6", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 27, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:59:38.586859 | Addisjon", "object_id": "5", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 28, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:59:11.658703 | Addisjon", "object_id": "4", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 29, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:58:25.267152 | Addisjon", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 30, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:57:45.110544 | Addisjon", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 31, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:57:16.340061 | Addisjon", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 19, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 12:40:51.846371 | Addisjon", "object_id": "13", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 20, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 12:36:11.859253 | Addisjon", "object_id": "12", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 21, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 12:24:23.680071 | Subtraksjon", "object_id": "11", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 22, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:49:13.174200 | Addisjon", "object_id": "10", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 23, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:06:46.026789 | Addisjon", "object_id": "9", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 24, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:05:58.137954 | Addisjon", "object_id": "8", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 25, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:04:57.168726 | Addisjon", "object_id": "7", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 18, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 12:45:14", "object_repr": "test", "object_id": "1", "change_message": "Endret first_name og last_name.", "user": 1, "content_type": 3}}, {"pk": 17, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 12:44:51", "object_repr": "test", "object_id": "1", "change_message": "Endret first_name og last_name.", "user": 1, "content_type": 3}}, {"pk": 16, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:25:25", "object_repr": "Hva 34-5?", "object_id": "6", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 15, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:25:09", "object_repr": "Hva er 200-100", "object_id": "5", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 14, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:25:00", "object_repr": "Hva 10 - 3?", "object_id": "4", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 9, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:45:55.770004 | Addisjon", "object_id": "5", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 10, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:45:25.432687 | Addisjon", "object_id": "4", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 11, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:43:06.129923 | Addisjon", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 12, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:40:22.639628 | Addisjon", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 13, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:38:05 | Addisjon", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 8, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 10:39:54", "object_repr": "test | 2010-10-15 10:38:05 | Addisjon", "object_id": "1", "change_message": "Endret date_end og complete.", "user": 1, "content_type": 12}}, {"pk": 7, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:37:50", "object_repr": "Hva er 125+125?", "object_id": "3", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 6, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:37:30", "object_repr": "Hva er 50+23?", "object_id": "2", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 5, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:37:14", "object_repr": "Hva er 2 + 2?", "object_id": "1", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 4, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:54", "object_repr": "Divisjon", "object_id": "4", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 3, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:47", "object_repr": "Multiplikasjon", "object_id": "3", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 2, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:37", "object_repr": "Subtraksjon", "object_id": "2", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 1, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:25", "object_repr": "Addisjon", "object_id": "1", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 1, "model": "main.userprofile", "fields": {"points": 50, "user": 1}}, {"pk": 1, "model": "main.room", "fields": {"required_points": 0, "name": "Addisjon", "description": "Addere tall"}}, {"pk": 2, "model": "main.room", "fields": {"required_points": 100, "name": "Subtraksjon", "description": "Subtrahere tall"}}, {"pk": 3, "model": "main.room", "fields": {"required_points": 200, "name": "Multiplikasjon", "description": "Multiplisere tall"}}, {"pk": 4, "model": "main.room", "fields": {"required_points": 300, "name": "Divisjon", "description": "Dividere tall"}}, {"pk": 1, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "Hva er 2 + 2?", "real_answer": "4", "points": 10, "date_created": "2010-10-15 10:37:14"}}, {"pk": 2, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "Hva er 50+23?", "real_answer": "73", "points": 14, "date_created": "2010-10-15 10:37:30"}}, {"pk": 3, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "Hva er 125+125?", "real_answer": "250", "points": 16, "date_created": "2010-10-15 10:37:50"}}, {"pk": 4, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Hva 10 - 3?", "real_answer": "7", "points": 21, "date_created": "2010-10-15 12:25:00"}}, {"pk": 5, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Hva er 200-100", "real_answer": "100", "points": 26, "date_created": "2010-10-15 12:25:09"}}, {"pk": 6, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Hva 34-5?", "real_answer": "29", "points": 28, "date_created": "2010-10-15 12:25:25"}}, {"pk": 7, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Hva er 4 * 4?", "real_answer": "16", "points": 32, "date_created": "2010-10-15 12:46:59"}}, {"pk": 8, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Hva er 2 * 9?", "real_answer": "18", "points": 25, "date_created": "2010-10-15 12:47:12"}}, {"pk": 9, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Hva er 10 * 10?", "real_answer": "100", "points": 27, "date_created": "2010-10-15 12:48:08"}}, {"pk": 10, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "Hva er 4 / 2?", "real_answer": "2", "points": 42, "date_created": "2010-10-15 12:48:27"}}, {"pk": 11, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "Hva er 8 / 4?", "real_answer": "2", "points": 46, "date_created": "2010-10-15 12:48:48"}}, {"pk": 12, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "Hva er 9 / 3?", "real_answer": "3", "points": 48, "date_created": "2010-10-15 12:49:09"}}, {"pk": 13, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Hilde har 54 kroner, og Magnus har 57 kroner. Hvor mange kroner mindre har Hilde enn Magnus?", "real_answer": "3", "points": 10, "date_created": "2010-10-15 14:01:37"}}, {"pk": 14, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Marthe har 35 kaker. Hun gir bort 10 til Elias. Hvor mange kaker har hun igjen?", "real_answer": "25", "points": 10, "date_created": "2010-10-15 14:02:08"}}, {"pk": 15, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Per har 90 kroner og Lise har 50 kroner. De kj\u00f8per seg en CD til 80 kroner. Hvor mye har de igjen tilsammen?", "real_answer": "60", "points": 20, "date_created": "2010-10-15 14:04:59"}}, {"pk": 16, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "En gutt har en valp. S\u00e5 f\u00e5r han en til. Hvor mange valper har han n\u00e5?", "real_answer": "2", "points": 5, "date_created": "2010-10-15 14:05:36"}}, {"pk": 17, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "\u00c5ge har 5 epler. Han f\u00e5r 3 epler av Ingrid. Hvor mange epler har \u00c5ge til sammen?", "real_answer": "8", "points": 10, "date_created": "2010-10-15 14:06:34"}}, {"pk": 18, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "Tre venner har ni epler. Hvor mange f\u00e5r de hver?", "real_answer": "3", "points": 25, "date_created": "2010-10-15 14:09:36"}}, {"pk": 19, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Petter f\u00e5r 50 kroner i ukel\u00f8nn. Hvor mye penger f\u00e5r han i l\u00f8pet av 5 uker?", "real_answer": "250", "points": 20, "date_created": "2010-10-15 14:10:47"}}, {"pk": 20, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "En klasse p\u00e5 32 elever skal deles i fire. Hvor mange blir det p\u00e5 hver gruppe?", "real_answer": "8", "points": 30, "date_created": "2010-10-15 14:12:09"}}, {"pk": 21, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Andre trinn p\u00e5 Notodden skole best\u00e5r av tre klasser. Det g\u00e5r 21 elever i hver klasse. Hvor mange elever er det i alt p\u00e5 andre trinn?", "real_answer": "63", "points": 25, "date_created": "2010-10-15 14:14:03"}}, {"pk": 22, "model": "main.question", "fields": {"room": 1, "author": 2, "question": "Maria har 5 bananer og Per har 3 bananer. Hvor mange bananer har Maria og Per til sammen?", "real_answer": "8", "points": 10, "date_created": "2010-10-15 14:19:10"}}, {"pk": 22, "model": "auth.permission", "fields": {"codename": "add_logentry", "name": "Can add log entry", "content_type": 8}}, {"pk": 23, "model": "auth.permission", "fields": {"codename": "change_logentry", "name": "Can change log entry", "content_type": 8}}, {"pk": 24, "model": "auth.permission", "fields": {"codename": "delete_logentry", "name": "Can delete log entry", "content_type": 8}}, {"pk": 4, "model": "auth.permission", "fields": {"codename": "add_group", "name": "Can add group", "content_type": 2}}, {"pk": 5, "model": "auth.permission", "fields": {"codename": "change_group", "name": "Can change group", "content_type": 2}}, {"pk": 6, "model": "auth.permission", "fields": {"codename": "delete_group", "name": "Can delete group", "content_type": 2}}, {"pk": 10, "model": "auth.permission", "fields": {"codename": "add_message", "name": "Can add message", "content_type": 4}}, {"pk": 11, "model": "auth.permission", "fields": {"codename": "change_message", "name": "Can change message", "content_type": 4}}, {"pk": 12, "model": "auth.permission", "fields": {"codename": "delete_message", "name": "Can delete message", "content_type": 4}}, {"pk": 1, "model": "auth.permission", "fields": {"codename": "add_permission", "name": "Can add permission", "content_type": 1}}, {"pk": 2, "model": "auth.permission", "fields": {"codename": "change_permission", "name": "Can change permission", "content_type": 1}}, {"pk": 3, "model": "auth.permission", "fields": {"codename": "delete_permission", "name": "Can delete permission", "content_type": 1}}, {"pk": 7, "model": "auth.permission", "fields": {"codename": "add_user", "name": "Can add user", "content_type": 3}}, {"pk": 8, "model": "auth.permission", "fields": {"codename": "change_user", "name": "Can change user", "content_type": 3}}, {"pk": 9, "model": "auth.permission", "fields": {"codename": "delete_user", "name": "Can delete user", "content_type": 3}}, {"pk": 13, "model": "auth.permission", "fields": {"codename": "add_contenttype", "name": "Can add content type", "content_type": 5}}, {"pk": 14, "model": "auth.permission", "fields": {"codename": "change_contenttype", "name": "Can change content type", "content_type": 5}}, {"pk": 15, "model": "auth.permission", "fields": {"codename": "delete_contenttype", "name": "Can delete content type", "content_type": 5}}, {"pk": 31, "model": "auth.permission", "fields": {"codename": "add_question", "name": "Can add question", "content_type": 11}}, {"pk": 32, "model": "auth.permission", "fields": {"codename": "change_question", "name": "Can change question", "content_type": 11}}, {"pk": 33, "model": "auth.permission", "fields": {"codename": "delete_question", "name": "Can delete question", "content_type": 11}}, {"pk": 37, "model": "auth.permission", "fields": {"codename": "add_result", "name": "Can add result", "content_type": 13}}, {"pk": 38, "model": "auth.permission", "fields": {"codename": "change_result", "name": "Can change result", "content_type": 13}}, {"pk": 39, "model": "auth.permission", "fields": {"codename": "delete_result", "name": "Can delete result", "content_type": 13}}, {"pk": 28, "model": "auth.permission", "fields": {"codename": "add_room", "name": "Can add room", "content_type": 10}}, {"pk": 29, "model": "auth.permission", "fields": {"codename": "change_room", "name": "Can change room", "content_type": 10}}, {"pk": 30, "model": "auth.permission", "fields": {"codename": "delete_room", "name": "Can delete room", "content_type": 10}}, {"pk": 34, "model": "auth.permission", "fields": {"codename": "add_turn", "name": "Can add turn", "content_type": 12}}, {"pk": 35, "model": "auth.permission", "fields": {"codename": "change_turn", "name": "Can change turn", "content_type": 12}}, {"pk": 36, "model": "auth.permission", "fields": {"codename": "delete_turn", "name": "Can delete turn", "content_type": 12}}, {"pk": 25, "model": "auth.permission", "fields": {"codename": "add_userprofile", "name": "Can add user profile", "content_type": 9}}, {"pk": 26, "model": "auth.permission", "fields": {"codename": "change_userprofile", "name": "Can change user profile", "content_type": 9}}, {"pk": 27, "model": "auth.permission", "fields": {"codename": "delete_userprofile", "name": "Can delete user profile", "content_type": 9}}, {"pk": 16, "model": "auth.permission", "fields": {"codename": "add_session", "name": "Can add session", "content_type": 6}}, {"pk": 17, "model": "auth.permission", "fields": {"codename": "change_session", "name": "Can change session", "content_type": 6}}, {"pk": 18, "model": "auth.permission", "fields": {"codename": "delete_session", "name": "Can delete session", "content_type": 6}}, {"pk": 19, "model": "auth.permission", "fields": {"codename": "add_site", "name": "Can add site", "content_type": 7}}, {"pk": 20, "model": "auth.permission", "fields": {"codename": "change_site", "name": "Can change site", "content_type": 7}}, {"pk": 21, "model": "auth.permission", "fields": {"codename": "delete_site", "name": "Can delete site", "content_type": 7}}, {"pk": 1, "model": "auth.user", "fields": {"username": "test", "first_name": "Eric", "last_name": "Cartman", "is_active": true, "is_superuser": true, "is_staff": true, "last_login": "2010-10-15 14:36:09", "groups": [], "user_permissions": [], "password": "sha1$59aea$c0f29c76f430fb25c1f93856b104a222232a1324", "email": "[email protected]", "date_joined": "2010-10-15 10:35:58"}}, {"pk": 2, "model": "auth.user", "fields": {"username": "vegardoj", "first_name": "Vegard ", "last_name": "Test", "is_active": true, "is_superuser": false, "is_staff": false, "last_login": "2010-10-15 13:50:10", "groups": [], "user_permissions": [], "password": "sha1$154b3$75b41062e9d9059a52ebc2fb3e41769a8e8e6fbf", "email": "[email protected]", "date_joined": "2010-10-15 13:50:07"}}] \ No newline at end of file +[{"pk": 5, "model": "contenttypes.contenttype", "fields": {"model": "contenttype", "name": "content type", "app_label": "contenttypes"}}, {"pk": 2, "model": "contenttypes.contenttype", "fields": {"model": "group", "name": "group", "app_label": "auth"}}, {"pk": 14, "model": "contenttypes.contenttype", "fields": {"model": "hint", "name": "hint", "app_label": "main"}}, {"pk": 8, "model": "contenttypes.contenttype", "fields": {"model": "logentry", "name": "log entry", "app_label": "admin"}}, {"pk": 4, "model": "contenttypes.contenttype", "fields": {"model": "message", "name": "message", "app_label": "auth"}}, {"pk": 1, "model": "contenttypes.contenttype", "fields": {"model": "permission", "name": "permission", "app_label": "auth"}}, {"pk": 11, "model": "contenttypes.contenttype", "fields": {"model": "question", "name": "question", "app_label": "main"}}, {"pk": 13, "model": "contenttypes.contenttype", "fields": {"model": "result", "name": "result", "app_label": "main"}}, {"pk": 10, "model": "contenttypes.contenttype", "fields": {"model": "room", "name": "room", "app_label": "main"}}, {"pk": 6, "model": "contenttypes.contenttype", "fields": {"model": "session", "name": "session", "app_label": "sessions"}}, {"pk": 7, "model": "contenttypes.contenttype", "fields": {"model": "site", "name": "site", "app_label": "sites"}}, {"pk": 12, "model": "contenttypes.contenttype", "fields": {"model": "turn", "name": "turn", "app_label": "main"}}, {"pk": 3, "model": "contenttypes.contenttype", "fields": {"model": "user", "name": "user", "app_label": "auth"}}, {"pk": 9, "model": "contenttypes.contenttype", "fields": {"model": "userprofile", "name": "user profile", "app_label": "main"}}, {"pk": "5a51edfd2da6fd1442ecfebe170564ac", "model": "sessions.session", "fields": {"expire_date": "2010-10-29 12:36:30", "session_data": "gAJ9cQEoVQdyb29tX2lkcQJYAQAAADFVEl9hdXRoX3VzZXJfYmFja2VuZHEDVSlkamFuZ28uY29u\ndHJpYi5hdXRoLmJhY2tlbmRzLk1vZGVsQmFja2VuZHEEVQ1fYXV0aF91c2VyX2lkcQVLAXUuYThl\nZjM4YTUyZGIzOTQ4ODE1NzM0MTU1NTc0OWYxZWM=\n"}}, {"pk": "82d8dd22044d3c538a2dfe6dd7a8581e", "model": "sessions.session", "fields": {"expire_date": "2010-10-29 13:56:34", "session_data": "gAJ9cQEoVRJfYXV0aF91c2VyX2JhY2tlbmRxAlUpZGphbmdvLmNvbnRyaWIuYXV0aC5iYWNrZW5k\ncy5Nb2RlbEJhY2tlbmRxA1UNX2F1dGhfdXNlcl9pZHEESwF1LmNhYTgxNjQ5YjIxNjUzMzMyOGQw\nODJlNGY0MDEyZDAy\n"}}, {"pk": "a9e85fb1644846c7cb311646c210fccb", "model": "sessions.session", "fields": {"expire_date": "2010-10-29 14:53:57", "session_data": "gAJ9cQEoVQdyb29tX2lkcQJYAQAAADFVDV9hdXRoX3VzZXJfaWRxA0sBVRJfYXV0aF91c2VyX2Jh\nY2tlbmRxBFUpZGphbmdvLmNvbnRyaWIuYXV0aC5iYWNrZW5kcy5Nb2RlbEJhY2tlbmRxBXUuOWFm\nYjQ4ZmZhZmZmOTM0MjgzYTVmMmE2YWFhZGMzNzY=\n"}}, {"pk": "9144be769c27a17b96e5d9afedea04a7", "model": "sessions.session", "fields": {"expire_date": "2010-11-15 10:32:20", "session_data": "gAJ9cQEoVQdyb29tX2lkcQJYAQAAADJVDV9hdXRoX3VzZXJfaWRxA0sBVRJfYXV0aF91c2VyX2Jh\nY2tlbmRxBFUpZGphbmdvLmNvbnRyaWIuYXV0aC5iYWNrZW5kcy5Nb2RlbEJhY2tlbmRxBXUuNzBm\nYzhkZGNjYTYyMzBlODBlY2YyODNiMDI2ODZjMDk=\n"}}, {"pk": "4e710015a910ac114305d3df1ff63869", "model": "sessions.session", "fields": {"expire_date": "2010-10-29 14:37:57", "session_data": "gAJ9cQEoVQdyb29tX2lkcQJYAQAAADFVDV9hdXRoX3VzZXJfaWRxA0sBVRJfYXV0aF91c2VyX2Jh\nY2tlbmRxBFUpZGphbmdvLmNvbnRyaWIuYXV0aC5iYWNrZW5kcy5Nb2RlbEJhY2tlbmRxBXUuOWFm\nYjQ4ZmZhZmZmOTM0MjgzYTVmMmE2YWFhZGMzNzY=\n"}}, {"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}, {"pk": 85, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-11-01 11:17:45", "object_repr": "[Addisjon, 2010-10-15 14:55:50] ericc", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 84, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-11-01 11:17:45", "object_repr": "[Addisjon, 2010-10-15 14:56:35] ericc", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 83, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-11-01 11:17:44", "object_repr": "[Subtraksjon, 2010-10-15 14:56:39] ericc", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 82, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-11-01 11:17:44", "object_repr": "[Addisjon, 2010-10-15 14:58:10] ericc", "object_id": "4", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 81, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-11-01 11:17:44", "object_repr": "[Addisjon, 2010-10-19 17:30:49] ericc", "object_id": "5", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 80, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-11-01 11:17:44", "object_repr": "[Subtraksjon, 2010-10-19 17:31:02] ericc", "object_id": "6", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 79, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-11-01 11:17:17", "object_repr": "ericc's profile", "object_id": "1", "change_message": "Endret points.", "user": 1, "content_type": 9}}, {"pk": 78, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-11-01 11:16:35", "object_repr": "kennym", "object_id": "3", "change_message": "Endret username, first_name, last_name og email.", "user": 1, "content_type": 3}}, {"pk": 77, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-11-01 11:15:49", "object_repr": "ericc", "object_id": "1", "change_message": "Endret username.", "user": 1, "content_type": 3}}, {"pk": 76, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-11-01 11:15:35", "object_repr": "vegardoj", "object_id": "2", "change_message": "", "user": 1, "content_type": 3}}, {"pk": 75, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-11-01 11:13:40", "object_repr": "[Addisjon] Forestill deg to epler blablabla FFFFFFFFFUUUUU", "object_id": "1", "change_message": "", "user": 1, "content_type": 14}}, {"pk": 74, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-11-01 09:15:57", "object_repr": "test2", "object_id": "3", "change_message": "", "user": 1, "content_type": 3}}, {"pk": 73, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:54:55", "object_repr": "vegardoj's profile", "object_id": "2", "change_message": "", "user": 1, "content_type": 9}}, {"pk": 72, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 14:54:48", "object_repr": "test's profile", "object_id": "1", "change_message": "Endret points.", "user": 1, "content_type": 9}}, {"pk": 71, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:54:25", "object_repr": "[Addisjon, 2010-10-15 14:37:13] test", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 70, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:54:24", "object_repr": "[Addisjon, 2010-10-15 14:53:56] test", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 69, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:37:05", "object_repr": "[Addisjon, 2010-10-15 14:31:24] test", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 68, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:37:04", "object_repr": "[Addisjon, 2010-10-15 14:33:15] test", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 67, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:31:12", "object_repr": "[Subtraksjon, 2010-10-15 14:27:18] test", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 66, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:31:11", "object_repr": "[Addisjon, 2010-10-15 14:29:27] test", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 65, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:12", "object_repr": "[Subtraksjon, 2010-10-15 12:57:40] test", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 57, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Divisjon, 2010-10-15 12:58:59] test", "object_id": "9", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 58, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Divisjon, 2010-10-15 12:58:50] test", "object_id": "8", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 59, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Divisjon, 2010-10-15 12:58:42] test", "object_id": "7", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 60, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Divisjon, 2010-10-15 12:58:34] test", "object_id": "6", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 61, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Divisjon, 2010-10-15 12:58:21] test", "object_id": "5", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 62, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Multiplikasjon, 2010-10-15 12:58:14] test", "object_id": "4", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 63, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Multiplikasjon, 2010-10-15 12:58:02] test", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 64, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:11", "object_repr": "[Subtraksjon, 2010-10-15 12:57:53] test", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 53, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:10", "object_repr": "[Addisjon, 2010-10-15 14:25:12] test", "object_id": "13", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 54, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:10", "object_repr": "[Addisjon, 2010-10-15 13:50:34] vegardoj", "object_id": "12", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 55, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:10", "object_repr": "[Addisjon, 2010-10-15 13:50:19] vegardoj", "object_id": "11", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 56, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 14:27:10", "object_repr": "[Divisjon, 2010-10-15 12:59:04] test", "object_id": "10", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 48, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:19:10", "object_repr": "[Addisjon] Maria har 5 bananer og Per har 3 bananer. Hvor mange bananer har Maria og Per til sammen?", "object_id": "22", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 47, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:14:03", "object_repr": "[Multiplikasjon] Andre trinn p\u00e5 Notodden skole best\u00e5r av tre klasser. Det g\u00e5r 21 elever i hver klasse. Hvor mange elever er det i alt p\u00e5 andre trinn?", "object_id": "21", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 46, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:12:09", "object_repr": "[Divisjon] En klasse p\u00e5 32 elever skal deles i fire. Hvor mange blir det p\u00e5 hver gruppe?", "object_id": "20", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 45, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:10:47", "object_repr": "[Multiplikasjon] Petter f\u00e5r 50 kroner i ukel\u00f8nn. Hvor mye penger f\u00e5r han i l\u00f8pet av 5 uker?", "object_id": "19", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 44, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:09:36", "object_repr": "[Divisjon] Tre venner har ni epler. Hvor mange f\u00e5r de hver?", "object_id": "18", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 43, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:06:34", "object_repr": "[Addisjon] \u00c5ge har 5 epler. Han f\u00e5r 3 epler av Ingrid. Hvor mange epler har \u00c5ge til sammen?", "object_id": "17", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 42, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:05:36", "object_repr": "[Addisjon] En gutt har en valp. S\u00e5 f\u00e5r han en til. Hvor mange valper har han n\u00e5?", "object_id": "16", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 41, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:04:59", "object_repr": "[Subtraksjon] Per har 90 kroner og Lise har 50 kroner. De kj\u00f8per seg en CD til 80 kroner. Hvor mye har de igjen tilsammen?", "object_id": "15", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 40, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:02:08", "object_repr": "[Subtraksjon] Marthe har 35 kaker. Hun gir bort 10 til Elias. Hvor mange kaker har hun igjen?", "object_id": "14", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 39, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:01:37", "object_repr": "[Subtraksjon] Hilde har 54 kroner, og Magnus har 57 kroner. Hvor mange kroner mindre har Hilde enn Magnus?", "object_id": "13", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 52, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 13:59:12", "object_repr": "test's profile", "object_id": "1", "change_message": "Endret points.", "user": 1, "content_type": 9}}, {"pk": 49, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 13:16:53", "object_repr": "test | 2010-10-15 12:51:20.907567 | Divisjon", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 50, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 13:16:53", "object_repr": "test | 2010-10-15 12:50:03.041886 | Divisjon", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 51, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 13:16:53", "object_repr": "test | 2010-10-15 12:49:59.962029 | Addisjon", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 38, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:49:09", "object_repr": "Hva er 9 / 3?", "object_id": "12", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 37, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:48:48", "object_repr": "Hva er 8 / 4?", "object_id": "11", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 36, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:48:27", "object_repr": "Hva er 4 / 2?", "object_id": "10", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 35, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:48:08", "object_repr": "Hva er 10 * 10?", "object_id": "9", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 34, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:47:12", "object_repr": "Hva er 2 * 9?", "object_id": "8", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 33, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:46:59", "object_repr": "Hva er 4 * 4?", "object_id": "7", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 32, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:46:01", "object_repr": "example.com", "object_id": "1", "change_message": "", "user": 1, "content_type": 7}}, {"pk": 26, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 11:04:16.476584 | Addisjon", "object_id": "6", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 27, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:59:38.586859 | Addisjon", "object_id": "5", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 28, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:59:11.658703 | Addisjon", "object_id": "4", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 29, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:58:25.267152 | Addisjon", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 30, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:57:45.110544 | Addisjon", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 31, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:57:16.340061 | Addisjon", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 19, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 12:40:51.846371 | Addisjon", "object_id": "13", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 20, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 12:36:11.859253 | Addisjon", "object_id": "12", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 21, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 12:24:23.680071 | Subtraksjon", "object_id": "11", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 22, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:49:13.174200 | Addisjon", "object_id": "10", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 23, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:06:46.026789 | Addisjon", "object_id": "9", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 24, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:05:58.137954 | Addisjon", "object_id": "8", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 25, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:04:57.168726 | Addisjon", "object_id": "7", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 18, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 12:45:14", "object_repr": "test", "object_id": "1", "change_message": "Endret first_name og last_name.", "user": 1, "content_type": 3}}, {"pk": 17, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 12:44:51", "object_repr": "test", "object_id": "1", "change_message": "Endret first_name og last_name.", "user": 1, "content_type": 3}}, {"pk": 16, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:25:25", "object_repr": "Hva 34-5?", "object_id": "6", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 15, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:25:09", "object_repr": "Hva er 200-100", "object_id": "5", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 14, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:25:00", "object_repr": "Hva 10 - 3?", "object_id": "4", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 9, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:45:55.770004 | Addisjon", "object_id": "5", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 10, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:45:25.432687 | Addisjon", "object_id": "4", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 11, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:43:06.129923 | Addisjon", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 12, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:40:22.639628 | Addisjon", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 13, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:38:05 | Addisjon", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 8, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 10:39:54", "object_repr": "test | 2010-10-15 10:38:05 | Addisjon", "object_id": "1", "change_message": "Endret date_end og complete.", "user": 1, "content_type": 12}}, {"pk": 7, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:37:50", "object_repr": "Hva er 125+125?", "object_id": "3", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 6, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:37:30", "object_repr": "Hva er 50+23?", "object_id": "2", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 5, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:37:14", "object_repr": "Hva er 2 + 2?", "object_id": "1", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 4, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:54", "object_repr": "Divisjon", "object_id": "4", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 3, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:47", "object_repr": "Multiplikasjon", "object_id": "3", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 2, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:37", "object_repr": "Subtraksjon", "object_id": "2", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 1, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:25", "object_repr": "Addisjon", "object_id": "1", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 1, "model": "main.userprofile", "fields": {"points": 100, "user": 1}}, {"pk": 2, "model": "main.userprofile", "fields": {"points": 50, "user": 3}}, {"pk": 1, "model": "main.room", "fields": {"required_points": 0, "name": "Addisjon", "description": "Addere tall"}}, {"pk": 2, "model": "main.room", "fields": {"required_points": 100, "name": "Subtraksjon", "description": "Subtrahere tall"}}, {"pk": 3, "model": "main.room", "fields": {"required_points": 200, "name": "Multiplikasjon", "description": "Multiplisere tall"}}, {"pk": 4, "model": "main.room", "fields": {"required_points": 300, "name": "Divisjon", "description": "Dividere tall"}}, {"pk": 1, "model": "main.hint", "fields": {"text": "Forestill deg to epler blablabla FFFFFFFFFUUUUU", "room": 1}}, {"pk": 1, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "Hva er 2 + 2?", "real_answer": "4", "points": 10, "date_created": "2010-10-15 10:37:14"}}, {"pk": 2, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "Hva er 50+23?", "real_answer": "73", "points": 14, "date_created": "2010-10-15 10:37:30"}}, {"pk": 3, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "Hva er 125+125?", "real_answer": "250", "points": 16, "date_created": "2010-10-15 10:37:50"}}, {"pk": 4, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Hva 10 - 3?", "real_answer": "7", "points": 21, "date_created": "2010-10-15 12:25:00"}}, {"pk": 5, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Hva er 200-100", "real_answer": "100", "points": 26, "date_created": "2010-10-15 12:25:09"}}, {"pk": 6, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Hva 34-5?", "real_answer": "29", "points": 28, "date_created": "2010-10-15 12:25:25"}}, {"pk": 7, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Hva er 4 * 4?", "real_answer": "16", "points": 32, "date_created": "2010-10-15 12:46:59"}}, {"pk": 8, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Hva er 2 * 9?", "real_answer": "18", "points": 25, "date_created": "2010-10-15 12:47:12"}}, {"pk": 9, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Hva er 10 * 10?", "real_answer": "100", "points": 27, "date_created": "2010-10-15 12:48:08"}}, {"pk": 10, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "Hva er 4 / 2?", "real_answer": "2", "points": 42, "date_created": "2010-10-15 12:48:27"}}, {"pk": 11, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "Hva er 8 / 4?", "real_answer": "2", "points": 46, "date_created": "2010-10-15 12:48:48"}}, {"pk": 12, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "Hva er 9 / 3?", "real_answer": "3", "points": 48, "date_created": "2010-10-15 12:49:09"}}, {"pk": 13, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Hilde har 54 kroner, og Magnus har 57 kroner. Hvor mange kroner mindre har Hilde enn Magnus?", "real_answer": "3", "points": 10, "date_created": "2010-10-15 14:01:37"}}, {"pk": 14, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Marthe har 35 kaker. Hun gir bort 10 til Elias. Hvor mange kaker har hun igjen?", "real_answer": "25", "points": 10, "date_created": "2010-10-15 14:02:08"}}, {"pk": 15, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Per har 90 kroner og Lise har 50 kroner. De kj\u00f8per seg en CD til 80 kroner. Hvor mye har de igjen tilsammen?", "real_answer": "60", "points": 20, "date_created": "2010-10-15 14:04:59"}}, {"pk": 16, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "En gutt har en valp. S\u00e5 f\u00e5r han en til. Hvor mange valper har han n\u00e5?", "real_answer": "2", "points": 5, "date_created": "2010-10-15 14:05:36"}}, {"pk": 17, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "\u00c5ge har 5 epler. Han f\u00e5r 3 epler av Ingrid. Hvor mange epler har \u00c5ge til sammen?", "real_answer": "8", "points": 10, "date_created": "2010-10-15 14:06:34"}}, {"pk": 18, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "Tre venner har ni epler. Hvor mange f\u00e5r de hver?", "real_answer": "3", "points": 25, "date_created": "2010-10-15 14:09:36"}}, {"pk": 19, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Petter f\u00e5r 50 kroner i ukel\u00f8nn. Hvor mye penger f\u00e5r han i l\u00f8pet av 5 uker?", "real_answer": "250", "points": 20, "date_created": "2010-10-15 14:10:47"}}, {"pk": 20, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "En klasse p\u00e5 32 elever skal deles i fire. Hvor mange blir det p\u00e5 hver gruppe?", "real_answer": "8", "points": 30, "date_created": "2010-10-15 14:12:09"}}, {"pk": 21, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Andre trinn p\u00e5 Notodden skole best\u00e5r av tre klasser. Det g\u00e5r 21 elever i hver klasse. Hvor mange elever er det i alt p\u00e5 andre trinn?", "real_answer": "63", "points": 25, "date_created": "2010-10-15 14:14:03"}}, {"pk": 22, "model": "auth.permission", "fields": {"codename": "add_logentry", "name": "Can add log entry", "content_type": 8}}, {"pk": 23, "model": "auth.permission", "fields": {"codename": "change_logentry", "name": "Can change log entry", "content_type": 8}}, {"pk": 24, "model": "auth.permission", "fields": {"codename": "delete_logentry", "name": "Can delete log entry", "content_type": 8}}, {"pk": 4, "model": "auth.permission", "fields": {"codename": "add_group", "name": "Can add group", "content_type": 2}}, {"pk": 5, "model": "auth.permission", "fields": {"codename": "change_group", "name": "Can change group", "content_type": 2}}, {"pk": 6, "model": "auth.permission", "fields": {"codename": "delete_group", "name": "Can delete group", "content_type": 2}}, {"pk": 10, "model": "auth.permission", "fields": {"codename": "add_message", "name": "Can add message", "content_type": 4}}, {"pk": 11, "model": "auth.permission", "fields": {"codename": "change_message", "name": "Can change message", "content_type": 4}}, {"pk": 12, "model": "auth.permission", "fields": {"codename": "delete_message", "name": "Can delete message", "content_type": 4}}, {"pk": 1, "model": "auth.permission", "fields": {"codename": "add_permission", "name": "Can add permission", "content_type": 1}}, {"pk": 2, "model": "auth.permission", "fields": {"codename": "change_permission", "name": "Can change permission", "content_type": 1}}, {"pk": 3, "model": "auth.permission", "fields": {"codename": "delete_permission", "name": "Can delete permission", "content_type": 1}}, {"pk": 7, "model": "auth.permission", "fields": {"codename": "add_user", "name": "Can add user", "content_type": 3}}, {"pk": 8, "model": "auth.permission", "fields": {"codename": "change_user", "name": "Can change user", "content_type": 3}}, {"pk": 9, "model": "auth.permission", "fields": {"codename": "delete_user", "name": "Can delete user", "content_type": 3}}, {"pk": 13, "model": "auth.permission", "fields": {"codename": "add_contenttype", "name": "Can add content type", "content_type": 5}}, {"pk": 14, "model": "auth.permission", "fields": {"codename": "change_contenttype", "name": "Can change content type", "content_type": 5}}, {"pk": 15, "model": "auth.permission", "fields": {"codename": "delete_contenttype", "name": "Can delete content type", "content_type": 5}}, {"pk": 40, "model": "auth.permission", "fields": {"codename": "add_hint", "name": "Can add hint", "content_type": 14}}, {"pk": 41, "model": "auth.permission", "fields": {"codename": "change_hint", "name": "Can change hint", "content_type": 14}}, {"pk": 42, "model": "auth.permission", "fields": {"codename": "delete_hint", "name": "Can delete hint", "content_type": 14}}, {"pk": 31, "model": "auth.permission", "fields": {"codename": "add_question", "name": "Can add question", "content_type": 11}}, {"pk": 32, "model": "auth.permission", "fields": {"codename": "change_question", "name": "Can change question", "content_type": 11}}, {"pk": 33, "model": "auth.permission", "fields": {"codename": "delete_question", "name": "Can delete question", "content_type": 11}}, {"pk": 37, "model": "auth.permission", "fields": {"codename": "add_result", "name": "Can add result", "content_type": 13}}, {"pk": 38, "model": "auth.permission", "fields": {"codename": "change_result", "name": "Can change result", "content_type": 13}}, {"pk": 39, "model": "auth.permission", "fields": {"codename": "delete_result", "name": "Can delete result", "content_type": 13}}, {"pk": 28, "model": "auth.permission", "fields": {"codename": "add_room", "name": "Can add room", "content_type": 10}}, {"pk": 29, "model": "auth.permission", "fields": {"codename": "change_room", "name": "Can change room", "content_type": 10}}, {"pk": 30, "model": "auth.permission", "fields": {"codename": "delete_room", "name": "Can delete room", "content_type": 10}}, {"pk": 34, "model": "auth.permission", "fields": {"codename": "add_turn", "name": "Can add turn", "content_type": 12}}, {"pk": 35, "model": "auth.permission", "fields": {"codename": "change_turn", "name": "Can change turn", "content_type": 12}}, {"pk": 36, "model": "auth.permission", "fields": {"codename": "delete_turn", "name": "Can delete turn", "content_type": 12}}, {"pk": 25, "model": "auth.permission", "fields": {"codename": "add_userprofile", "name": "Can add user profile", "content_type": 9}}, {"pk": 26, "model": "auth.permission", "fields": {"codename": "change_userprofile", "name": "Can change user profile", "content_type": 9}}, {"pk": 27, "model": "auth.permission", "fields": {"codename": "delete_userprofile", "name": "Can delete user profile", "content_type": 9}}, {"pk": 16, "model": "auth.permission", "fields": {"codename": "add_session", "name": "Can add session", "content_type": 6}}, {"pk": 17, "model": "auth.permission", "fields": {"codename": "change_session", "name": "Can change session", "content_type": 6}}, {"pk": 18, "model": "auth.permission", "fields": {"codename": "delete_session", "name": "Can delete session", "content_type": 6}}, {"pk": 19, "model": "auth.permission", "fields": {"codename": "add_site", "name": "Can add site", "content_type": 7}}, {"pk": 20, "model": "auth.permission", "fields": {"codename": "change_site", "name": "Can change site", "content_type": 7}}, {"pk": 21, "model": "auth.permission", "fields": {"codename": "delete_site", "name": "Can delete site", "content_type": 7}}, {"pk": 1, "model": "auth.user", "fields": {"username": "ericc", "first_name": "Eric", "last_name": "Cartman", "is_active": true, "is_superuser": true, "is_staff": true, "last_login": "2010-10-15 14:36:09", "groups": [], "user_permissions": [], "password": "sha1$59aea$c0f29c76f430fb25c1f93856b104a222232a1324", "email": "[email protected]", "date_joined": "2010-10-15 10:35:58"}}, {"pk": 3, "model": "auth.user", "fields": {"username": "kennym", "first_name": "Kenny", "last_name": "McCormick", "is_active": true, "is_superuser": false, "is_staff": false, "last_login": "2010-11-01 09:15:57", "groups": [], "user_permissions": [], "password": "sha1$16b8e$dfbb0e995fee7d96474b15d46e4329c60ee1d045", "email": "[email protected]", "date_joined": "2010-11-01 09:15:57"}}] \ No newline at end of file diff --git a/main/admin.py b/main/admin.py index d7d79fe..e692f42 100644 --- a/main/admin.py +++ b/main/admin.py @@ -1,12 +1,13 @@ -from mattespill.main.models import Question, Room, Turn, Result, UserProfile +from mattespill.main.models import Question, Room, Turn, Result, UserProfile, Hint from django.contrib import admin class QuestionAdmin(admin.ModelAdmin): fields = ['question', 'real_answer', 'room', 'author', 'points'] admin.site.register(Question, QuestionAdmin) admin.site.register(Result) admin.site.register(Room) admin.site.register(Turn) admin.site.register(UserProfile) +admin.site.register(Hint) diff --git a/main/models.py b/main/models.py index 2340421..2fb7637 100644 --- a/main/models.py +++ b/main/models.py @@ -1,61 +1,68 @@ from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) points = models.IntegerField(default=50, null=True) def __unicode__(self): return "%s's profile" % self.user def groups(self): return self.user.groups.all() def create_user_profile(sender, instance, created, **kwargs): if created: profile, created = UserProfile.objects.get_or_create(user=instance) post_save.connect(create_user_profile, sender=User) class Room(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=300) required_points = models.IntegerField() def __unicode__(self): return self.name +class Hint(models.Model): + text = models.TextField() + room = models.ForeignKey(Room) + + def __unicode__(self): + return '[%s] %s' % (self.room, self.text) + class Question(models.Model): question = models.CharField(max_length=200) # Set to current date when object is created date_created = models.DateTimeField(auto_now_add=True) real_answer = models.CharField(max_length=100) author = models.ForeignKey(User) room = models.ForeignKey(Room) points = models.IntegerField() def __unicode__(self): return '[%s] %s' % (self.room, self.question) class Turn(models.Model): date_start = models.DateTimeField() date_end = models.DateTimeField(null=True) user = models.ForeignKey(User) room = models.ForeignKey(Room) complete = models.BooleanField(default=False) total_points = models.IntegerField(default=0) # Use result_set here to access associated # results def __unicode__(self): return '[%s, %s] %s' % (self.room, self.date_start.strftime('%Y-%m-%d %H:%M:%S'), self.user.username) class Result(models.Model): index = models.IntegerField() question = models.ForeignKey(Question) answer = models.CharField(max_length=200, blank=True) turn = models.ForeignKey(Turn) # Order by index field class Meta: ordering = ('index', )
ThomasPedersen/mattespill
89d73b7002914290d232569dcff2be6fb60a1343
Added a basic stats page.
diff --git a/main/templates/home.html b/main/templates/home.html index 25dc664..9ea61ae 100644 --- a/main/templates/home.html +++ b/main/templates/home.html @@ -1,123 +1,124 @@ {% extends "outer.html" %} {% block head %} <script src="/media/home.js" type="text/javascript"></script> <style type="text/css"> #right_content { /*background-color: #eaeaea; border: .3em solid #ddd;*/ padding: 1em 2em; text-align: center; float: right; } #left_content { padding: .5em 0em; } img#treasure_chest { width: 10em; } #room_box_container a:hover { text-decoration: none; } #room_box_container { width: 27em; height: 27em; } #room_box_container p { color: #fff; text-decoration: none; } #addition_box { background-color: #76ce76; border: .5em solid #60a860; } #subtraction_box { background-color: #dddd51; border: .5em solid #c2c247; float: right; } #multiplication_box { margin-top: 1em; background-color: #eca657; border: .5em solid #c28847; } #division_box { margin-top: 1em; background-color: #ec5757; border: .5em solid #c94a4a; float: right; } .room_box { -moz-border-radius: 1.5em; -webkit-border-radius: 1.5em; border-radius: 1.5em; width: 12em; height: 12em; position: relative; } .restricted_room_msg { position: absolute; bottom: 0; left: 0; right: 0; text-align: center; padding: .4em; color: #fff; -text-shadow: #fff 0 0 1px; background: rgba(0, 0, 0, 0.2); display: none; -moz-border-radius: 1em; -webkit-border-radius: 1em; border-radius: 1em; } .restricted_room_msg > div { opacity: 1; } .room_sign { /*margin-top: -.1em;*/ text-align: center; font-weight: bold; font-size: 10em; color: #fff; } .room_sign a { color: inherit; text-decoration: none; } /* http://robertnyman.com/2010/01/11/css-background-transparency-without-affecting-child-elements-through-rgba-and-filters/ */ </style> {% endblock %} {% block content %} <div id="right_content"> <p class="chest_header">Skattekiste</p> <img id="treasure_chest" src="/media/images/treasurechest.png" alt="skattekiste" /> - <p class="gold_coins">Du har <span class="gold_text"> {{ user.get_profile.points }} </span> gullmynter</p> + <p class="gold_coins">Du har <span class="gold_text"> {{ user.get_profile.points }} </span> gullmynter</p> + <p><a href="/stats/">Vis liste over de beste spillerne</a></p> </div> <div id="left_content"> <h1>Velg ditt rom</h1> <div id="room_box_container"> <div id="subtraction_box" class="room_box"> {% if user.get_profile.points < rooms.1.required_points %}<div class="restricted_room_msg"><div><b>Krav:<br />{{ rooms.1.required_points}} gullmynter!</b></div></div>{% endif %} <div class="room_sign">{% if user.get_profile.points >= rooms.1.required_points %}<a href="/room/2/">{% endif %}&minus;{% if user.get_profile.points >= rooms.1.required_points %}</a>{% endif %}</div> </div></a> <div id="addition_box" class="room_box"> {% if user.get_profile.points < rooms.0.required_points %}<div class="restricted_room_msg"><div><b>Krav:<br />{{ rooms.0.required_points }} gullmynter!</b></div></div>{% endif %} <div class="room_sign">{% if user.get_profile.points >= rooms.0.required_points %}<a href="/room/1/">{% endif %}+{% if user.get_profile.points >= rooms.0.required_points %}</a>{% endif %}</div> </div></a> <div id="division_box" class="room_box"> {% if user.get_profile.points < rooms.3.required_points %}<div class="restricted_room_msg"><div><b>Krav:<br />{{ rooms.3.required_points }} gullmynter!</b></div></div>{% endif %} <div class="room_sign">{% if user.get_profile.points >= rooms.3.required_points %}<a href="/room/4/">{% endif %}&divide;{% if user.get_profile.points >= rooms.3.required_points %}</a>{% endif %}</div> </div></a> <div id="multiplication_box" class="room_box"> {% if user.get_profile.points < rooms.2.required_points %}<div class="restricted_room_msg"><div><b>Krav:<br />{{ rooms.2.required_points }} gullmynter!</b></div></div>{% endif %} <div class="room_sign">{% if user.get_profile.points >= rooms.2.required_points %}<a href="/room/3/">{% endif %}&times;{% if user.get_profile.points >= rooms.2.required_points %}</a>{% endif %}</div> </div></a> </div> </div> <p id="logout_reminder">Husk &aring; <a href="/logout">avslutte spillet</a> n&aring;r du er ferdig!</p> {% endblock %} diff --git a/main/templates/stats.html b/main/templates/stats.html new file mode 100644 index 0000000..e241ff1 --- /dev/null +++ b/main/templates/stats.html @@ -0,0 +1,32 @@ +{% extends "outer.html" %} + +{% block head %} +<style type="text/css"> +table tr.most_points td { + background-color: #aaffaa; +} +</style> +{% endblock %} + +{% block content %} +<h1>Resultater</h1> +<p>Her kan du se en oversikt over de 10 beste spillerne.</p> + +<table class="styled"> + <tr> + <th>Brukernavn</th> + <th>Navn</th> + <th>Antall poeng</th> +</tr> +{% for u in users %} + +<tr{% if forloop.first %} class="most_points"{% endif %}> + <td>{{ u.user.username }}</td> + <td>{{ u.user.first_name }} {{ u.user.last_name }}</td> + <td>{{ u.points }}</td> +</tr> +{% endfor %} +</table> + +<p class="back_button"><a href="/">G&aring; tilbake til hovedsiden</a></p> +{% endblock %} diff --git a/main/views.py b/main/views.py index a6233e6..82044b9 100644 --- a/main/views.py +++ b/main/views.py @@ -1,143 +1,151 @@ # -*- coding: utf-8 -*- from django.template import RequestContext, Context, loader from django.utils import simplejson from django.http import HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import render_to_response, get_object_or_404 from django.contrib import auth from django.contrib.auth.decorators import login_required from django.core import serializers from datetime import datetime -from mattespill.main.models import Question, Room, Turn, Result +from mattespill.main.models import Question, Room, Turn, Result, UserProfile from mattespill.main.forms import SignupForm import json login_url = '/login/' def index(request): if request.user.is_authenticated(): rooms = Room.objects.all() return render_to_response('home.html', {'user': request.user, 'home': True, \ 'rooms': rooms}) else: return HttpResponseRedirect(login_url) def room(request, room_id): if request.user.is_authenticated(): sess_room_id = request.session.get('room_id', None) if not sess_room_id or sess_room_id != room_id: room = get_object_or_404(Room, pk=room_id) else: room = get_object_or_404(Room, pk=sess_room_id) # If user does not have enough points to access room, # we redirect to index if request.user.get_profile().points < room.required_points: return HttpResponseRedirect('/') request.session['room_id'] = room_id turn_exists = False try: t = Turn.objects.get(room=room, user=request.user, complete=False) turn_exists = True except Turn.DoesNotExist: t = Turn(date_start=datetime.now(), date_end=None, user=request.user, room=room) t.save() # Fetch 10 random questions for the given room questions = Question.objects.filter(room=room).order_by('?')[:10] # Add Result objects (question and answer pairs) for each question i = 1 # Sequence number for each question for q in questions: result = Result(question=q, turn=t, index=i) result.save() i += 1 previous_turns = Turn.objects.filter(room=room, user=request.user, complete=True).\ order_by('-date_start').order_by('-total_points').all() return render_to_response('room.html', {'turn_exists': turn_exists, 'turn': t, \ 'user': request.user, 'previous_turns': previous_turns}) else: return HttpResponseRedirect(login_url) def logout(request): auth.logout(request) return HttpResponseRedirect('/') +def stats(request): + if request.user.is_authenticated(): + # Get max 10 users ordered by points desc + users = UserProfile.objects.order_by('-points')[:10] + return render_to_response('stats.html', {'user': request.user, 'users': users}) + else: + return HttpResponseRedirect(login_url) + def question(request): if request.user.is_authenticated(): room_id = request.session.get('room_id', None) if room_id: try: turn = Turn.objects.get(room=room_id, user=request.user, complete=False) except Turn.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) try: # The Meta.ordering defined in model will sort # the result ascending on Result.index result = Result.objects.filter(turn=turn, answer='')[:1] if not result: return render_to_response('room.html', {'turn': turn, 'user': request.user}) num_questions = Result.objects.filter(turn=turn).count() return render_to_response('question.html', {'user': request.user,'turn': turn, 'result': result[0], \ 'num_questions': num_questions, 'room_id': room_id}) except Result.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) else: return HttpResponseRedirect(login_url) def answer(request): if request.user.is_authenticated() and request.method == 'POST': room_id = request.session.get('room_id', None) if room_id and 'answer' in request.POST: given_answer = request.POST['answer'].strip() user = request.user t = get_object_or_404(Turn, room=room_id, user=user, complete=False) count = Result.objects.filter(turn=t).count() result = Result.objects.filter(turn=t, answer='')[0] try: #r = Result.objects.filter(turn=t, answer='') if result.index < count: index = result.index + 1 question = Result.objects.get(turn=t, index=index).question.question else: index = -1 # No more questions question = None t.complete = True t.save() correct = given_answer == result.question.real_answer if correct: # Give user some points user.get_profile().points += result.question.points t.total_points += result.question.points else: # For wrong answer users looses question points / 2 penalty = result.question.points / 2 user.get_profile().points -= penalty t.total_points -= penalty t.save() user.get_profile().save() result.answer = given_answer result.save() return HttpResponse(json.dumps({'correct': correct, 'index': index, \ 'question': question, 'points': user.get_profile().points})) except Result.DoesNotExist as e: return HttpResponse(e) else: return HttpResponseRedirect(login_url) def signup(request): if request.method == 'POST': form = SignupForm(data=request.POST) if form.is_valid(): form.save(); return HttpResponseRedirect('/') else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request)) else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request)) diff --git a/urls.py b/urls.py index 7e67fee..46bc9aa 100644 --- a/urls.py +++ b/urls.py @@ -1,23 +1,24 @@ from django.conf.urls.defaults import * from django.conf import settings # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^$', 'mattespill.main.views.index'), #(r'^question/(?P<question_id>\d+)/$', 'mattespill.main.views.questions'), (r'^login/$', 'django.contrib.auth.views.login'), (r'^logout/$', 'mattespill.main.views.logout'), (r'^room/(?P<room_id>\d+)/$', 'mattespill.main.views.room'), (r'^question/$', 'mattespill.main.views.question'), (r'^answer/$', 'mattespill.main.views.answer'), (r'^signup/$', 'mattespill.main.views.signup'), + (r'^stats/$', 'mattespill.main.views.stats'), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), # Hack to server static files (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_DOC_ROOT}), )
ThomasPedersen/mattespill
4c8a3383269441dea4d3c1cfd1e202326e641705
OMG FIXED!
diff --git a/main/views.py b/main/views.py index eba831d..a6233e6 100644 --- a/main/views.py +++ b/main/views.py @@ -1,143 +1,143 @@ # -*- coding: utf-8 -*- from django.template import RequestContext, Context, loader from django.utils import simplejson from django.http import HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import render_to_response, get_object_or_404 from django.contrib import auth from django.contrib.auth.decorators import login_required from django.core import serializers from datetime import datetime from mattespill.main.models import Question, Room, Turn, Result from mattespill.main.forms import SignupForm import json login_url = '/login/' def index(request): if request.user.is_authenticated(): rooms = Room.objects.all() return render_to_response('home.html', {'user': request.user, 'home': True, \ 'rooms': rooms}) else: return HttpResponseRedirect(login_url) def room(request, room_id): if request.user.is_authenticated(): sess_room_id = request.session.get('room_id', None) if not sess_room_id or sess_room_id != room_id: room = get_object_or_404(Room, pk=room_id) else: room = get_object_or_404(Room, pk=sess_room_id) # If user does not have enough points to access room, # we redirect to index if request.user.get_profile().points < room.required_points: return HttpResponseRedirect('/') request.session['room_id'] = room_id turn_exists = False try: t = Turn.objects.get(room=room, user=request.user, complete=False) turn_exists = True except Turn.DoesNotExist: t = Turn(date_start=datetime.now(), date_end=None, user=request.user, room=room) t.save() # Fetch 10 random questions for the given room questions = Question.objects.filter(room=room).order_by('?')[:10] # Add Result objects (question and answer pairs) for each question i = 1 # Sequence number for each question for q in questions: result = Result(question=q, turn=t, index=i) result.save() i += 1 previous_turns = Turn.objects.filter(room=room, user=request.user, complete=True).\ - order_by('-total_points').order_by('-date_start').all() + order_by('-date_start').order_by('-total_points').all() return render_to_response('room.html', {'turn_exists': turn_exists, 'turn': t, \ 'user': request.user, 'previous_turns': previous_turns}) else: return HttpResponseRedirect(login_url) def logout(request): auth.logout(request) return HttpResponseRedirect('/') def question(request): if request.user.is_authenticated(): room_id = request.session.get('room_id', None) if room_id: try: turn = Turn.objects.get(room=room_id, user=request.user, complete=False) except Turn.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) try: # The Meta.ordering defined in model will sort # the result ascending on Result.index result = Result.objects.filter(turn=turn, answer='')[:1] if not result: return render_to_response('room.html', {'turn': turn, 'user': request.user}) num_questions = Result.objects.filter(turn=turn).count() return render_to_response('question.html', {'user': request.user,'turn': turn, 'result': result[0], \ 'num_questions': num_questions, 'room_id': room_id}) except Result.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) else: return HttpResponseRedirect(login_url) def answer(request): if request.user.is_authenticated() and request.method == 'POST': room_id = request.session.get('room_id', None) if room_id and 'answer' in request.POST: given_answer = request.POST['answer'].strip() user = request.user t = get_object_or_404(Turn, room=room_id, user=user, complete=False) + count = Result.objects.filter(turn=t).count() + result = Result.objects.filter(turn=t, answer='')[0] try: #r = Result.objects.filter(turn=t, answer='') - count = Result.objects.filter(turn=t).count() - result = Result.objects.filter(turn=t, answer='')[0] - if result.index <= count: + if result.index < count: index = result.index + 1 question = Result.objects.get(turn=t, index=index).question.question else: index = -1 # No more questions question = None t.complete = True t.save() correct = given_answer == result.question.real_answer if correct: # Give user some points user.get_profile().points += result.question.points t.total_points += result.question.points else: # For wrong answer users looses question points / 2 penalty = result.question.points / 2 user.get_profile().points -= penalty t.total_points -= penalty t.save() user.get_profile().save() result.answer = given_answer result.save() return HttpResponse(json.dumps({'correct': correct, 'index': index, \ 'question': question, 'points': user.get_profile().points})) - except Result.DoesNotExist: - return HttpResponseRedirect('/room/%s/' % room_id) + except Result.DoesNotExist as e: + return HttpResponse(e) else: return HttpResponseRedirect(login_url) def signup(request): if request.method == 'POST': form = SignupForm(data=request.POST) if form.is_valid(): form.save(); return HttpResponseRedirect('/') else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request)) else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request))
ThomasPedersen/mattespill
5bed0d6afbb7564dd97bc20ba2653835f873b4e7
chrome eyllow outline remove
diff --git a/main/media/main.css b/main/media/main.css index 0734270..85ebe6a 100644 --- a/main/media/main.css +++ b/main/media/main.css @@ -1,164 +1,167 @@ @font-face { font-family: Aller; font-weight: normal; src: url('fonts/Aller_Rg.ttf'); } @font-face { font-family: Aller; font-weight: bold; src: url('fonts/Aller_Bd.ttf'); } body { font-family: Aller, sans-serif; margin: 0; padding: 0; background: url(images/stripes.png); } +*:focus { + outline: none; +} h1 { font-size: 1.8em; margin-top: 0; } h2 { font-size: 1.4em; color: #666; } .chest_header { margin-top: 0; font-size: 150%; font-weight: bold; /*text-shadow: #1D4088 1.5px 1.5px 1.5px;*/ } h1, .chest_header { color: #1D4088; /*color: #9342ad;*/ /*color: #dbda00;*/ /*text-shadow: #aaa 1.5px 1.5px 0px;*/ } #header a { color: #fff; } a, a:visited a:active { text-decoration: none; color: #0000aa; } a:hover { text-decoration: underline; color: #434358; } #wrapper { margin: 0; /*background-color: #dadada;*/ } #header { /*border-bottom: 2px solid #777;*/ color: #fff; padding: .8em 1.5em .6em 1em; font-weight: bold; } #headertable { width: 100%; } #headertable td { width: 33%; } .align_center { text-align: center; } .align_right { text-align: right; } #page_content { margin: 0 8em; padding: 1em; padding-bottom: 2em; background-color: #fff; -moz-border-radius-bottomleft: 1.5em; -webkit-bottom-left-border-radius: 1.5em; border-bottom-left-radius: 1.5em; -moz-border-radius-bottomright: 1.5em; -webkit-border-bottom-right-radius: 1.5em; border-bottom-right-radius: 1.5em; -webkit-box-shadow: 0 0 2em #bbb; -moz-box-shadow: 0 0 2em #bbb; box-shadow: 0 0 2em #bbb; margin-bottom: 3em; } .gold_coins { padding-bottom: .4em; padding-left: .5em; padding-right: .5em; background-color: #e5e5e5; -moz-border-radius: .7em; -webkit-border-radius: .7em; border-radius: .7em; } .gold_text { vertical-align: bottom; font-size: 140%; color: #ff0; font-weight: bold; text-shadow: #000 0 0 5px; } #logout_reminder { font-size: 150%; color: #4b844b; } .simple_button { cursor: pointer; padding: .5em; background-color: #627AAD; color: #fff; font-weight: bold; font-size: 1.3em; border: .2em solid #325193; /*-webkit-box-shadow: 0 0 2em #bbb; -moz-box-shadow: 0 0 2em #bbb; box-shadow: 0 0 2em #bbb;*/ -moz-border-radius: .6em; -webkit-border-radius: .6em; border-radius: .6em; } .simple_button a { color: inherit; } .back_button { margin-top: 4em; } table.styled { text-align: left; border-collapse: collapse; border: 2px solid #b7d4f4; } table.styled th { background-color: #eaf0f6; border: 1px solid #d1e3f6; } table.styled td { background-color: #f7f7f7; border: 1px solid #dadada; } table.styled tr:nth-child(even) td { background-color: white; } table.styled td, table.styled th { padding: .3em .4em; } \ No newline at end of file
ThomasPedersen/mattespill
3cf3e13132e09697d76b9bbba20e7425f0a13a7c
Fixed question count
diff --git a/main/views.py b/main/views.py index 9d2f679..eba831d 100644 --- a/main/views.py +++ b/main/views.py @@ -1,143 +1,143 @@ # -*- coding: utf-8 -*- from django.template import RequestContext, Context, loader from django.utils import simplejson from django.http import HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import render_to_response, get_object_or_404 from django.contrib import auth from django.contrib.auth.decorators import login_required from django.core import serializers from datetime import datetime from mattespill.main.models import Question, Room, Turn, Result from mattespill.main.forms import SignupForm import json login_url = '/login/' def index(request): if request.user.is_authenticated(): rooms = Room.objects.all() return render_to_response('home.html', {'user': request.user, 'home': True, \ 'rooms': rooms}) else: return HttpResponseRedirect(login_url) def room(request, room_id): if request.user.is_authenticated(): sess_room_id = request.session.get('room_id', None) if not sess_room_id or sess_room_id != room_id: room = get_object_or_404(Room, pk=room_id) else: room = get_object_or_404(Room, pk=sess_room_id) # If user does not have enough points to access room, # we redirect to index if request.user.get_profile().points < room.required_points: return HttpResponseRedirect('/') request.session['room_id'] = room_id turn_exists = False try: t = Turn.objects.get(room=room, user=request.user, complete=False) turn_exists = True except Turn.DoesNotExist: t = Turn(date_start=datetime.now(), date_end=None, user=request.user, room=room) t.save() # Fetch 10 random questions for the given room questions = Question.objects.filter(room=room).order_by('?')[:10] # Add Result objects (question and answer pairs) for each question i = 1 # Sequence number for each question for q in questions: result = Result(question=q, turn=t, index=i) result.save() i += 1 previous_turns = Turn.objects.filter(room=room, user=request.user, complete=True).\ order_by('-total_points').order_by('-date_start').all() return render_to_response('room.html', {'turn_exists': turn_exists, 'turn': t, \ 'user': request.user, 'previous_turns': previous_turns}) else: return HttpResponseRedirect(login_url) def logout(request): auth.logout(request) return HttpResponseRedirect('/') def question(request): if request.user.is_authenticated(): room_id = request.session.get('room_id', None) if room_id: try: turn = Turn.objects.get(room=room_id, user=request.user, complete=False) except Turn.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) try: # The Meta.ordering defined in model will sort # the result ascending on Result.index result = Result.objects.filter(turn=turn, answer='')[:1] if not result: return render_to_response('room.html', {'turn': turn, 'user': request.user}) num_questions = Result.objects.filter(turn=turn).count() return render_to_response('question.html', {'user': request.user,'turn': turn, 'result': result[0], \ 'num_questions': num_questions, 'room_id': room_id}) except Result.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) else: return HttpResponseRedirect(login_url) def answer(request): if request.user.is_authenticated() and request.method == 'POST': room_id = request.session.get('room_id', None) if room_id and 'answer' in request.POST: given_answer = request.POST['answer'].strip() user = request.user t = get_object_or_404(Turn, room=room_id, user=user, complete=False) try: - r = Result.objects.filter(turn=t, answer='') - count = r.count() - result = r[0] + #r = Result.objects.filter(turn=t, answer='') + count = Result.objects.filter(turn=t).count() + result = Result.objects.filter(turn=t, answer='')[0] if result.index <= count: index = result.index + 1 question = Result.objects.get(turn=t, index=index).question.question else: index = -1 # No more questions question = None t.complete = True t.save() correct = given_answer == result.question.real_answer if correct: # Give user some points user.get_profile().points += result.question.points t.total_points += result.question.points else: # For wrong answer users looses question points / 2 penalty = result.question.points / 2 user.get_profile().points -= penalty t.total_points -= penalty t.save() user.get_profile().save() result.answer = given_answer result.save() return HttpResponse(json.dumps({'correct': correct, 'index': index, \ 'question': question, 'points': user.get_profile().points})) except Result.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) else: return HttpResponseRedirect(login_url) def signup(request): if request.method == 'POST': form = SignupForm(data=request.POST) if form.is_valid(): form.save(); return HttpResponseRedirect('/') else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request)) else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request))
ThomasPedersen/mattespill
258dca02fc914786268ee790ae9eac934f6dadfb
autofocus bugfix
diff --git a/main/media/question.js b/main/media/question.js index 8ce3998..17c46b3 100644 --- a/main/media/question.js +++ b/main/media/question.js @@ -1,47 +1,47 @@ $(function() { $('.start_button').click(function() { if ($.trim($('input[name=answer]').val()) == '') { alert('Du må skrive inn noe!'); $('input[name=answer]').val(''); return; } $.ajax({ type: 'POST', url: '/answer/', dataType: 'json', data: {answer: $('input[name=answer]').val()}, success: function(data, textStatus) { $('#num_points').text(data.points); if (data.correct) { $('#wrong_answer').hide(); $('#correct_answer').fadeIn(); } else { $('#correct_answer').hide(); $('#wrong_answer').fadeIn(); } if (data.index < 0) { $('#question_wrapper').remove(); $('#finished_wrapper').show(); } else { - $('input[name=answer]').val(''); + $('input[name=answer]').val('').focus(); $('#question_index').text(data.index); $('#question_text').text(data.question); } }, error: function(XMLHttpRequest, textStatus) { alert('Det oppstod en feil'); } }); }); $('#answer_form').submit(function() { $('.simple_button').click(); return false; }); $('input[name=answer]').focus(); }); \ No newline at end of file
ThomasPedersen/mattespill
98b33c60de4061de25db9e01249568277d254323
autocomplete off
diff --git a/main/templates/question.html b/main/templates/question.html index 4eb6328..c8eb651 100644 --- a/main/templates/question.html +++ b/main/templates/question.html @@ -1,67 +1,67 @@ {% extends "outer.html" %} {% block head %} <style type="text/css"> #correct_answer { background-color: #afa; } #wrong_answer { background-color: #fcc; } #correct_answer, #wrong_answer { display: none; padding: .3em; -moz-border-radius: .3em; -webkit-border-radius: .3em; border-radius: .3em; } #question_text { font-size: 1.5em; } #finished_wrapper { display: none; } input[name=answer] { font-size: 1.5em; padding: .5em; border: .2em solid #325193; background-color: #f2f2f2; margin: .5em 0; -moz-border-radius: .5em; -webkit-border-radius: .5em; border-radius: .5em; -text-shadow: #bbb 1px 1px 3px; -webkit-box-shadow: 0 0 .7em #bbb; -moz-box-shadow: 0 0 .7em #bbb; box-shadow: 0 0 .7em #bbb; } </style> <script src="/media/question.js" type="text/javascript"></script> {% endblock %} {% block content %} <h1>Sp&oslash;rsm&aring;l <span id="question_index">{{ result.index }}</span> av {{ num_questions }}</h1> <p id="correct_answer">Du svarte riktig p&aring; forrige oppgave.</p> <p id="wrong_answer">Feil svar p&aring; forrige oppgave.</p> <div id="question_wrapper"> <p id="question_text">{{ result.question.question}}</p> <form id="answer_form" action="" method="post"> - <input type="text" name="answer" /> + <input type="text" name="answer" autocomplete="off" /> <p class="start_button_container"><span class="start_button simple_button">Svar</span></p></p> </form> <p class="back_button"><a href="/room/{{ room_id }}/">G&aring; tilbake til rommet</a></p> </div> <div id="finished_wrapper"> <p>Du er ferdig med dette fors&oslash;ket!</p> <p class="start_button_container"><span class="simple_button"><a href="/room/{{ room_id }}/">Tilbake til rommet!</a></span></p> </div> {% endblock %}
ThomasPedersen/mattespill
31ea1b0a787ef17c813d21599904532eb2dac8f3
Order by Turn by date_start after ordering by total_points
diff --git a/main/views.py b/main/views.py index 976c040..9d2f679 100644 --- a/main/views.py +++ b/main/views.py @@ -1,142 +1,143 @@ # -*- coding: utf-8 -*- from django.template import RequestContext, Context, loader from django.utils import simplejson from django.http import HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import render_to_response, get_object_or_404 from django.contrib import auth from django.contrib.auth.decorators import login_required from django.core import serializers from datetime import datetime from mattespill.main.models import Question, Room, Turn, Result from mattespill.main.forms import SignupForm import json login_url = '/login/' def index(request): if request.user.is_authenticated(): rooms = Room.objects.all() return render_to_response('home.html', {'user': request.user, 'home': True, \ 'rooms': rooms}) else: return HttpResponseRedirect(login_url) def room(request, room_id): if request.user.is_authenticated(): sess_room_id = request.session.get('room_id', None) if not sess_room_id or sess_room_id != room_id: room = get_object_or_404(Room, pk=room_id) else: room = get_object_or_404(Room, pk=sess_room_id) # If user does not have enough points to access room, # we redirect to index if request.user.get_profile().points < room.required_points: return HttpResponseRedirect('/') request.session['room_id'] = room_id turn_exists = False try: t = Turn.objects.get(room=room, user=request.user, complete=False) turn_exists = True except Turn.DoesNotExist: t = Turn(date_start=datetime.now(), date_end=None, user=request.user, room=room) t.save() # Fetch 10 random questions for the given room questions = Question.objects.filter(room=room).order_by('?')[:10] # Add Result objects (question and answer pairs) for each question i = 1 # Sequence number for each question for q in questions: result = Result(question=q, turn=t, index=i) result.save() i += 1 - previous_turns = Turn.objects.filter(room=room, user=request.user, complete=True).order_by('-total_points').all() + previous_turns = Turn.objects.filter(room=room, user=request.user, complete=True).\ + order_by('-total_points').order_by('-date_start').all() return render_to_response('room.html', {'turn_exists': turn_exists, 'turn': t, \ 'user': request.user, 'previous_turns': previous_turns}) else: return HttpResponseRedirect(login_url) def logout(request): auth.logout(request) return HttpResponseRedirect('/') def question(request): if request.user.is_authenticated(): room_id = request.session.get('room_id', None) if room_id: try: turn = Turn.objects.get(room=room_id, user=request.user, complete=False) except Turn.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) try: # The Meta.ordering defined in model will sort # the result ascending on Result.index result = Result.objects.filter(turn=turn, answer='')[:1] if not result: return render_to_response('room.html', {'turn': turn, 'user': request.user}) num_questions = Result.objects.filter(turn=turn).count() return render_to_response('question.html', {'user': request.user,'turn': turn, 'result': result[0], \ 'num_questions': num_questions, 'room_id': room_id}) except Result.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) else: return HttpResponseRedirect(login_url) def answer(request): if request.user.is_authenticated() and request.method == 'POST': room_id = request.session.get('room_id', None) if room_id and 'answer' in request.POST: given_answer = request.POST['answer'].strip() user = request.user t = get_object_or_404(Turn, room=room_id, user=user, complete=False) try: r = Result.objects.filter(turn=t, answer='') count = r.count() result = r[0] if result.index <= count: index = result.index + 1 question = Result.objects.get(turn=t, index=index).question.question else: index = -1 # No more questions question = None t.complete = True t.save() correct = given_answer == result.question.real_answer if correct: # Give user some points user.get_profile().points += result.question.points t.total_points += result.question.points else: # For wrong answer users looses question points / 2 penalty = result.question.points / 2 user.get_profile().points -= penalty t.total_points -= penalty t.save() user.get_profile().save() result.answer = given_answer result.save() return HttpResponse(json.dumps({'correct': correct, 'index': index, \ 'question': question, 'points': user.get_profile().points})) except Result.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) else: return HttpResponseRedirect(login_url) def signup(request): if request.method == 'POST': form = SignupForm(data=request.POST) if form.is_valid(): form.save(); return HttpResponseRedirect('/') else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request)) else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request))
ThomasPedersen/mattespill
6049fd027edce0b31bdde4c8ac72779b97a93eee
Lagt til spørsmål!
diff --git a/initial_data.json b/initial_data.json index 4905039..4fbe8d5 100644 --- a/initial_data.json +++ b/initial_data.json @@ -1 +1 @@ -[{"pk": 5, "model": "contenttypes.contenttype", "fields": {"model": "contenttype", "name": "content type", "app_label": "contenttypes"}}, {"pk": 2, "model": "contenttypes.contenttype", "fields": {"model": "group", "name": "group", "app_label": "auth"}}, {"pk": 8, "model": "contenttypes.contenttype", "fields": {"model": "logentry", "name": "log entry", "app_label": "admin"}}, {"pk": 4, "model": "contenttypes.contenttype", "fields": {"model": "message", "name": "message", "app_label": "auth"}}, {"pk": 1, "model": "contenttypes.contenttype", "fields": {"model": "permission", "name": "permission", "app_label": "auth"}}, {"pk": 11, "model": "contenttypes.contenttype", "fields": {"model": "question", "name": "question", "app_label": "main"}}, {"pk": 13, "model": "contenttypes.contenttype", "fields": {"model": "result", "name": "result", "app_label": "main"}}, {"pk": 10, "model": "contenttypes.contenttype", "fields": {"model": "room", "name": "room", "app_label": "main"}}, {"pk": 6, "model": "contenttypes.contenttype", "fields": {"model": "session", "name": "session", "app_label": "sessions"}}, {"pk": 7, "model": "contenttypes.contenttype", "fields": {"model": "site", "name": "site", "app_label": "sites"}}, {"pk": 12, "model": "contenttypes.contenttype", "fields": {"model": "turn", "name": "turn", "app_label": "main"}}, {"pk": 3, "model": "contenttypes.contenttype", "fields": {"model": "user", "name": "user", "app_label": "auth"}}, {"pk": 9, "model": "contenttypes.contenttype", "fields": {"model": "userprofile", "name": "user profile", "app_label": "main"}}, {"pk": "d58d99add984c655b2bd48c0765da04a", "model": "sessions.session", "fields": {"expire_date": "2010-10-29 12:42:50", "session_data": "gAJ9cQEoVQdyb29tX2lkcQJYAQAAADFVEl9hdXRoX3VzZXJfYmFja2VuZHEDVSlkamFuZ28uY29u\ndHJpYi5hdXRoLmJhY2tlbmRzLk1vZGVsQmFja2VuZHEEVQ1fYXV0aF91c2VyX2lkcQVLAXUuYThl\nZjM4YTUyZGIzOTQ4ODE1NzM0MTU1NTc0OWYxZWM=\n"}}, {"pk": "bfb3c5a9c61eed9b843d787916dd9936", "model": "sessions.session", "fields": {"expire_date": "2010-10-29 13:15:14", "session_data": "gAJ9cQEoVQdyb29tX2lkcQJYAQAAADJVDV9hdXRoX3VzZXJfaWRxA0sBVRJfYXV0aF91c2VyX2Jh\nY2tlbmRxBFUpZGphbmdvLmNvbnRyaWIuYXV0aC5iYWNrZW5kcy5Nb2RlbEJhY2tlbmRxBXUuNzBm\nYzhkZGNjYTYyMzBlODBlY2YyODNiMDI2ODZjMDk=\n"}}, {"pk": 1, "model": "sites.site", "fields": {"domain": "mattespill.tld", "name": "mattespill.tld"}}, {"pk": 51, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 13:16:53", "object_repr": "test | 2010-10-15 12:49:59.962029 | Addisjon", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 50, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 13:16:53", "object_repr": "test | 2010-10-15 12:50:03.041886 | Divisjon", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 49, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 13:16:53", "object_repr": "test | 2010-10-15 12:51:20.907567 | Divisjon", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 48, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 13:16:53", "object_repr": "test | 2010-10-15 12:51:49.362569 | Multiplikasjon", "object_id": "4", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 47, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 13:16:53", "object_repr": "test | 2010-10-15 12:52:15.767920 | Multiplikasjon", "object_id": "5", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 46, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 13:16:53", "object_repr": "test | 2010-10-15 12:53:13.274247 | Subtraksjon", "object_id": "6", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 45, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 13:16:53", "object_repr": "test | 2010-10-15 12:54:04.900428 | Addisjon", "object_id": "7", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 44, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 13:16:53", "object_repr": "test | 2010-10-15 12:57:49.395061 | Addisjon", "object_id": "8", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 43, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 13:16:52", "object_repr": "test | 2010-10-15 12:58:03.696631 | Addisjon", "object_id": "9", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 42, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 13:16:36", "object_repr": "mattespill.tld", "object_id": "1", "change_message": "Endret domain og name.", "user": 1, "content_type": 7}}, {"pk": 41, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 13:10:00", "object_repr": "mattespill.no", "object_id": "1", "change_message": "", "user": 1, "content_type": 7}}, {"pk": 40, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 12:59:55", "object_repr": "Divisjon", "object_id": "4", "change_message": "Endret required_points.", "user": 1, "content_type": 10}}, {"pk": 39, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 12:59:50", "object_repr": "Multiplikasjon", "object_id": "3", "change_message": "Endret required_points.", "user": 1, "content_type": 10}}, {"pk": 38, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:49:09", "object_repr": "Hva er 9 / 3?", "object_id": "12", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 37, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:48:48", "object_repr": "Hva er 8 / 4?", "object_id": "11", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 36, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:48:27", "object_repr": "Hva er 4 / 2?", "object_id": "10", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 35, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:48:08", "object_repr": "Hva er 10 * 10?", "object_id": "9", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 34, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:47:12", "object_repr": "Hva er 2 * 9?", "object_id": "8", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 33, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:46:59", "object_repr": "Hva er 4 * 4?", "object_id": "7", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 32, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:46:01", "object_repr": "example.com", "object_id": "1", "change_message": "", "user": 1, "content_type": 7}}, {"pk": 31, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:57:16.340061 | Addisjon", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 30, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:57:45.110544 | Addisjon", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 29, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:58:25.267152 | Addisjon", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 28, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:59:11.658703 | Addisjon", "object_id": "4", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 27, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:59:38.586859 | Addisjon", "object_id": "5", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 26, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 11:04:16.476584 | Addisjon", "object_id": "6", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 25, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:04:57.168726 | Addisjon", "object_id": "7", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 24, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:05:58.137954 | Addisjon", "object_id": "8", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 23, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:06:46.026789 | Addisjon", "object_id": "9", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 22, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:49:13.174200 | Addisjon", "object_id": "10", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 21, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 12:24:23.680071 | Subtraksjon", "object_id": "11", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 20, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 12:36:11.859253 | Addisjon", "object_id": "12", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 19, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 12:40:51.846371 | Addisjon", "object_id": "13", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 18, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 12:45:14", "object_repr": "test", "object_id": "1", "change_message": "Endret first_name og last_name.", "user": 1, "content_type": 3}}, {"pk": 17, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 12:44:51", "object_repr": "test", "object_id": "1", "change_message": "Endret first_name og last_name.", "user": 1, "content_type": 3}}, {"pk": 16, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:25:25", "object_repr": "Hva 34-5?", "object_id": "6", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 15, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:25:09", "object_repr": "Hva er 200-100", "object_id": "5", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 14, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:25:00", "object_repr": "Hva 10 - 3?", "object_id": "4", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 9, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:45:55.770004 | Addisjon", "object_id": "5", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 10, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:45:25.432687 | Addisjon", "object_id": "4", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 11, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:43:06.129923 | Addisjon", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 12, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:40:22.639628 | Addisjon", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 13, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:38:05 | Addisjon", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 8, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 10:39:54", "object_repr": "test | 2010-10-15 10:38:05 | Addisjon", "object_id": "1", "change_message": "Endret date_end og complete.", "user": 1, "content_type": 12}}, {"pk": 7, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:37:50", "object_repr": "Hva er 125+125?", "object_id": "3", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 6, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:37:30", "object_repr": "Hva er 50+23?", "object_id": "2", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 5, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:37:14", "object_repr": "Hva er 2 + 2?", "object_id": "1", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 4, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:54", "object_repr": "Divisjon", "object_id": "4", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 3, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:47", "object_repr": "Multiplikasjon", "object_id": "3", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 2, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:37", "object_repr": "Subtraksjon", "object_id": "2", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 1, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:25", "object_repr": "Addisjon", "object_id": "1", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 1, "model": "main.userprofile", "fields": {"points": 408, "user": 1}}, {"pk": 1, "model": "main.room", "fields": {"required_points": 0, "name": "Addisjon", "description": "Addere tall"}}, {"pk": 2, "model": "main.room", "fields": {"required_points": 100, "name": "Subtraksjon", "description": "Subtrahere tall"}}, {"pk": 3, "model": "main.room", "fields": {"required_points": 500, "name": "Multiplikasjon", "description": "Multiplisere tall"}}, {"pk": 4, "model": "main.room", "fields": {"required_points": 1000, "name": "Divisjon", "description": "Dividere tall"}}, {"pk": 1, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "Hva er 2 + 2?", "real_answer": "4", "points": 10, "date_created": "2010-10-15 10:37:14"}}, {"pk": 2, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "Hva er 50+23?", "real_answer": "73", "points": 14, "date_created": "2010-10-15 10:37:30"}}, {"pk": 3, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "Hva er 125+125?", "real_answer": "250", "points": 16, "date_created": "2010-10-15 10:37:50"}}, {"pk": 4, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Hva 10 - 3?", "real_answer": "7", "points": 21, "date_created": "2010-10-15 12:25:00"}}, {"pk": 5, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Hva er 200-100", "real_answer": "100", "points": 26, "date_created": "2010-10-15 12:25:09"}}, {"pk": 6, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Hva 34-5?", "real_answer": "29", "points": 28, "date_created": "2010-10-15 12:25:25"}}, {"pk": 7, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Hva er 4 * 4?", "real_answer": "16", "points": 32, "date_created": "2010-10-15 12:46:59"}}, {"pk": 8, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Hva er 2 * 9?", "real_answer": "18", "points": 25, "date_created": "2010-10-15 12:47:12"}}, {"pk": 9, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Hva er 10 * 10?", "real_answer": "100", "points": 27, "date_created": "2010-10-15 12:48:08"}}, {"pk": 10, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "Hva er 4 / 2?", "real_answer": "2", "points": 42, "date_created": "2010-10-15 12:48:27"}}, {"pk": 11, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "Hva er 8 / 4?", "real_answer": "2", "points": 46, "date_created": "2010-10-15 12:48:48"}}, {"pk": 12, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "Hva er 9 / 3?", "real_answer": "3", "points": 48, "date_created": "2010-10-15 12:49:09"}}, {"pk": 22, "model": "auth.permission", "fields": {"codename": "add_logentry", "name": "Can add log entry", "content_type": 8}}, {"pk": 23, "model": "auth.permission", "fields": {"codename": "change_logentry", "name": "Can change log entry", "content_type": 8}}, {"pk": 24, "model": "auth.permission", "fields": {"codename": "delete_logentry", "name": "Can delete log entry", "content_type": 8}}, {"pk": 4, "model": "auth.permission", "fields": {"codename": "add_group", "name": "Can add group", "content_type": 2}}, {"pk": 5, "model": "auth.permission", "fields": {"codename": "change_group", "name": "Can change group", "content_type": 2}}, {"pk": 6, "model": "auth.permission", "fields": {"codename": "delete_group", "name": "Can delete group", "content_type": 2}}, {"pk": 10, "model": "auth.permission", "fields": {"codename": "add_message", "name": "Can add message", "content_type": 4}}, {"pk": 11, "model": "auth.permission", "fields": {"codename": "change_message", "name": "Can change message", "content_type": 4}}, {"pk": 12, "model": "auth.permission", "fields": {"codename": "delete_message", "name": "Can delete message", "content_type": 4}}, {"pk": 1, "model": "auth.permission", "fields": {"codename": "add_permission", "name": "Can add permission", "content_type": 1}}, {"pk": 2, "model": "auth.permission", "fields": {"codename": "change_permission", "name": "Can change permission", "content_type": 1}}, {"pk": 3, "model": "auth.permission", "fields": {"codename": "delete_permission", "name": "Can delete permission", "content_type": 1}}, {"pk": 7, "model": "auth.permission", "fields": {"codename": "add_user", "name": "Can add user", "content_type": 3}}, {"pk": 8, "model": "auth.permission", "fields": {"codename": "change_user", "name": "Can change user", "content_type": 3}}, {"pk": 9, "model": "auth.permission", "fields": {"codename": "delete_user", "name": "Can delete user", "content_type": 3}}, {"pk": 13, "model": "auth.permission", "fields": {"codename": "add_contenttype", "name": "Can add content type", "content_type": 5}}, {"pk": 14, "model": "auth.permission", "fields": {"codename": "change_contenttype", "name": "Can change content type", "content_type": 5}}, {"pk": 15, "model": "auth.permission", "fields": {"codename": "delete_contenttype", "name": "Can delete content type", "content_type": 5}}, {"pk": 31, "model": "auth.permission", "fields": {"codename": "add_question", "name": "Can add question", "content_type": 11}}, {"pk": 32, "model": "auth.permission", "fields": {"codename": "change_question", "name": "Can change question", "content_type": 11}}, {"pk": 33, "model": "auth.permission", "fields": {"codename": "delete_question", "name": "Can delete question", "content_type": 11}}, {"pk": 37, "model": "auth.permission", "fields": {"codename": "add_result", "name": "Can add result", "content_type": 13}}, {"pk": 38, "model": "auth.permission", "fields": {"codename": "change_result", "name": "Can change result", "content_type": 13}}, {"pk": 39, "model": "auth.permission", "fields": {"codename": "delete_result", "name": "Can delete result", "content_type": 13}}, {"pk": 28, "model": "auth.permission", "fields": {"codename": "add_room", "name": "Can add room", "content_type": 10}}, {"pk": 29, "model": "auth.permission", "fields": {"codename": "change_room", "name": "Can change room", "content_type": 10}}, {"pk": 30, "model": "auth.permission", "fields": {"codename": "delete_room", "name": "Can delete room", "content_type": 10}}, {"pk": 34, "model": "auth.permission", "fields": {"codename": "add_turn", "name": "Can add turn", "content_type": 12}}, {"pk": 35, "model": "auth.permission", "fields": {"codename": "change_turn", "name": "Can change turn", "content_type": 12}}, {"pk": 36, "model": "auth.permission", "fields": {"codename": "delete_turn", "name": "Can delete turn", "content_type": 12}}, {"pk": 25, "model": "auth.permission", "fields": {"codename": "add_userprofile", "name": "Can add user profile", "content_type": 9}}, {"pk": 26, "model": "auth.permission", "fields": {"codename": "change_userprofile", "name": "Can change user profile", "content_type": 9}}, {"pk": 27, "model": "auth.permission", "fields": {"codename": "delete_userprofile", "name": "Can delete user profile", "content_type": 9}}, {"pk": 16, "model": "auth.permission", "fields": {"codename": "add_session", "name": "Can add session", "content_type": 6}}, {"pk": 17, "model": "auth.permission", "fields": {"codename": "change_session", "name": "Can change session", "content_type": 6}}, {"pk": 18, "model": "auth.permission", "fields": {"codename": "delete_session", "name": "Can delete session", "content_type": 6}}, {"pk": 19, "model": "auth.permission", "fields": {"codename": "add_site", "name": "Can add site", "content_type": 7}}, {"pk": 20, "model": "auth.permission", "fields": {"codename": "change_site", "name": "Can change site", "content_type": 7}}, {"pk": 21, "model": "auth.permission", "fields": {"codename": "delete_site", "name": "Can delete site", "content_type": 7}}, {"pk": 1, "model": "auth.user", "fields": {"username": "test", "first_name": "Eric", "last_name": "Cartman", "is_active": true, "is_superuser": true, "is_staff": true, "last_login": "2010-10-15 13:15:05", "groups": [], "user_permissions": [], "password": "sha1$59aea$c0f29c76f430fb25c1f93856b104a222232a1324", "email": "[email protected]", "date_joined": "2010-10-15 10:35:58"}}] \ No newline at end of file +[{"pk": 5, "model": "contenttypes.contenttype", "fields": {"model": "contenttype", "name": "content type", "app_label": "contenttypes"}}, {"pk": 2, "model": "contenttypes.contenttype", "fields": {"model": "group", "name": "group", "app_label": "auth"}}, {"pk": 8, "model": "contenttypes.contenttype", "fields": {"model": "logentry", "name": "log entry", "app_label": "admin"}}, {"pk": 4, "model": "contenttypes.contenttype", "fields": {"model": "message", "name": "message", "app_label": "auth"}}, {"pk": 1, "model": "contenttypes.contenttype", "fields": {"model": "permission", "name": "permission", "app_label": "auth"}}, {"pk": 11, "model": "contenttypes.contenttype", "fields": {"model": "question", "name": "question", "app_label": "main"}}, {"pk": 13, "model": "contenttypes.contenttype", "fields": {"model": "result", "name": "result", "app_label": "main"}}, {"pk": 10, "model": "contenttypes.contenttype", "fields": {"model": "room", "name": "room", "app_label": "main"}}, {"pk": 6, "model": "contenttypes.contenttype", "fields": {"model": "session", "name": "session", "app_label": "sessions"}}, {"pk": 7, "model": "contenttypes.contenttype", "fields": {"model": "site", "name": "site", "app_label": "sites"}}, {"pk": 12, "model": "contenttypes.contenttype", "fields": {"model": "turn", "name": "turn", "app_label": "main"}}, {"pk": 3, "model": "contenttypes.contenttype", "fields": {"model": "user", "name": "user", "app_label": "auth"}}, {"pk": 9, "model": "contenttypes.contenttype", "fields": {"model": "userprofile", "name": "user profile", "app_label": "main"}}, {"pk": "5a51edfd2da6fd1442ecfebe170564ac", "model": "sessions.session", "fields": {"expire_date": "2010-10-29 12:36:30", "session_data": "gAJ9cQEoVQdyb29tX2lkcQJYAQAAADFVEl9hdXRoX3VzZXJfYmFja2VuZHEDVSlkamFuZ28uY29u\ndHJpYi5hdXRoLmJhY2tlbmRzLk1vZGVsQmFja2VuZHEEVQ1fYXV0aF91c2VyX2lkcQVLAXUuYThl\nZjM4YTUyZGIzOTQ4ODE1NzM0MTU1NTc0OWYxZWM=\n"}}, {"pk": "d58d99add984c655b2bd48c0765da04a", "model": "sessions.session", "fields": {"expire_date": "2010-10-29 12:42:50", "session_data": "gAJ9cQEoVQdyb29tX2lkcQJYAQAAADFVEl9hdXRoX3VzZXJfYmFja2VuZHEDVSlkamFuZ28uY29u\ndHJpYi5hdXRoLmJhY2tlbmRzLk1vZGVsQmFja2VuZHEEVQ1fYXV0aF91c2VyX2lkcQVLAXUuYThl\nZjM4YTUyZGIzOTQ4ODE1NzM0MTU1NTc0OWYxZWM=\n"}}, {"pk": "82d8dd22044d3c538a2dfe6dd7a8581e", "model": "sessions.session", "fields": {"expire_date": "2010-10-29 13:56:34", "session_data": "gAJ9cQEoVRJfYXV0aF91c2VyX2JhY2tlbmRxAlUpZGphbmdvLmNvbnRyaWIuYXV0aC5iYWNrZW5k\ncy5Nb2RlbEJhY2tlbmRxA1UNX2F1dGhfdXNlcl9pZHEESwF1LmNhYTgxNjQ5YjIxNjUzMzMyOGQw\nODJlNGY0MDEyZDAy\n"}}, {"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}, {"pk": 48, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:19:10", "object_repr": "[Addisjon] Maria har 5 bananer og Per har 3 bananer. Hvor mange bananer har Maria og Per til sammen?", "object_id": "22", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 47, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:14:03", "object_repr": "[Multiplikasjon] Andre trinn p\u00e5 Notodden skole best\u00e5r av tre klasser. Det g\u00e5r 21 elever i hver klasse. Hvor mange elever er det i alt p\u00e5 andre trinn?", "object_id": "21", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 46, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:12:09", "object_repr": "[Divisjon] En klasse p\u00e5 32 elever skal deles i fire. Hvor mange blir det p\u00e5 hver gruppe?", "object_id": "20", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 45, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:10:47", "object_repr": "[Multiplikasjon] Petter f\u00e5r 50 kroner i ukel\u00f8nn. Hvor mye penger f\u00e5r han i l\u00f8pet av 5 uker?", "object_id": "19", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 44, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:09:36", "object_repr": "[Divisjon] Tre venner har ni epler. Hvor mange f\u00e5r de hver?", "object_id": "18", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 43, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:06:34", "object_repr": "[Addisjon] \u00c5ge har 5 epler. Han f\u00e5r 3 epler av Ingrid. Hvor mange epler har \u00c5ge til sammen?", "object_id": "17", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 42, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:05:36", "object_repr": "[Addisjon] En gutt har en valp. S\u00e5 f\u00e5r han en til. Hvor mange valper har han n\u00e5?", "object_id": "16", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 41, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:04:59", "object_repr": "[Subtraksjon] Per har 90 kroner og Lise har 50 kroner. De kj\u00f8per seg en CD til 80 kroner. Hvor mye har de igjen tilsammen?", "object_id": "15", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 40, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:02:08", "object_repr": "[Subtraksjon] Marthe har 35 kaker. Hun gir bort 10 til Elias. Hvor mange kaker har hun igjen?", "object_id": "14", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 39, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 14:01:37", "object_repr": "[Subtraksjon] Hilde har 54 kroner, og Magnus har 57 kroner. Hvor mange kroner mindre har Hilde enn Magnus?", "object_id": "13", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 38, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:49:09", "object_repr": "Hva er 9 / 3?", "object_id": "12", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 37, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:48:48", "object_repr": "Hva er 8 / 4?", "object_id": "11", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 36, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:48:27", "object_repr": "Hva er 4 / 2?", "object_id": "10", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 35, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:48:08", "object_repr": "Hva er 10 * 10?", "object_id": "9", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 34, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:47:12", "object_repr": "Hva er 2 * 9?", "object_id": "8", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 33, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:46:59", "object_repr": "Hva er 4 * 4?", "object_id": "7", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 32, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:46:01", "object_repr": "example.com", "object_id": "1", "change_message": "", "user": 1, "content_type": 7}}, {"pk": 26, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 11:04:16.476584 | Addisjon", "object_id": "6", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 27, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:59:38.586859 | Addisjon", "object_id": "5", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 28, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:59:11.658703 | Addisjon", "object_id": "4", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 29, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:58:25.267152 | Addisjon", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 30, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:57:45.110544 | Addisjon", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 31, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:41", "object_repr": "test | 2010-10-15 10:57:16.340061 | Addisjon", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 19, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 12:40:51.846371 | Addisjon", "object_id": "13", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 20, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 12:36:11.859253 | Addisjon", "object_id": "12", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 21, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 12:24:23.680071 | Subtraksjon", "object_id": "11", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 22, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:49:13.174200 | Addisjon", "object_id": "10", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 23, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:06:46.026789 | Addisjon", "object_id": "9", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 24, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:05:58.137954 | Addisjon", "object_id": "8", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 25, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 12:45:40", "object_repr": "test | 2010-10-15 11:04:57.168726 | Addisjon", "object_id": "7", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 18, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 12:45:14", "object_repr": "test", "object_id": "1", "change_message": "Endret first_name og last_name.", "user": 1, "content_type": 3}}, {"pk": 17, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 12:44:51", "object_repr": "test", "object_id": "1", "change_message": "Endret first_name og last_name.", "user": 1, "content_type": 3}}, {"pk": 16, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:25:25", "object_repr": "Hva 34-5?", "object_id": "6", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 15, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:25:09", "object_repr": "Hva er 200-100", "object_id": "5", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 14, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 12:25:00", "object_repr": "Hva 10 - 3?", "object_id": "4", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 9, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:45:55.770004 | Addisjon", "object_id": "5", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 10, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:45:25.432687 | Addisjon", "object_id": "4", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 11, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:43:06.129923 | Addisjon", "object_id": "3", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 12, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:40:22.639628 | Addisjon", "object_id": "2", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 13, "model": "admin.logentry", "fields": {"action_flag": 3, "action_time": "2010-10-15 10:52:02", "object_repr": "test | 2010-10-15 10:38:05 | Addisjon", "object_id": "1", "change_message": "", "user": 1, "content_type": 12}}, {"pk": 8, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2010-10-15 10:39:54", "object_repr": "test | 2010-10-15 10:38:05 | Addisjon", "object_id": "1", "change_message": "Endret date_end og complete.", "user": 1, "content_type": 12}}, {"pk": 7, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:37:50", "object_repr": "Hva er 125+125?", "object_id": "3", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 6, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:37:30", "object_repr": "Hva er 50+23?", "object_id": "2", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 5, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:37:14", "object_repr": "Hva er 2 + 2?", "object_id": "1", "change_message": "", "user": 1, "content_type": 11}}, {"pk": 4, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:54", "object_repr": "Divisjon", "object_id": "4", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 3, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:47", "object_repr": "Multiplikasjon", "object_id": "3", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 2, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:37", "object_repr": "Subtraksjon", "object_id": "2", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 1, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2010-10-15 10:36:25", "object_repr": "Addisjon", "object_id": "1", "change_message": "", "user": 1, "content_type": 10}}, {"pk": 1, "model": "main.userprofile", "fields": {"points": 1109, "user": 1}}, {"pk": 2, "model": "main.userprofile", "fields": {"points": 90, "user": 2}}, {"pk": 1, "model": "main.room", "fields": {"required_points": 0, "name": "Addisjon", "description": "Addere tall"}}, {"pk": 2, "model": "main.room", "fields": {"required_points": 100, "name": "Subtraksjon", "description": "Subtrahere tall"}}, {"pk": 3, "model": "main.room", "fields": {"required_points": 200, "name": "Multiplikasjon", "description": "Multiplisere tall"}}, {"pk": 4, "model": "main.room", "fields": {"required_points": 300, "name": "Divisjon", "description": "Dividere tall"}}, {"pk": 1, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "Hva er 2 + 2?", "real_answer": "4", "points": 10, "date_created": "2010-10-15 10:37:14"}}, {"pk": 2, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "Hva er 50+23?", "real_answer": "73", "points": 14, "date_created": "2010-10-15 10:37:30"}}, {"pk": 3, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "Hva er 125+125?", "real_answer": "250", "points": 16, "date_created": "2010-10-15 10:37:50"}}, {"pk": 4, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Hva 10 - 3?", "real_answer": "7", "points": 21, "date_created": "2010-10-15 12:25:00"}}, {"pk": 5, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Hva er 200-100", "real_answer": "100", "points": 26, "date_created": "2010-10-15 12:25:09"}}, {"pk": 6, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Hva 34-5?", "real_answer": "29", "points": 28, "date_created": "2010-10-15 12:25:25"}}, {"pk": 7, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Hva er 4 * 4?", "real_answer": "16", "points": 32, "date_created": "2010-10-15 12:46:59"}}, {"pk": 8, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Hva er 2 * 9?", "real_answer": "18", "points": 25, "date_created": "2010-10-15 12:47:12"}}, {"pk": 9, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Hva er 10 * 10?", "real_answer": "100", "points": 27, "date_created": "2010-10-15 12:48:08"}}, {"pk": 10, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "Hva er 4 / 2?", "real_answer": "2", "points": 42, "date_created": "2010-10-15 12:48:27"}}, {"pk": 11, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "Hva er 8 / 4?", "real_answer": "2", "points": 46, "date_created": "2010-10-15 12:48:48"}}, {"pk": 12, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "Hva er 9 / 3?", "real_answer": "3", "points": 48, "date_created": "2010-10-15 12:49:09"}}, {"pk": 13, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Hilde har 54 kroner, og Magnus har 57 kroner. Hvor mange kroner mindre har Hilde enn Magnus?", "real_answer": "3", "points": 10, "date_created": "2010-10-15 14:01:37"}}, {"pk": 14, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Marthe har 35 kaker. Hun gir bort 10 til Elias. Hvor mange kaker har hun igjen?", "real_answer": "25", "points": 10, "date_created": "2010-10-15 14:02:08"}}, {"pk": 15, "model": "main.question", "fields": {"room": 2, "author": 1, "question": "Per har 90 kroner og Lise har 50 kroner. De kj\u00f8per seg en CD til 80 kroner. Hvor mye har de igjen tilsammen?", "real_answer": "60", "points": 20, "date_created": "2010-10-15 14:04:59"}}, {"pk": 16, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "En gutt har en valp. S\u00e5 f\u00e5r han en til. Hvor mange valper har han n\u00e5?", "real_answer": "2", "points": 5, "date_created": "2010-10-15 14:05:36"}}, {"pk": 17, "model": "main.question", "fields": {"room": 1, "author": 1, "question": "\u00c5ge har 5 epler. Han f\u00e5r 3 epler av Ingrid. Hvor mange epler har \u00c5ge til sammen?", "real_answer": "8", "points": 10, "date_created": "2010-10-15 14:06:34"}}, {"pk": 18, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "Tre venner har ni epler. Hvor mange f\u00e5r de hver?", "real_answer": "3", "points": 25, "date_created": "2010-10-15 14:09:36"}}, {"pk": 19, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Petter f\u00e5r 50 kroner i ukel\u00f8nn. Hvor mye penger f\u00e5r han i l\u00f8pet av 5 uker?", "real_answer": "250", "points": 20, "date_created": "2010-10-15 14:10:47"}}, {"pk": 20, "model": "main.question", "fields": {"room": 4, "author": 1, "question": "En klasse p\u00e5 32 elever skal deles i fire. Hvor mange blir det p\u00e5 hver gruppe?", "real_answer": "8", "points": 30, "date_created": "2010-10-15 14:12:09"}}, {"pk": 21, "model": "main.question", "fields": {"room": 3, "author": 1, "question": "Andre trinn p\u00e5 Notodden skole best\u00e5r av tre klasser. Det g\u00e5r 21 elever i hver klasse. Hvor mange elever er det i alt p\u00e5 andre trinn?", "real_answer": "63", "points": 25, "date_created": "2010-10-15 14:14:03"}}, {"pk": 22, "model": "main.question", "fields": {"room": 1, "author": 2, "question": "Maria har 5 bananer og Per har 3 bananer. Hvor mange bananer har Maria og Per til sammen?", "real_answer": "8", "points": 10, "date_created": "2010-10-15 14:19:10"}}, {"pk": 1, "model": "main.turn", "fields": {"complete": true, "date_end": null, "date_start": "2010-10-15 12:57:40", "user": 1, "total_points": 75, "room": 2}}, {"pk": 2, "model": "main.turn", "fields": {"complete": false, "date_end": null, "date_start": "2010-10-15 12:57:53", "user": 1, "total_points": 0, "room": 2}}, {"pk": 3, "model": "main.turn", "fields": {"complete": true, "date_end": null, "date_start": "2010-10-15 12:58:02", "user": 1, "total_points": 84, "room": 3}}, {"pk": 4, "model": "main.turn", "fields": {"complete": false, "date_end": null, "date_start": "2010-10-15 12:58:14", "user": 1, "total_points": 0, "room": 3}}, {"pk": 5, "model": "main.turn", "fields": {"complete": true, "date_end": null, "date_start": "2010-10-15 12:58:21", "user": 1, "total_points": 136, "room": 4}}, {"pk": 6, "model": "main.turn", "fields": {"complete": true, "date_end": null, "date_start": "2010-10-15 12:58:34", "user": 1, "total_points": 136, "room": 4}}, {"pk": 7, "model": "main.turn", "fields": {"complete": true, "date_end": null, "date_start": "2010-10-15 12:58:42", "user": 1, "total_points": 136, "room": 4}}, {"pk": 8, "model": "main.turn", "fields": {"complete": true, "date_end": null, "date_start": "2010-10-15 12:58:50", "user": 1, "total_points": 136, "room": 4}}, {"pk": 9, "model": "main.turn", "fields": {"complete": true, "date_end": null, "date_start": "2010-10-15 12:58:59", "user": 1, "total_points": 136, "room": 4}}, {"pk": 10, "model": "main.turn", "fields": {"complete": false, "date_end": null, "date_start": "2010-10-15 12:59:04", "user": 1, "total_points": 0, "room": 4}}, {"pk": 11, "model": "main.turn", "fields": {"complete": true, "date_end": null, "date_start": "2010-10-15 13:50:19", "user": 2, "total_points": 40, "room": 1}}, {"pk": 12, "model": "main.turn", "fields": {"complete": false, "date_end": null, "date_start": "2010-10-15 13:50:34", "user": 2, "total_points": 0, "room": 1}}, {"pk": 1, "model": "main.result", "fields": {"answer": "7", "index": 1, "question": 4, "turn": 1}}, {"pk": 4, "model": "main.result", "fields": {"answer": "", "index": 1, "question": 4, "turn": 2}}, {"pk": 7, "model": "main.result", "fields": {"answer": "16", "index": 1, "question": 7, "turn": 3}}, {"pk": 10, "model": "main.result", "fields": {"answer": "", "index": 1, "question": 7, "turn": 4}}, {"pk": 13, "model": "main.result", "fields": {"answer": "2", "index": 1, "question": 10, "turn": 5}}, {"pk": 16, "model": "main.result", "fields": {"answer": "2", "index": 1, "question": 10, "turn": 6}}, {"pk": 19, "model": "main.result", "fields": {"answer": "2", "index": 1, "question": 10, "turn": 7}}, {"pk": 22, "model": "main.result", "fields": {"answer": "2", "index": 1, "question": 10, "turn": 8}}, {"pk": 25, "model": "main.result", "fields": {"answer": "2", "index": 1, "question": 10, "turn": 9}}, {"pk": 28, "model": "main.result", "fields": {"answer": "", "index": 1, "question": 10, "turn": 10}}, {"pk": 31, "model": "main.result", "fields": {"answer": "4", "index": 1, "question": 1, "turn": 11}}, {"pk": 34, "model": "main.result", "fields": {"answer": "", "index": 1, "question": 1, "turn": 12}}, {"pk": 2, "model": "main.result", "fields": {"answer": "100", "index": 2, "question": 5, "turn": 1}}, {"pk": 5, "model": "main.result", "fields": {"answer": "", "index": 2, "question": 5, "turn": 2}}, {"pk": 8, "model": "main.result", "fields": {"answer": "18", "index": 2, "question": 8, "turn": 3}}, {"pk": 11, "model": "main.result", "fields": {"answer": "", "index": 2, "question": 8, "turn": 4}}, {"pk": 14, "model": "main.result", "fields": {"answer": "2", "index": 2, "question": 11, "turn": 5}}, {"pk": 17, "model": "main.result", "fields": {"answer": "2", "index": 2, "question": 11, "turn": 6}}, {"pk": 20, "model": "main.result", "fields": {"answer": "2", "index": 2, "question": 11, "turn": 7}}, {"pk": 23, "model": "main.result", "fields": {"answer": "2", "index": 2, "question": 11, "turn": 8}}, {"pk": 26, "model": "main.result", "fields": {"answer": "2", "index": 2, "question": 11, "turn": 9}}, {"pk": 29, "model": "main.result", "fields": {"answer": "", "index": 2, "question": 11, "turn": 10}}, {"pk": 32, "model": "main.result", "fields": {"answer": "73", "index": 2, "question": 2, "turn": 11}}, {"pk": 35, "model": "main.result", "fields": {"answer": "", "index": 2, "question": 2, "turn": 12}}, {"pk": 3, "model": "main.result", "fields": {"answer": "29", "index": 3, "question": 6, "turn": 1}}, {"pk": 6, "model": "main.result", "fields": {"answer": "", "index": 3, "question": 6, "turn": 2}}, {"pk": 9, "model": "main.result", "fields": {"answer": "100", "index": 3, "question": 9, "turn": 3}}, {"pk": 12, "model": "main.result", "fields": {"answer": "", "index": 3, "question": 9, "turn": 4}}, {"pk": 15, "model": "main.result", "fields": {"answer": "3", "index": 3, "question": 12, "turn": 5}}, {"pk": 18, "model": "main.result", "fields": {"answer": "3", "index": 3, "question": 12, "turn": 6}}, {"pk": 21, "model": "main.result", "fields": {"answer": "3", "index": 3, "question": 12, "turn": 7}}, {"pk": 24, "model": "main.result", "fields": {"answer": "3", "index": 3, "question": 12, "turn": 8}}, {"pk": 27, "model": "main.result", "fields": {"answer": "3", "index": 3, "question": 12, "turn": 9}}, {"pk": 30, "model": "main.result", "fields": {"answer": "", "index": 3, "question": 12, "turn": 10}}, {"pk": 33, "model": "main.result", "fields": {"answer": "250", "index": 3, "question": 3, "turn": 11}}, {"pk": 36, "model": "main.result", "fields": {"answer": "", "index": 3, "question": 3, "turn": 12}}, {"pk": 22, "model": "auth.permission", "fields": {"codename": "add_logentry", "name": "Can add log entry", "content_type": 8}}, {"pk": 23, "model": "auth.permission", "fields": {"codename": "change_logentry", "name": "Can change log entry", "content_type": 8}}, {"pk": 24, "model": "auth.permission", "fields": {"codename": "delete_logentry", "name": "Can delete log entry", "content_type": 8}}, {"pk": 4, "model": "auth.permission", "fields": {"codename": "add_group", "name": "Can add group", "content_type": 2}}, {"pk": 5, "model": "auth.permission", "fields": {"codename": "change_group", "name": "Can change group", "content_type": 2}}, {"pk": 6, "model": "auth.permission", "fields": {"codename": "delete_group", "name": "Can delete group", "content_type": 2}}, {"pk": 10, "model": "auth.permission", "fields": {"codename": "add_message", "name": "Can add message", "content_type": 4}}, {"pk": 11, "model": "auth.permission", "fields": {"codename": "change_message", "name": "Can change message", "content_type": 4}}, {"pk": 12, "model": "auth.permission", "fields": {"codename": "delete_message", "name": "Can delete message", "content_type": 4}}, {"pk": 1, "model": "auth.permission", "fields": {"codename": "add_permission", "name": "Can add permission", "content_type": 1}}, {"pk": 2, "model": "auth.permission", "fields": {"codename": "change_permission", "name": "Can change permission", "content_type": 1}}, {"pk": 3, "model": "auth.permission", "fields": {"codename": "delete_permission", "name": "Can delete permission", "content_type": 1}}, {"pk": 7, "model": "auth.permission", "fields": {"codename": "add_user", "name": "Can add user", "content_type": 3}}, {"pk": 8, "model": "auth.permission", "fields": {"codename": "change_user", "name": "Can change user", "content_type": 3}}, {"pk": 9, "model": "auth.permission", "fields": {"codename": "delete_user", "name": "Can delete user", "content_type": 3}}, {"pk": 13, "model": "auth.permission", "fields": {"codename": "add_contenttype", "name": "Can add content type", "content_type": 5}}, {"pk": 14, "model": "auth.permission", "fields": {"codename": "change_contenttype", "name": "Can change content type", "content_type": 5}}, {"pk": 15, "model": "auth.permission", "fields": {"codename": "delete_contenttype", "name": "Can delete content type", "content_type": 5}}, {"pk": 31, "model": "auth.permission", "fields": {"codename": "add_question", "name": "Can add question", "content_type": 11}}, {"pk": 32, "model": "auth.permission", "fields": {"codename": "change_question", "name": "Can change question", "content_type": 11}}, {"pk": 33, "model": "auth.permission", "fields": {"codename": "delete_question", "name": "Can delete question", "content_type": 11}}, {"pk": 37, "model": "auth.permission", "fields": {"codename": "add_result", "name": "Can add result", "content_type": 13}}, {"pk": 38, "model": "auth.permission", "fields": {"codename": "change_result", "name": "Can change result", "content_type": 13}}, {"pk": 39, "model": "auth.permission", "fields": {"codename": "delete_result", "name": "Can delete result", "content_type": 13}}, {"pk": 28, "model": "auth.permission", "fields": {"codename": "add_room", "name": "Can add room", "content_type": 10}}, {"pk": 29, "model": "auth.permission", "fields": {"codename": "change_room", "name": "Can change room", "content_type": 10}}, {"pk": 30, "model": "auth.permission", "fields": {"codename": "delete_room", "name": "Can delete room", "content_type": 10}}, {"pk": 34, "model": "auth.permission", "fields": {"codename": "add_turn", "name": "Can add turn", "content_type": 12}}, {"pk": 35, "model": "auth.permission", "fields": {"codename": "change_turn", "name": "Can change turn", "content_type": 12}}, {"pk": 36, "model": "auth.permission", "fields": {"codename": "delete_turn", "name": "Can delete turn", "content_type": 12}}, {"pk": 25, "model": "auth.permission", "fields": {"codename": "add_userprofile", "name": "Can add user profile", "content_type": 9}}, {"pk": 26, "model": "auth.permission", "fields": {"codename": "change_userprofile", "name": "Can change user profile", "content_type": 9}}, {"pk": 27, "model": "auth.permission", "fields": {"codename": "delete_userprofile", "name": "Can delete user profile", "content_type": 9}}, {"pk": 16, "model": "auth.permission", "fields": {"codename": "add_session", "name": "Can add session", "content_type": 6}}, {"pk": 17, "model": "auth.permission", "fields": {"codename": "change_session", "name": "Can change session", "content_type": 6}}, {"pk": 18, "model": "auth.permission", "fields": {"codename": "delete_session", "name": "Can delete session", "content_type": 6}}, {"pk": 19, "model": "auth.permission", "fields": {"codename": "add_site", "name": "Can add site", "content_type": 7}}, {"pk": 20, "model": "auth.permission", "fields": {"codename": "change_site", "name": "Can change site", "content_type": 7}}, {"pk": 21, "model": "auth.permission", "fields": {"codename": "delete_site", "name": "Can delete site", "content_type": 7}}, {"pk": 1, "model": "auth.user", "fields": {"username": "test", "first_name": "Eric", "last_name": "Cartman", "is_active": true, "is_superuser": true, "is_staff": true, "last_login": "2010-10-15 13:56:34", "groups": [], "user_permissions": [], "password": "sha1$59aea$c0f29c76f430fb25c1f93856b104a222232a1324", "email": "[email protected]", "date_joined": "2010-10-15 10:35:58"}}, {"pk": 2, "model": "auth.user", "fields": {"username": "vegardoj", "first_name": "Vegard ", "last_name": "Test", "is_active": true, "is_superuser": false, "is_staff": false, "last_login": "2010-10-15 13:50:10", "groups": [], "user_permissions": [], "password": "sha1$154b3$75b41062e9d9059a52ebc2fb3e41769a8e8e6fbf", "email": "[email protected]", "date_joined": "2010-10-15 13:50:07"}}] \ No newline at end of file diff --git a/main/forms.py b/main/forms.py index aed5f77..f498879 100644 --- a/main/forms.py +++ b/main/forms.py @@ -1,34 +1,34 @@ from django.contrib.auth.models import User from django import forms class SignupForm(forms.Form): Brukernavn = forms.CharField(max_length=30) Epost = forms.EmailField(); Passord = forms.CharField(max_length=30, widget=forms.PasswordInput(render_value=False)) Bekreft_Passord = forms.CharField(max_length=30, widget=forms.PasswordInput(render_value=False)) Fornavn = forms.CharField(max_length=30) Etternavn = forms.CharField(max_length=30) def clean_username(self): try: - User.objects.get(username=self.cleaned_data['username']) + User.objects.get(username=self.cleaned_data['Brukernavn']) except User.DoesNotExist: - return self.cleaned_data['username'] - raise forms.ValidationError("This username is already in use") + return self.cleaned_data['Brukernavn'] + raise forms.ValidationError("Dette brukernavnet er allerede tatt.") def clean(self): - if 'password1' in self.changed_data and 'password2' in self.changed_data: - if self.cleaned_data['password1'] != self.cleaned_data['password2']: - raise forms.ValidationError("Passwords do not match") + if 'Passord' in self.changed_data and 'Bekreft_Passord' in self.changed_data: + if self.cleaned_data['Passord'] != self.cleaned_data['Bekreft_Passord']: + raise forms.ValidationError("Passordene er ikke like") return self.cleaned_data def save(self): new_user = User.objects.create_user(username=self.cleaned_data['Brukernavn'], email=self.cleaned_data['Epost'], password=self.cleaned_data['Passord']) new_user.first_name = self.cleaned_data['Fornavn'] new_user.last_name = self.cleaned_data['Etternavn'] new_user.save() return new_user
ThomasPedersen/mattespill
3f9c94b7f548f7c9649bc0ba80032c6cd0d4eae9
fixed homepage logics
diff --git a/main/templates/home.html b/main/templates/home.html index 87a087f..25dc664 100644 --- a/main/templates/home.html +++ b/main/templates/home.html @@ -1,123 +1,123 @@ {% extends "outer.html" %} {% block head %} <script src="/media/home.js" type="text/javascript"></script> <style type="text/css"> #right_content { /*background-color: #eaeaea; border: .3em solid #ddd;*/ padding: 1em 2em; text-align: center; float: right; } #left_content { padding: .5em 0em; } img#treasure_chest { width: 10em; } #room_box_container a:hover { text-decoration: none; } #room_box_container { width: 27em; height: 27em; } #room_box_container p { color: #fff; text-decoration: none; } #addition_box { background-color: #76ce76; border: .5em solid #60a860; } #subtraction_box { background-color: #dddd51; border: .5em solid #c2c247; float: right; } #multiplication_box { margin-top: 1em; background-color: #eca657; border: .5em solid #c28847; } #division_box { margin-top: 1em; background-color: #ec5757; border: .5em solid #c94a4a; float: right; } .room_box { -moz-border-radius: 1.5em; -webkit-border-radius: 1.5em; border-radius: 1.5em; width: 12em; height: 12em; position: relative; } .restricted_room_msg { position: absolute; bottom: 0; left: 0; right: 0; text-align: center; padding: .4em; color: #fff; -text-shadow: #fff 0 0 1px; background: rgba(0, 0, 0, 0.2); display: none; -moz-border-radius: 1em; -webkit-border-radius: 1em; border-radius: 1em; } .restricted_room_msg > div { opacity: 1; } .room_sign { /*margin-top: -.1em;*/ text-align: center; font-weight: bold; font-size: 10em; color: #fff; } .room_sign a { color: inherit; text-decoration: none; } /* http://robertnyman.com/2010/01/11/css-background-transparency-without-affecting-child-elements-through-rgba-and-filters/ */ </style> {% endblock %} {% block content %} <div id="right_content"> <p class="chest_header">Skattekiste</p> <img id="treasure_chest" src="/media/images/treasurechest.png" alt="skattekiste" /> <p class="gold_coins">Du har <span class="gold_text"> {{ user.get_profile.points }} </span> gullmynter</p> </div> <div id="left_content"> + <h1>Velg ditt rom</h1> <div id="room_box_container"> - - <a href="/room/2/"><div id="subtraction_box" class="room_box"> - {% if user.get_profile.points >= rooms.2.required_points %}<div class="restricted_room_msg"><div><b>Krav:<br />{{ rooms.2.required_points}} gullmynter!</b></div></div>{% endif %} - <div class="room_sign">&minus;</div> + <div id="subtraction_box" class="room_box"> + {% if user.get_profile.points < rooms.1.required_points %}<div class="restricted_room_msg"><div><b>Krav:<br />{{ rooms.1.required_points}} gullmynter!</b></div></div>{% endif %} + <div class="room_sign">{% if user.get_profile.points >= rooms.1.required_points %}<a href="/room/2/">{% endif %}&minus;{% if user.get_profile.points >= rooms.1.required_points %}</a>{% endif %}</div> </div></a> - <a href="/room/1/"><div id="addition_box" class="room_box"> - {% if user.get_profile.points >= rooms.1.required_points %}<div class="restricted_room_msg"><div><b>Krav:<br />{{ rooms.1.required_points }} gullmynter!</b></div></div>{% endif %} - <div class="room_sign">+</div> + <div id="addition_box" class="room_box"> + {% if user.get_profile.points < rooms.0.required_points %}<div class="restricted_room_msg"><div><b>Krav:<br />{{ rooms.0.required_points }} gullmynter!</b></div></div>{% endif %} + <div class="room_sign">{% if user.get_profile.points >= rooms.0.required_points %}<a href="/room/1/">{% endif %}+{% if user.get_profile.points >= rooms.0.required_points %}</a>{% endif %}</div> </div></a> - <a href="/room/4/"><div id="division_box" class="room_box"> - {% if user.get_profile.points >= rooms.4.required_points %}<div class="restricted_room_msg"><div><b>Krav:<br />{{ rooms.4.required_points }} gullmynter!</b></div></div>{% endif %} - <div class="room_sign">&divide;</div> + <div id="division_box" class="room_box"> + {% if user.get_profile.points < rooms.3.required_points %}<div class="restricted_room_msg"><div><b>Krav:<br />{{ rooms.3.required_points }} gullmynter!</b></div></div>{% endif %} + <div class="room_sign">{% if user.get_profile.points >= rooms.3.required_points %}<a href="/room/4/">{% endif %}&divide;{% if user.get_profile.points >= rooms.3.required_points %}</a>{% endif %}</div> </div></a> - <a href="/room/3/"><div id="multiplication_box" class="room_box"> - {% if user.get_profile.points >= rooms.3.required_points %}<div class="restricted_room_msg"><div><b>Krav:<br />{{ rooms.3.required_points }} gullmynter!</b></div></div>{% endif %} - <div class="room_sign">&times;</div> + <div id="multiplication_box" class="room_box"> + {% if user.get_profile.points < rooms.2.required_points %}<div class="restricted_room_msg"><div><b>Krav:<br />{{ rooms.2.required_points }} gullmynter!</b></div></div>{% endif %} + <div class="room_sign">{% if user.get_profile.points >= rooms.2.required_points %}<a href="/room/3/">{% endif %}&times;{% if user.get_profile.points >= rooms.2.required_points %}</a>{% endif %}</div> </div></a> </div> </div> <p id="logout_reminder">Husk &aring; <a href="/logout">avslutte spillet</a> n&aring;r du er ferdig!</p> {% endblock %}
ThomasPedersen/mattespill
f6862adfecec5523deb7e8e9adb5d54c9fc061d1
Randomize questions
diff --git a/main/views.py b/main/views.py index fbcc305..976c040 100644 --- a/main/views.py +++ b/main/views.py @@ -1,142 +1,142 @@ # -*- coding: utf-8 -*- from django.template import RequestContext, Context, loader from django.utils import simplejson from django.http import HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import render_to_response, get_object_or_404 from django.contrib import auth from django.contrib.auth.decorators import login_required from django.core import serializers from datetime import datetime from mattespill.main.models import Question, Room, Turn, Result from mattespill.main.forms import SignupForm import json login_url = '/login/' def index(request): if request.user.is_authenticated(): rooms = Room.objects.all() return render_to_response('home.html', {'user': request.user, 'home': True, \ 'rooms': rooms}) else: return HttpResponseRedirect(login_url) def room(request, room_id): if request.user.is_authenticated(): sess_room_id = request.session.get('room_id', None) if not sess_room_id or sess_room_id != room_id: room = get_object_or_404(Room, pk=room_id) else: room = get_object_or_404(Room, pk=sess_room_id) # If user does not have enough points to access room, # we redirect to index if request.user.get_profile().points < room.required_points: return HttpResponseRedirect('/') request.session['room_id'] = room_id turn_exists = False try: t = Turn.objects.get(room=room, user=request.user, complete=False) turn_exists = True except Turn.DoesNotExist: t = Turn(date_start=datetime.now(), date_end=None, user=request.user, room=room) t.save() - # Fetch 10 questions for the given room - questions = Question.objects.filter(room=room)[:10] + # Fetch 10 random questions for the given room + questions = Question.objects.filter(room=room).order_by('?')[:10] # Add Result objects (question and answer pairs) for each question i = 1 # Sequence number for each question for q in questions: result = Result(question=q, turn=t, index=i) result.save() i += 1 previous_turns = Turn.objects.filter(room=room, user=request.user, complete=True).order_by('-total_points').all() return render_to_response('room.html', {'turn_exists': turn_exists, 'turn': t, \ 'user': request.user, 'previous_turns': previous_turns}) else: return HttpResponseRedirect(login_url) def logout(request): auth.logout(request) return HttpResponseRedirect('/') def question(request): if request.user.is_authenticated(): room_id = request.session.get('room_id', None) if room_id: try: turn = Turn.objects.get(room=room_id, user=request.user, complete=False) except Turn.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) try: # The Meta.ordering defined in model will sort # the result ascending on Result.index result = Result.objects.filter(turn=turn, answer='')[:1] if not result: return render_to_response('room.html', {'turn': turn, 'user': request.user}) num_questions = Result.objects.filter(turn=turn).count() return render_to_response('question.html', {'user': request.user,'turn': turn, 'result': result[0], \ 'num_questions': num_questions, 'room_id': room_id}) except Result.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) else: return HttpResponseRedirect(login_url) def answer(request): if request.user.is_authenticated() and request.method == 'POST': room_id = request.session.get('room_id', None) if room_id and 'answer' in request.POST: given_answer = request.POST['answer'].strip() user = request.user t = get_object_or_404(Turn, room=room_id, user=user, complete=False) try: r = Result.objects.filter(turn=t, answer='') count = r.count() result = r[0] if result.index <= count: index = result.index + 1 question = Result.objects.get(turn=t, index=index).question.question else: index = -1 # No more questions question = None t.complete = True t.save() correct = given_answer == result.question.real_answer if correct: # Give user some points user.get_profile().points += result.question.points t.total_points += result.question.points else: # For wrong answer users looses question points / 2 penalty = result.question.points / 2 user.get_profile().points -= penalty t.total_points -= penalty t.save() user.get_profile().save() result.answer = given_answer result.save() return HttpResponse(json.dumps({'correct': correct, 'index': index, \ 'question': question, 'points': user.get_profile().points})) except Result.DoesNotExist: return HttpResponseRedirect('/room/%s/' % room_id) else: return HttpResponseRedirect(login_url) def signup(request): if request.method == 'POST': form = SignupForm(data=request.POST) if form.is_valid(): form.save(); return HttpResponseRedirect('/') else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request)) else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request))
ThomasPedersen/mattespill
6e9710bbb6e9902e962bd3b902584696e931c2d5
Redirect to room when refresh happens at the end of a turn
diff --git a/main/views.py b/main/views.py index 5f3d310..fbcc305 100644 --- a/main/views.py +++ b/main/views.py @@ -1,138 +1,142 @@ # -*- coding: utf-8 -*- from django.template import RequestContext, Context, loader from django.utils import simplejson from django.http import HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import render_to_response, get_object_or_404 from django.contrib import auth from django.contrib.auth.decorators import login_required from django.core import serializers from datetime import datetime from mattespill.main.models import Question, Room, Turn, Result from mattespill.main.forms import SignupForm import json login_url = '/login/' def index(request): if request.user.is_authenticated(): rooms = Room.objects.all() return render_to_response('home.html', {'user': request.user, 'home': True, \ 'rooms': rooms}) else: return HttpResponseRedirect(login_url) def room(request, room_id): if request.user.is_authenticated(): sess_room_id = request.session.get('room_id', None) if not sess_room_id or sess_room_id != room_id: room = get_object_or_404(Room, pk=room_id) else: room = get_object_or_404(Room, pk=sess_room_id) # If user does not have enough points to access room, # we redirect to index if request.user.get_profile().points < room.required_points: return HttpResponseRedirect('/') request.session['room_id'] = room_id turn_exists = False try: t = Turn.objects.get(room=room, user=request.user, complete=False) turn_exists = True except Turn.DoesNotExist: t = Turn(date_start=datetime.now(), date_end=None, user=request.user, room=room) t.save() # Fetch 10 questions for the given room questions = Question.objects.filter(room=room)[:10] # Add Result objects (question and answer pairs) for each question i = 1 # Sequence number for each question for q in questions: result = Result(question=q, turn=t, index=i) result.save() i += 1 previous_turns = Turn.objects.filter(room=room, user=request.user, complete=True).order_by('-total_points').all() return render_to_response('room.html', {'turn_exists': turn_exists, 'turn': t, \ 'user': request.user, 'previous_turns': previous_turns}) else: return HttpResponseRedirect(login_url) def logout(request): auth.logout(request) return HttpResponseRedirect('/') def question(request): if request.user.is_authenticated(): room_id = request.session.get('room_id', None) if room_id: - t = get_object_or_404(Turn, room=room_id, user=request.user, complete=False) + try: + turn = Turn.objects.get(room=room_id, user=request.user, complete=False) + except Turn.DoesNotExist: + return HttpResponseRedirect('/room/%s/' % room_id) try: # The Meta.ordering defined in model will sort # the result ascending on Result.index - result = Result.objects.filter(turn=t, answer='')[:1] + result = Result.objects.filter(turn=turn, answer='')[:1] if not result: - return render_to_response('room.html', {'turn': t, 'user': request.user}) - num_questions = Result.objects.filter(turn=t).count() - return render_to_response('question.html', {'user': request.user,'turn': t, 'result': result[0], \ + return render_to_response('room.html', {'turn': turn, 'user': request.user}) + + num_questions = Result.objects.filter(turn=turn).count() + return render_to_response('question.html', {'user': request.user,'turn': turn, 'result': result[0], \ 'num_questions': num_questions, 'room_id': room_id}) except Result.DoesNotExist: - pass + return HttpResponseRedirect('/room/%s/' % room_id) else: return HttpResponseRedirect(login_url) def answer(request): if request.user.is_authenticated() and request.method == 'POST': room_id = request.session.get('room_id', None) if room_id and 'answer' in request.POST: given_answer = request.POST['answer'].strip() user = request.user t = get_object_or_404(Turn, room=room_id, user=user, complete=False) try: r = Result.objects.filter(turn=t, answer='') count = r.count() result = r[0] if result.index <= count: index = result.index + 1 question = Result.objects.get(turn=t, index=index).question.question else: index = -1 # No more questions question = None t.complete = True t.save() correct = given_answer == result.question.real_answer if correct: # Give user some points user.get_profile().points += result.question.points t.total_points += result.question.points else: # For wrong answer users looses question points / 2 penalty = result.question.points / 2 user.get_profile().points -= penalty t.total_points -= penalty t.save() user.get_profile().save() result.answer = given_answer result.save() return HttpResponse(json.dumps({'correct': correct, 'index': index, \ 'question': question, 'points': user.get_profile().points})) except Result.DoesNotExist: - return HttpResponse('wtf') + return HttpResponseRedirect('/room/%s/' % room_id) else: return HttpResponseRedirect(login_url) def signup(request): if request.method == 'POST': form = SignupForm(data=request.POST) if form.is_valid(): form.save(); return HttpResponseRedirect('/') else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request)) else: form = SignupForm() return render_to_response('signup.html', {'form': form}, context_instance=RequestContext(request))
michaelansel/dukenow
998d233a143afd8f807178ce7f8de7d800237b25
Optimize iPhone-Places layout
diff --git a/app/views/layouts/places.iphone.erb b/app/views/layouts/places.iphone.erb index 421fb1b..dc5948c 100644 --- a/app/views/layouts/places.iphone.erb +++ b/app/views/layouts/places.iphone.erb @@ -1,92 +1,60 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> - <title>DukeNow: <%=h controller_name.capitalize %></title> + <title>DukeNow</title> <meta http-equiv="Content-type" content="text/html;charset=UTF-8" /> + + <%= stylesheet_link_tag 'iphone'%> + <meta name="viewport" content="width = device-width" /> + +</head> + +<body> + + <div id="flash_notice"><%= flash[:notice] %></div> + + +<%= yield %> + +</body> +</html> <% if RAILS_ENV == 'production' %> <script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> - <script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js"></script> <% else %> <%= javascript_include_tag 'jquery' %> - <%= javascript_include_tag 'jqueryui' %> <% end %> <script type='text/javascript'> - function toggle_drawer(id,e) { - var a = $('#'+id + " .place_long"); - var b = ""; - if(a.is(':visible')) { - a.href="#/places?expand="+id; - b = "#/places?"; - } else { - a.href="#/places?"; - b = "#/places?expand="+id; - } - a.toggle('blind'); - window.location=b; - } - $(document).ready(function() { - update_nowIndicator(); - setInterval('update_nowIndicator();update_operatingStatus();update_nextTime();', 5 *60*1000); // Update every 5 minutes + setInterval('update_operatingStatus();', 5 *60*1000); // Update every 5 minutes }); - function update_nowIndicator() { - a=document.getElementById('nowIndicatorStyle') - nowOffset = ((new Date().getHours() * 60 + new Date().getMinutes()) * 100 / (24*60)); - $(a).html( '.place .schedule .nowindicator { left: '+nowOffset.toString()+'%;}' ); - } - function update_operatingStatus() { a=$('.place'); + nowOffset = ((new Date().getHours() * 60 + new Date().getMinutes()) * 100 / (24*60)); a.removeClass('open'); a.addClass('closed'); a.each(function(){ $('.timeblock',$(this)).each(function(){ if( nowOffset>=parseFloat(this.style.left) && nowOffset<=(parseFloat(this.style.left) + parseFloat(this.style.width)) ) { b=$(this).closest('.place'); if(b.hasClass('closed')) { b.removeClass('closed'); }; b.addClass('open'); } }); }); } - - function update_nextTime() { - /* Not (really) possible by just parsing the the timeblocks - * Better off just grabbing some JSON with the proper strings - */ - } </script> - - <style id='nowIndicatorStyle'> - .place .schedule .nowindicator { display: none; } - </style> - - <%= stylesheet_link_tag 'iphone'%> - <meta name="viewport" content="width = device-width" /> - -</head> - -<body> - - <div id="flash_notice"><%= flash[:notice] %></div> - - -<%= yield %> - <!-- Begin Google Analytics --> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> try { var pageTracker = _gat._getTracker("UA-9284802-1"); pageTracker._trackPageview(); } catch(err) {}</script> <!-- End Google Analytics --> -</body> -</html>
michaelansel/dukenow
5ee5c6fc8e38a8c9e58577178a64ec9385a3f5c2
Add additional database indexes
diff --git a/db/migrate/20090801004614_dining_extension_indexes.rb b/db/migrate/20090801004614_dining_extension_indexes.rb new file mode 100644 index 0000000..880e938 --- /dev/null +++ b/db/migrate/20090801004614_dining_extension_indexes.rb @@ -0,0 +1,9 @@ +class DiningExtensionIndexes < ActiveRecord::Migration + def self.up + add_index :dining_extensions, :place_id + end + + def self.down + remove_index :dining_extensions, :place_id + end +end diff --git a/db/migrate/20090801203932_operating_time_indexes.rb b/db/migrate/20090801203932_operating_time_indexes.rb new file mode 100644 index 0000000..c1eafb0 --- /dev/null +++ b/db/migrate/20090801203932_operating_time_indexes.rb @@ -0,0 +1,11 @@ +class OperatingTimeIndexes < ActiveRecord::Migration + def self.up + add_index :operating_times, :place_id + add_index :operating_times, [:startDate, :endDate] + end + + def self.down + remove_index :operating_times, :place_id + remove_index :operating_times, [:startDate, :endDate] + end +end
michaelansel/dukenow
14cc3d6f9f93eba90548a8032417ff15a4f40419
Bugfix: Explicit table/column names in find(:conditions) required when using PostgreSQL
diff --git a/app/models/operating_time.rb b/app/models/operating_time.rb index fa55b13..b57eaca 100644 --- a/app/models/operating_time.rb +++ b/app/models/operating_time.rb @@ -1,244 +1,246 @@ class OperatingTime < ActiveRecord::Base belongs_to :place acts_as_taggable_on :operating_time_tags validates_presence_of :place_id, :endDate, :startDate validates_associated :place validate :end_after_start, :days_of_week_valid validate {|ot| 0 <= ot.length and ot.length <= 1.days } named_scope :by_place_id, lambda {|place_id|{:conditions => {:place_id => place_id}}} named_scope :by_place, lambda {|place|{:conditions => {:place_id => place.id}}} named_scope :regular, :conditions => {:override => 0} named_scope :special, :conditions => {:override => 1} - named_scope :in_range, lambda {|range|{:conditions => ["startDate <= ? AND ? <= endDate",range.last.to_date+1,range.first.to_date-1]}} + named_scope :in_range, lambda {|range|{:conditions => + ['"operating_times"."startDate" <= ? AND ? <= "operating_times"."endDate"', + range.last.to_date+1,range.first.to_date-1] }} ## DaysOfWeek Constants ## SUNDAY = 0b00000001 MONDAY = 0b00000010 TUESDAY = 0b00000100 WEDNESDAY = 0b00001000 THURSDAY = 0b00010000 FRIDAY = 0b00100000 SATURDAY = 0b01000000 ALL_DAYS = (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) ## Validations ## def end_after_start if endDate < startDate errors.add_to_base("End date cannot preceed start date") end end def days_of_week_valid days_of_week == days_of_week & (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) end ## End Validations ## # TODO Is this OperatingTime applicable at +time+ def valid_at(time=Time.now) raise NotImplementedError end # Tag Helpers %w{tag_list tags tag_counts tag_ids tag_tagging_ids tag_taggings}.each do |m| [m,m+"="].each do |m| if self.instance_methods.include?("operating_time_"+m) self.class_eval "alias #{m.to_sym} #{"operating_time_#{m}".to_sym}" end end ; end def tags_from ; operating_time_tags_from ; end def override read_attribute(:override) == 1 end def override=(mode) if mode == true or mode == "true" or mode == 1 write_attribute(:override, true) elsif mode == false or mode == "false" or mode == 0 write_attribute(:override, false) else raise ArgumentError, "Invalid override value (#{mode.inspect}); Accepts true/false, 1/0" end end def days_of_week=(newDow) if not ( newDow & ALL_DAYS == newDow ) # Invalid input raise ArgumentError, "Not a valid value for days_of_week (#{newDow.inspect})" end write_attribute(:days_of_week, newDow & ALL_DAYS) @days_of_weekHash = nil @days_of_weekArray = nil @days_of_weekString = nil end ## days_of_week Helpers ## # Hash mapping day of week (Symbol) to valid(true)/invalid(false) def days_of_week_hash @days_of_week_hash ||= { :sunday => (days_of_week & SUNDAY ) > 0, :monday => (days_of_week & MONDAY ) > 0, :tuesday => (days_of_week & TUESDAY ) > 0, :wednesday => (days_of_week & WEDNESDAY ) > 0, :thursday => (days_of_week & THURSDAY ) > 0, :friday => (days_of_week & FRIDAY ) > 0, :saturday => (days_of_week & SATURDAY ) > 0 } end # Array beginning with Sunday of valid(true)/inactive(false) values def days_of_week_array dow = days_of_week_hash @days_of_week_array ||= [ dow[:sunday], dow[:monday], dow[:tuesday], dow[:wednesday], dow[:thursday], dow[:friday], dow[:saturday] ] end # Human-readable string of applicable days of week def days_of_week_string dow = days_of_week_hash @days_of_week_string ||= (dow[:sunday] ? "Su" : "") + (dow[:monday] ? "M" : "") + (dow[:tuesday] ? "Tu" : "") + (dow[:wednesday] ? "W" : "") + (dow[:thursday] ? "Th" : "") + (dow[:friday] ? "F" : "") + (dow[:saturday] ? "Sa" : "") end ## End days_of_week Helpers ## # Returns the next full occurrence of these operating time rule. # If we are currently within a valid time range, it will look forward for the # <em>next</em> opening time def next_times(at = Time.now) at = at.midnight unless at.respond_to? :offset return nil if length == 0 return nil if at.to_date > endDate # Schedules end at 23:59 of the stored endDate at = startDate.midnight if at < startDate # This schedule hasn't started yet, skip to startDate # Next occurrence is later today # This is the only time the "time" actually matters; # after today, all we care about is the date if days_of_week_array[at.wday] and start >= at.offset open = at.midnight + start close = open + length return [open,close] end # We don't care about the time offset anymore, jump to the next midnight at = at.midnight + 1.day # NOTE This also has the added benefit of preventing an infinite loop # from occurring if +at+ gets shifted by 0.days further down. # Shift days_of_weekArray so that +at+ is first element dow = days_of_week_array[at.wday..-1] + days_of_week_array[0..(at.wday-1)] # NOTE The above call does something a little quirky: # In the event that at.wday = 0, it concatenates the array with itself. # Since we are only interested in the first true value, this does not # cause a problem, but could probably be cleaned up if done so carefully. # Next day of the week this schedule is valid for (relative to current day) shift = dow.index(true) if shift # Skip forward at = at + shift.days else # Give up, there are no more occurrences # TODO Test edge case: valid for 1 day/week return nil end # Recurse to rerun the validation routines return next_times(at) end alias :to_times :next_times def to_xml(options = {}) #super(params.merge({:only => [:id, :place_id], :methods => [ {:times => :next_times}, :start, :length, :startDate, :endDate ]})) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] options[:skip_instruct] = true xml.tag!(self.class.to_s.underscore.dasherize) do xml.id(self.id) xml.place_id(self.place_id) #xml.place_name(self.place.name) #xml.place_location(self.place.location) #xml.place_phone(self.place.phone) xml.details(self.details) xml.tags do |xml| self.tag_list.each do |tag| xml.tag(tag) end end xml.start(self.start) xml.length(self.length) self.days_of_week_hash.to_xml(options.merge(:root => :days_of_week)) xml.startDate(self.startDate) xml.endDate(self.endDate) xml.override(self.override) open,close = self.next_times(Date.today) if open.nil? or close.nil? xml.tag!(:next_times.to_s.dasherize, :for => Date.today) else xml.tag!(:next_times.to_s.dasherize, :for => Date.today) do |xml| xml.open(open.xmlschema) xml.close(close.xmlschema) end end end end ##### TODO DEPRECATED METHODS ##### # Returns a RelativeTime object representing this OperatingTime def relativeTime @relativeTime ||= RelativeTime.new(self, :opensAt, :length) end; protected :relativeTime # Backwards compatibility with old database schema # TODO GET RID OF THIS!!! def flags ( (override ? 1 : 0) << 7) | read_attribute(:days_of_week) end # FIXME Deprecated, use +override+ instead def special override end # Input: isSpecial = true/false # FIXME Deprecated, use +override=+ instead def special=(isSpecial) if isSpecial == true or isSpecial == "true" or isSpecial == 1 self.override = true elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 self.override = false end end end
michaelansel/dukenow
f3a2acb44dd5d3779402cbd6668f4e46cace60b3
Add labels to Place index schedules
diff --git a/app/models/place.rb b/app/models/place.rb index b266d8c..6de59d5 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,262 +1,261 @@ class Place < ActiveRecord::Base DEBUG = false has_many :operating_times has_one :dining_extension acts_as_taggable_on :tags validates_presence_of :name def special_operating_times OperatingTime.special.by_place(self).find(:all) end def regular_operating_times OperatingTime.regular.by_place(self).find(:all) end # Returns an array of Times representing the opening and closing times # of this Place between +startAt+ and +endAt+ def schedule(startAt,endAt,opts={}) ## Caching ## @schedules ||= {} if @schedules[(startAt.xmlschema+endAt.xmlschema+opts.to_s).hash] return @schedules[(startAt.xmlschema+endAt.xmlschema+opts.to_s).hash] end ## End Caching ## # TODO Handle events starting within the range but ending outside of it? # TODO Offload this selection to the database; okay for testing though # NOTE This is actually faster thanks to the query cache for small numbers of operating times, but not very scalable #all_regular_operating_times = OperatingTime.find(:all, :conditions => {:place_id => self.id, :override => 0}).select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} #all_special_operating_times = OperatingTime.find(:all, :conditions => {:place_id => self.id, :override => 1}).select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} # Select all relevant times (1 day buffer on each end) # NOTE Make sure to use generous date comparisons to allow for midnight rollovers all_regular_operating_times = OperatingTime.regular.by_place_id(self.id).in_range(startAt..endAt).find(:all) all_special_operating_times = OperatingTime.special.by_place_id(self.id).in_range(startAt..endAt).find(:all) puts "\nRegular OperatingTimes: #{all_regular_operating_times.inspect}" if DEBUG puts "\nSpecial OperatingTimes: #{all_special_operating_times.inspect}" if DEBUG regular_times = [] special_times = [] special_ranges = [] all_special_operating_times.each do |ot| puts "\nSpecial Scheduling for: #{ot.inspect}" if DEBUG # Special Case: Overriding with NO times (e.g. closed all day) if ot.start == 0 and ot.length == 0 and startAt.to_date <= ot.startDate # Block out the range, but don't add the "null Times" special_ranges << Range.new(ot.startDate,ot.endDate) next end # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt.midnight : startAt - 1.day puts "EarlyStart: #{earlyStart.inspect}" if DEBUG # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do if DEBUG puts "Open: #{open}" puts "Close: #{close}" puts "Start Date: #{ot.startDate} (#{ot.startDate.class})" puts "End Date: #{ot.endDate} (#{ot.endDate.class})" end if close < startAt # Skip forward to the first occurrance in our time range puts "Seeking: #{close} < #{startAt}" if DEBUG open,close = ot.next_times(close) next end special_times << [open,close] special_ranges << Range.new(ot.startDate,ot.endDate) open,close = ot.next_times(close) end end puts "\nSpecial Times: #{special_times.inspect}" if DEBUG puts "\nSpecial Ranges: #{special_ranges.inspect}" if DEBUG all_regular_operating_times.each do |ot| puts "\nRegular Scheduling for: #{ot.inspect}" if DEBUG # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day puts "EarlyStart: #{earlyStart.inspect}" if DEBUG # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) if DEBUG puts "" puts "Open: #{open}" puts "Close: #{close}" end if open.nil? # No valid occurrences in the future puts "Skipping: No valid occurrences in the future." if DEBUG next end while not open.nil? and open <= endAt do if DEBUG puts "" puts "Open: #{open}" puts "Close: #{close}" end if close < startAt # Skip forward to the first occurrance in our time range puts "Seeking: #{close} < #{startAt}" if DEBUG open,close = ot.next_times(close) next end overridden = false special_ranges.each do |sr| overridden ||= sr.member?(open.to_date) end if overridden puts "Overridden" if DEBUG open,close = ot.next_times(close) next end # FIXME Causing an infinite loop; would be nice if this worked #open = startAt if open < startAt #close = endAt if close > endAt regular_times << [open,close] open,close = ot.next_times(close) end end puts "\nRegular Times: #{regular_times.inspect}" if DEBUG # TODO Handle schedule overrides # TODO Handle combinations (i.e. part special, part regular) final_schedule = (regular_times+special_times).sort{|a,b|a[0] <=> b[0]} ## Truncate times larger than range ## if opts[:truncate] final_schedule.each_index do |i| final_schedule[i][0] = startAt.dup if final_schedule[i][0] < startAt final_schedule[i][1] = endAt.dup if final_schedule[i][1] > endAt end end ## End truncating ## ## Caching ## @schedules ||= {} @schedules[(startAt.xmlschema+endAt.xmlschema+opts.to_s).hash] = final_schedule ## End caching ## final_schedule end def daySchedule(at = Date.today, opts={}) at = at.to_date if at.class == Time or at.class == DateTime # Allow daySchedule(:truncate => true) if at.class == Hash opts = at at = Date.today end opts[:truncate] ||= false day_schedule = schedule(at.midnight,(at+1).midnight, :truncate => opts[:truncate]) #schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } #schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end =end day_schedule.sort{|a,b|a[0] <=> b[0]} end def currentSchedule(at = Time.now) puts "At(cS): #{at}" if DEBUG daySchedule(at).select { |open,close| puts "Open(cS): #{open}" if DEBUG puts "Close(cS): #{close}" if DEBUG open <= at and at <= close }[0] end def open?(at = Time.now) - a = currentSchedule(at) - return a ? true : false + !currentSchedule(at).nil? end alias :open :open? def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end def to_xml(options = {}) #super(options.merge({:only => [:id, :name, :location, :phone], :methods => [ :open, :daySchedule ] })) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] options[:skip_instruct] = true xml.place do xml.id(self.id) xml.name(self.name) xml.location(self.location) xml.building_id(self.building_id) xml.phone(self.phone) xml.tags do |xml| self.tag_list.each do |tag| xml.tag(tag) end end self.dining_extension.to_xml(options.merge({:no_id => true})) unless self.dining_extension.nil? xml.open(self.open?) if options[:schedule_from] and options[:schedule_to] sched = schedule(options[:schedule_from],options[:schedule_to]) sched_opts = {:from => options[:schedule_from].xmlschema, :to => options[:schedule_to].xmlschema } elsif options[:schedule_for_date] sched = daySchedule(options[:schedule_for_date]) sched_opts = {:on => options[:schedule_for_date].to_date} else sched = daySchedule(Date.today) sched_opts = {:on => Date.today} end if sched.nil? or sched.empty? xml.schedule(sched_opts) else xml.schedule(sched_opts) do |xml| sched.each do |open,close| xml.open(open.xmlschema) xml.close(close.xmlschema) end end end end end end diff --git a/app/views/places/index.html.erb b/app/views/places/index.html.erb index 56e156e..bc37275 100644 --- a/app/views/places/index.html.erb +++ b/app/views/places/index.html.erb @@ -1,110 +1,114 @@ <% @places.each do |place| %> <% if RAILS_ENV == 'development' %> <!-- TODO: Remove the following comment (for debugging only) --> <!-- <%= place.inspect %> --> <% end %> <div class="<%=h placeClasses(place) %>" id="place<%=h place.id %>"> <div class="place_short"> <a class="place_name" title="<%=h place.name %>" onclick="toggle_drawer('place<%=h place.id %>',event);return false;" href="<%=h url_for(place) %>"> <span class="bubble-left"></span> <span class="name"><%=h place.name %></span> <span class="bubble-right"></span> </a> <div class="next_time"> <% next_time_words,next_time_time = next_time place %> <div class="next_time_words"><%=h next_time_words %></div> <div class="next_time_time"><%=h next_time_time %></div> </div> </div> <div class="place_long" style="display:none;"> <div class="details"> <div class="location">Location: <span><%=h place.location %></span></div> <div class="phone">Phone: <span><%=h place.phone %></span></div> <%= link_to 'More Info', place, :class => "more_info" %> <a class="weekly_schedule" href="#weekly_schedule">Weekly Schedule</a> <div class="tags"> <span>Tags</span> <% if place.tags != [] %> <% place.tags[0..-2].each do |tag| %> <a class="tag" href="#tag=<%=h tag.name %>"><%=h tag.name %></a>, <% end %> <a class="tag" href="#tag=<%=h place.tags[-1].name %>"><%=h place.tags[-1].name %></a> <% end # if place.tags != [] %> </div> </div> <!-- TODO: Load schedule info to generate timeblocks --> - <div class="schedule"><div class="inner-schedule"> - <div class="nowindicator"></div> - <!-- // Test timeblock - <div class="timeblock" id="timeblock_<%=h place.id %>_0" style="left: 0%; width: 100%;"> - <div class="bubble-left"></div> - <div class="bubble-middle"></div> - <div class="bubble-right"></div> + <div class="schedule"> + <div class="labels"> + <% 13.times do |i| %> + <div class="label divider" style="left:<%=h 100.0*2*i/24 %>%;"></div> + <div class="label text" style="left:<%=h 100.0*(2*i-1)/24 %>%;"><%=h (Time.now.midnight + 2*i.hours).strftime('%I%p').sub(/^0+/,'').downcase %></div> + <% unless i == 12 %> + <div class="label divider" style="left:<%=h 100.0*(2*i+1)/24 %>%;"></div> + <% end %> + <% end # 13.times do |i| %> </div> - --> - <% place.daySchedule(:truncate => true).each do |open,close| %> - <div class="timeblock" id="timeblock_<%=h place.id %>_<%=h rand %>" style="<%=h time_block_style(open,close) %>"> - <div class="bubble-left"></div> - <div class="bubble-middle"></div> - <div class="bubble-right"></div> - </div> - <% end # place.daySchedule.each %> - </div></div> <!-- div.schedule, div.inner-schedule --> + <div class="inner-schedule"> + <div class="nowindicator"></div> + <% place.daySchedule(:truncate => true).each do |open,close| %> + <div class="timeblock" id="timeblock_<%=h place.id %>_<%=h rand %>" style="<%=h time_block_style(open,close) %>"> + <div class="bubble-left"></div> + <div class="bubble-middle"></div> + <div class="bubble-right"></div> + </div> + <% end # place.daySchedule.each %> + </div> <!-- div.inner-schedule --> + </div> <!-- div.schedule --> </div> </div> <% end # @places.each %> <% =begin %> <!-- TODO: Reimplement under new design --> <div class="tagCloud"> <div style="font-size:2em;font-weight:bold;text-align:center;line-height:1.5em;">Tags</div> <div id="selectedTags" style="border-top: 1px solid black; padding-top:5px;"> <% @selected_tags.each do |tag_name| %> <%= link_to tag_name, { :action => :tag, :id => tag_name }, :id => "selected_tag_#{tag_name}", :class => "selectedTag", :onclick => "handleTagClick('#{h tag_name}',event);return false;" %> <% end %> </div> <script> // <%= @selected_tags.inspect %> <% if not @selected_tags.nil? %> document.lockedTags = <%= @selected_tags.join(", ").inspect %>; <% else %> document.lockedTags = ""; <% end %> </script> <div style="border-top: 1px solid black;padding-top:5px;"> <% tag_cloud @tag_counts, %w(size1 size2 size3 size4 size5 size6) do |tag, css_class| %> <%= link_to tag.name, { :action => :tag, :id => tag.name }, :id => "tag_#{tag.name}", :class => css_class, :onclick => "handleTagClick('#{h tag.name}',event);return false;" %> <% end %> </div> </div> <!-- TODO: Reimplement under new design --> <div style="position:absolute; right:0; top:0;"> <%= link_to "Yesterday", :at => Date.today - 1.day %><br/> <%= link_to "Today", :at => Date.today %><br/> <%= link_to "Tomorrow", :at => Date.today + 1.day %><br/> <%= link_to Date::DAYNAMES[(Date.today + 2.day).wday], :at => Date.today + 2.day %><br/> </div> <% =end %> diff --git a/public/stylesheets/main.css b/public/stylesheets/main.css index 338f0f3..d173bbc 100644 --- a/public/stylesheets/main.css +++ b/public/stylesheets/main.css @@ -1,376 +1,394 @@ /* Reset CSS */ /* v1.0 | 20080212 */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td { margin: 0; padding: 0; border: 0; outline: 0; font-size: 100%; vertical-align: baseline; background: transparent; } body { line-height: 1; } ol, ul { list-style: none; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; } /* remember to define focus styles! */ :focus { outline: 0; } /* remember to highlight inserts somehow! */ ins { text-decoration: none; } del { text-decoration: line-through; } /* tables still need 'cellspacing="0"' in the markup */ table { border-collapse: collapse; border-spacing: 0; } /* Backgrounds * * Body: f1f7f2 * Box: b3daff */ a { text-decoration: none; outline: none; } a:hover, a:visited, a:link { color: black; } body { background-color: #F1F7F2; font-family: Arial, Helvetica, Sans-Serif; margin: 0; padding: 0; left: 0; right: 0; top: 0; bottom: 0; width: auto; height: auto; position: absolute; } #container { width: 960px; margin-left: auto; margin-right: auto; position: relative; } #header { background-color: #B2DAFF; height: 60px; -moz-border-radius-bottomleft: 10px; -moz-border-radius-bottomright: 10px; -webkit-border-bottom-left-radius: 10px; -webkit-border-bottom-right-radius: 10px; border: 1px solid #0284FF; } #header h1#title { position: relative; left: 80px; width: 700px; font-size: 60px; text-align: center; } #header h2#controller { display: none; } #sidebar { position: absolute; right: 0px; top: 90px; width: 150px; height: 500px; background-color: #B2DAFF; -moz-border-radius: 5px; -webkit-border-radius: 5px; border: 1px solid #0284FF; } #sidebar :first-child h2 { border-top: none; } #sidebar h2 { text-align: center; border-top: 1px solid black; border-bottom: 1px solid black; } #sidebar > div { height: 300px; } #content { width: 720px; position: relative; } #content .place { position: relative; margin-top: 30px; left: 80px; width: 700px; -moz-border-radius: 5px; -webkit-border-radius: 5px; background-color: #B2DAFF; } #content .place .place_short { position: relative; height: 50px; width: 100%; /* border: 1px solid #0284FF; */ } .place_short .place_name { position: relative; display: block; top: -10px; left: -10px; height: 70px; width: 400px; background: transparent repeat-x; font-size: 40px; text-align: left; } /* Element containing name */ .place_short .place_name span.name { position: absolute; display: block; top: 0; bottom: 0; left: 0; right: 0; height: 1.1em; width: auto; margin: auto 0; /* TODO: Handle long names better */ /* padding-left: 5px; padding-right: 5px; */ /*white-space: nowrap;*/ /** Let the browser wrap and chop at an appropriate place **/ overflow: hidden; /* Long names just get cut off */ } /* Use appropriate gradient images for open/closed status */ .place.open .place_short .place_name { background-image: url('/images/place_name_bubble_open_middle.png'); } .place.closed .place_short .place_name { background-image: url('/images/place_name_bubble_closed_middle.png'); } /* CSS3 rounded corners; only with Mozilla/WebKit */ .place_short .place_name { -moz-border-radius: 10px; -webkit-border-radius: 10px; border-radius: 10px; padding-left: 10px; padding-right: 10px; } .place_short .place_name span.name { padding-left: 10px; padding-right: 10px; } /* Hide rounded corner images */ .place_short .bubble-left, .place_short .bubble-right { display: none; } /* End CSS3 rounded corners */ .place_short .next_time { position: absolute; right: 0px; top: 0px; width: 260px; height: 50px; } .next_time .next_time_words { position: absolute; top: 15px; height: 20px; width: 100px; font-size: 16px; text-align: center; color: #4A4A4A; } .next_time .next_time_time { position: relative; left: 100px; top: 4px; width: 140px; font-size: 36px; text-align: center; } #content .place .place_long { height: 200px; width: 100%; /* border: 1px solid #0284FF; border-top: none; */ } .place_long .details { position: relative; top: 20px; height: 55px; font-size: 14px; line-height: 14px; } .details .location { position: absolute; left: 20px; width: 260px; } .details .location span { position: absolute; left: 70px; width: 210px; height: 1.0em; overflow: hidden; } .details .phone { position: absolute; left: 320px; width: 210px; } .details .phone span { position: absolute; left: 60px; width: 150px; height: 1.0em; overflow: hidden; } .details .more_info { position: absolute; left: 580px; font-weight: bold; } .details .weekly_schedule { position: absolute; left: 20px; top: 30px; font-weight: bold; } .details .tags { position: absolute; left: 320px; top: 30px; width: 380px; height: 4.0em; overflow: hidden; } .details .tags span { position: absolute; left: 0;top:0; } .details .tags span:first-child+.tag { position: relative; margin-left: 60px; } .details .tags .tag { margin-left: 2px; font-style: italic; color: #4F4F4F; } .place_long .schedule { position: absolute; bottom: 10px; left: 10px; right: 10px; width: 680px; height: 50px; background-color: #D7F5FF; } +.place_long .schedule .labels { + position: absolute; + left: 10px; right: 10px; +} +.place_long .schedule .labels .label { + position: absolute; +} +.place_long .schedule .labels .label.text { + top: -12px; + width: 8.333333333%; + font-size: 10px; + text-align:center; +} +.place_long .schedule .labels .label.divider { + height: 10px; + width: 1px; + background-color: black; +} .place_long .schedule .inner-schedule { position: absolute; left: 10px; right: 10px; top: 10px; bottom: 10px; } .place_long .schedule .timeblock { top: 10px; } .place_long .schedule .timeblock, .place_long .schedule .timeblock div { position: absolute; height: 20px; } .place_long .schedule .timeblock .bubble-left { width: 10px; left: 0; background: url('/images/timeblock_bubble.png') no-repeat 0 0; } .place_long .schedule .timeblock .bubble-middle { left: 10px; right: 10px; background: url('/images/timeblock_bubble_middle.png') repeat-x; /*background-color: #4EFE4E; opacity: 0.5;*/ } .place_long .schedule .timeblock .bubble-right { width: 10px; right: 0; background: url('/images/timeblock_bubble.png') no-repeat -10px 0; } .place .schedule .nowindicator { position: absolute; width: 1px; height: 40px; top: 0; z-index: 1; background-color: #FF2D2D; }
michaelansel/dukenow
68a14ddb616a95ab61c1c66092c99d56fb3004db
Bugfix: Incorrect day names on graphic (weekly) schedule
diff --git a/app/views/places/show.html.erb b/app/views/places/show.html.erb index 6b8770d..3b830f2 100644 --- a/app/views/places/show.html.erb +++ b/app/views/places/show.html.erb @@ -1,239 +1,239 @@ <p> <b>Name:</b> <%=h @place.name %> </p> <p> <b>Location:</b> <%=h @place.location %> </p> <p> <b>Phone:</b> <%=h @place.phone %> </p> <p> <b>Tags:</b> <%=h @place.tag_list %> </p> <p> <b>Open Now?</b> <%=h (@place.open ? "Yes" : "No") %> </p> <p> <b><%= link_to "All Operating Times", place_operating_times_path(@place) %></b> </p> <p> <b>Schedule for this week:</b><br/> <%# Begin static graphic_schedule data %> <style type="text/css"> .graphic_schedule { margin: 0 auto; margin-top: 10px; } .graphic_schedule { position: relative; width: 960px; max-height: 800px; padding: 10px 0 10px 10px; -moz-border-radius: 10px; -webkit-border-radius: 10px; } .day-column { width: 128px; /* 130px - 2px border */ border-left: 2px solid; position: relative; float: left; overflow: hidden; } .top-row { position: relative; height: 1.33em; padding-top: 10px; padding-left: 40px; /* Pad over for time_labels */ } .top-row .day-column div { line-height: 1.33em; } .bottom-row { position: relative; height: 1.33em; padding-left: 40px; /* Pad over for time_labels */ } .schedule_container { clear: both; width: 100%; border-top: 1px solid; border-bottom: 1px solid; overflow: hidden; } .schedules { position: relative; max-height: 720px; overflow-x: hidden; overflow-y: scroll; -moz-border-radius: 5px; -webkit-border-radius: 5px; } .schedules .time_labels { float: left; position: relative; overflow: hidden; width: 40px; margin-bottom: -15px; } .schedules .time_labels .hour { /* total height == 30px */ padding-bottom: 14px; border-bottom: 1px solid; line-height: 15px; } .schedules .day-column { height: 720px; /* (.hour line-height + .hour padding-top/bottom + .hour border) * 24 hours */ } .day-column .time-block { position: absolute; width: 100px; margin: 0 15px; -moz-border-radius: 5px; -webkit-border-radius: 5px; } .time-block .ui-resizable-s, .time-block .drag-point { position: absolute; width: 80px; margin: 0 10px; height: 10px; bottom: 0; cursor: s-resize; } .bottom-row .wday-select { display: table-row; } .wday-select .wday { display: table-cell; padding: 0 1px; text-align: center; } .day-column .overlay-mask { position: absolute; left: 0; right: 0; top: 0; bottom: 0; width: auto; height; auto; background-color: gray; opacity: 0.75; } </style> <style type="text/css"> /** Cosmetics **/ .graphic_schedule { background-color: #B2DAFF; } .top-row .day-column div { text-align: center; } .top-row .closed-button { background-color: red; } .top-row .allday-button { background-color: green; } .schedules { border-color: gray; background-color: #F1F7F2; } .schedules .time_labels .hour { text-align: center; font-size: 12px; } .schedules .time-block { background-color: #4EFE4E; } .time-block .ui-resizable-s, .time-block .drag-point { background: transparent url('drag_point.png') no-repeat center; z-index: 1; } .wday-select .wday.selected { background-color: #389FFF; } </style> <style type="text/css" id="calculated_styles"> /* Sane defaults in event of no JavaScript */ .graphic_schedule { width: 980px; } .schedules { height: 500px; } </style> <div class="graphic_schedule"> <div class="top-row"> <% 7.times do |i| %> <div class="day-column"> - <div class="day-label"><%= Date::DAYNAMES[i] %></div> + <div class="day-label"><%= Date::DAYNAMES[(@at.wday+i)%7] %></div> <div class="menu" style="display: none;"> <a class="closed-button">Closed All Day</a> <a class="allday-button">Open 24 Hours</a> </div> </div> <% end # 7.times do %> </div> <div class="schedule_container"> <div class="schedules"> <div class="time_labels"> <div class="hour">12am</div> <% (1..11).each do |hr| %> <div class="hour"><%= hr %>am</div> <% end %> <div class="hour">12pm</div> <% (1..11).each do |hr| %> <div class="hour"><%= hr %>pm</div> <% end %> </div> <%# End static graphic_schedule data %> <% 7.times do |i| %> <div class="day-column"> <% @place.daySchedule(@at + i.days, :truncate => true).each do |open,close| %> <%# yield(open,close) %><%# puts "building time_block from #{open} to #{close}" %> <div class="time-block" style="<%= time_block_style(open, close, :direction => :vertical) %>"> <!--<div class="drag-point ui-resizable-s ui-resizable-handle"></div>--> </div> <%# end yield(open,close) %> <% end #daySchedule.each %> </div> <% end # 7.times do %> <%# Begin static graphic_schedule data %> </div> </div> <div class="bottom-row"> <% 7.times do |i| %> <div class="day-column"> <div class="wday-select"> <% (wdays = %w{Su M T W Th F Sa}).each_index do |j| %> <a class="wday color<%=(j%2)+1%><%=(i==j)?" select-locked selected":""%>" href="#wday"><%= wdays[j] %></a> <% end # %w{}.each do |wda| %> </div> </div> <% end %> </div> </div> <%# End static graphic_schedule data %> </p> <%= link_to 'Edit', edit_place_path(@place) %> | <%= link_to 'Back', places_path %>
michaelansel/dukenow
d89845e7ddf675cc0e94c1360d8e901db7ce5d90
Bugfix: XML Schema inconsistent for <schedule on="...">
diff --git a/app/models/place.rb b/app/models/place.rb index 41c99b8..b266d8c 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,262 +1,262 @@ class Place < ActiveRecord::Base DEBUG = false has_many :operating_times has_one :dining_extension acts_as_taggable_on :tags validates_presence_of :name def special_operating_times OperatingTime.special.by_place(self).find(:all) end def regular_operating_times OperatingTime.regular.by_place(self).find(:all) end # Returns an array of Times representing the opening and closing times # of this Place between +startAt+ and +endAt+ def schedule(startAt,endAt,opts={}) ## Caching ## @schedules ||= {} if @schedules[(startAt.xmlschema+endAt.xmlschema+opts.to_s).hash] return @schedules[(startAt.xmlschema+endAt.xmlschema+opts.to_s).hash] end ## End Caching ## # TODO Handle events starting within the range but ending outside of it? # TODO Offload this selection to the database; okay for testing though # NOTE This is actually faster thanks to the query cache for small numbers of operating times, but not very scalable #all_regular_operating_times = OperatingTime.find(:all, :conditions => {:place_id => self.id, :override => 0}).select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} #all_special_operating_times = OperatingTime.find(:all, :conditions => {:place_id => self.id, :override => 1}).select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} # Select all relevant times (1 day buffer on each end) # NOTE Make sure to use generous date comparisons to allow for midnight rollovers all_regular_operating_times = OperatingTime.regular.by_place_id(self.id).in_range(startAt..endAt).find(:all) all_special_operating_times = OperatingTime.special.by_place_id(self.id).in_range(startAt..endAt).find(:all) puts "\nRegular OperatingTimes: #{all_regular_operating_times.inspect}" if DEBUG puts "\nSpecial OperatingTimes: #{all_special_operating_times.inspect}" if DEBUG regular_times = [] special_times = [] special_ranges = [] all_special_operating_times.each do |ot| puts "\nSpecial Scheduling for: #{ot.inspect}" if DEBUG # Special Case: Overriding with NO times (e.g. closed all day) if ot.start == 0 and ot.length == 0 and startAt.to_date <= ot.startDate # Block out the range, but don't add the "null Times" special_ranges << Range.new(ot.startDate,ot.endDate) next end # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt.midnight : startAt - 1.day puts "EarlyStart: #{earlyStart.inspect}" if DEBUG # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do if DEBUG puts "Open: #{open}" puts "Close: #{close}" puts "Start Date: #{ot.startDate} (#{ot.startDate.class})" puts "End Date: #{ot.endDate} (#{ot.endDate.class})" end if close < startAt # Skip forward to the first occurrance in our time range puts "Seeking: #{close} < #{startAt}" if DEBUG open,close = ot.next_times(close) next end special_times << [open,close] special_ranges << Range.new(ot.startDate,ot.endDate) open,close = ot.next_times(close) end end puts "\nSpecial Times: #{special_times.inspect}" if DEBUG puts "\nSpecial Ranges: #{special_ranges.inspect}" if DEBUG all_regular_operating_times.each do |ot| puts "\nRegular Scheduling for: #{ot.inspect}" if DEBUG # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day puts "EarlyStart: #{earlyStart.inspect}" if DEBUG # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) if DEBUG puts "" puts "Open: #{open}" puts "Close: #{close}" end if open.nil? # No valid occurrences in the future puts "Skipping: No valid occurrences in the future." if DEBUG next end while not open.nil? and open <= endAt do if DEBUG puts "" puts "Open: #{open}" puts "Close: #{close}" end if close < startAt # Skip forward to the first occurrance in our time range puts "Seeking: #{close} < #{startAt}" if DEBUG open,close = ot.next_times(close) next end overridden = false special_ranges.each do |sr| overridden ||= sr.member?(open.to_date) end if overridden puts "Overridden" if DEBUG open,close = ot.next_times(close) next end # FIXME Causing an infinite loop; would be nice if this worked #open = startAt if open < startAt #close = endAt if close > endAt regular_times << [open,close] open,close = ot.next_times(close) end end puts "\nRegular Times: #{regular_times.inspect}" if DEBUG # TODO Handle schedule overrides # TODO Handle combinations (i.e. part special, part regular) final_schedule = (regular_times+special_times).sort{|a,b|a[0] <=> b[0]} ## Truncate times larger than range ## if opts[:truncate] final_schedule.each_index do |i| final_schedule[i][0] = startAt.dup if final_schedule[i][0] < startAt final_schedule[i][1] = endAt.dup if final_schedule[i][1] > endAt end end ## End truncating ## ## Caching ## @schedules ||= {} @schedules[(startAt.xmlschema+endAt.xmlschema+opts.to_s).hash] = final_schedule ## End caching ## final_schedule end def daySchedule(at = Date.today, opts={}) at = at.to_date if at.class == Time or at.class == DateTime # Allow daySchedule(:truncate => true) if at.class == Hash opts = at at = Date.today end opts[:truncate] ||= false day_schedule = schedule(at.midnight,(at+1).midnight, :truncate => opts[:truncate]) #schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } #schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end =end day_schedule.sort{|a,b|a[0] <=> b[0]} end def currentSchedule(at = Time.now) puts "At(cS): #{at}" if DEBUG daySchedule(at).select { |open,close| puts "Open(cS): #{open}" if DEBUG puts "Close(cS): #{close}" if DEBUG open <= at and at <= close }[0] end def open?(at = Time.now) a = currentSchedule(at) return a ? true : false end alias :open :open? def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end def to_xml(options = {}) #super(options.merge({:only => [:id, :name, :location, :phone], :methods => [ :open, :daySchedule ] })) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] options[:skip_instruct] = true xml.place do xml.id(self.id) xml.name(self.name) xml.location(self.location) xml.building_id(self.building_id) xml.phone(self.phone) xml.tags do |xml| self.tag_list.each do |tag| xml.tag(tag) end end self.dining_extension.to_xml(options.merge({:no_id => true})) unless self.dining_extension.nil? xml.open(self.open?) if options[:schedule_from] and options[:schedule_to] sched = schedule(options[:schedule_from],options[:schedule_to]) sched_opts = {:from => options[:schedule_from].xmlschema, :to => options[:schedule_to].xmlschema } elsif options[:schedule_for_date] sched = daySchedule(options[:schedule_for_date]) - sched_opts = {:on => options[:schedule_for_date].xmlschema} + sched_opts = {:on => options[:schedule_for_date].to_date} else sched = daySchedule(Date.today) sched_opts = {:on => Date.today} end if sched.nil? or sched.empty? xml.schedule(sched_opts) else xml.schedule(sched_opts) do |xml| sched.each do |open,close| xml.open(open.xmlschema) xml.close(close.xmlschema) end end end end end end
michaelansel/dukenow
584f303b3b3b6d9ec60b69c308df8bfe33685f8f
Add option to truncate times at boundaries when scheduling
diff --git a/TODO b/TODO index 8010228..fdc02e7 100644 --- a/TODO +++ b/TODO @@ -1,115 +1,116 @@ vim:set syntax=todo: Database Places - -- has_one :dining_extension + \- has_one :dining_extension \- name (string) -- location (lat/long) -- ?GeoKit Plugin? \- phone_number (string) DiningExtensions - -- acts_as_taggable_on :dining_tags ## needs work + \- acts_as_taggable_on :dining_tags ## needs work -- **delivery/eat-in** ## operating_time details/tag - -- more_info_url - -- owner_operator - -- payment_methods - -- logo_url + \- more_info_url + \- owner_operator + \- payment_methods + \- logo_url OperatingTimes \- place_id \- start (midnight offset in seconds) \- length (in seconds) \- startDate (Date) \- endDate (Date) \- details (String) \- override \- days_of_week (bit-wise AND of wday's) OperatingTimesTags \- name OperatingTimesTaggings (clone auto-generated) \- clone Taggings schema \- operating_time_id \- operating_times_tag_id TimePeriods -- name (String) -- startDate (Date) -- endDate (Date) API Versioning + \- Route namespacing -- Subdirectories -- rake task for adding new versions and deprecating old versions Places OperatingTimes -- Array of DateTime objects for the next N hours/days/etc -- Bulk import Excel spreadsheet -- What qualifies as a Tag versus an Attribute? Timeline OperatingTimes StartLengthSchema \- Migration Feature-parity \- schedule(from,to) \- daySchedule(date) \- currentSchedule(at) \- open?(at) Testing Unit Tests -- Database accessors Model Validations -- Prevent overlapping time periods without "override" flag Extend API \- Generate Time objects (Enumerable?) -- Add versioning DiningExtensions -- Migration -- Full unit tests + validation DiningExtensions Tags -- Migrations -- Full unit tests + validation OperatingTimes Tags \- Migration -- Full unit tests + validation -- Extend OperatingTimes.find to filter by tags -- Extend Places.open? to test delivery/dine-in tags TimePeriods -- Migration -- Full unit tests + validation -- Create integration -- View Integration API Versioning rake Tasks -- Clone for new version and increment version number -- Deprecate old version -- Hosting for web app/file server? -- Can I get help with the UI design, or will DukeMobile only be focusing on the iPhone side? -- Set "expiration" date; Send reminder emails; Show _nothing_ rather than inaccurate info Database Adjust schema to be more flexible !- Late nights: seamless midnight rollover -- Start,End => Start,Length (then, convert to real "Time"s based on @at) -- iCal RRULE (string) and parse with RiCal (pre-release) \- Add "midnight" method to Date, Time -- (?) Multiple "special"/override schedules (e.g. every weekday during Spring Break except Friday) -- Special: "normally open, but closed all day today" -- Semester-style schedules -- List of important dates (likely to be scheduling boundaries) Interface Index (Main Page) -- Hide nowIndicator after midnight instead of wrapping around -- JavaScript Tag Filtering -- Status @ DateTime Data Entry -- Bulk import (CSV, XML) -- Duke Dining PDF parser (?) -- Not worth the effort to get consistent data Web Form -- Text entry of times (drop downs, input fields) -- Quickly add/edit all times for a location -- Graphic schedule of current settings -- Show "normal" schedule in background if making an exception -- Drag/Drop/Resize-able blocks on schedule diff --git a/app/models/place.rb b/app/models/place.rb index 74ac245..41c99b8 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,249 +1,262 @@ class Place < ActiveRecord::Base DEBUG = false has_many :operating_times has_one :dining_extension acts_as_taggable_on :tags validates_presence_of :name def special_operating_times OperatingTime.special.by_place(self).find(:all) end def regular_operating_times OperatingTime.regular.by_place(self).find(:all) end # Returns an array of Times representing the opening and closing times # of this Place between +startAt+ and +endAt+ - def schedule(startAt,endAt) + def schedule(startAt,endAt,opts={}) ## Caching ## @schedules ||= {} - if @schedules[startAt.xmlschema] and - @schedules[startAt.xmlschema][endAt.xmlschema] - return @schedules[startAt.xmlschema][endAt.xmlschema] + if @schedules[(startAt.xmlschema+endAt.xmlschema+opts.to_s).hash] + return @schedules[(startAt.xmlschema+endAt.xmlschema+opts.to_s).hash] end ## End Caching ## # TODO Handle events starting within the range but ending outside of it? # TODO Offload this selection to the database; okay for testing though # NOTE This is actually faster thanks to the query cache for small numbers of operating times, but not very scalable #all_regular_operating_times = OperatingTime.find(:all, :conditions => {:place_id => self.id, :override => 0}).select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} #all_special_operating_times = OperatingTime.find(:all, :conditions => {:place_id => self.id, :override => 1}).select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} # Select all relevant times (1 day buffer on each end) # NOTE Make sure to use generous date comparisons to allow for midnight rollovers all_regular_operating_times = OperatingTime.regular.by_place_id(self.id).in_range(startAt..endAt).find(:all) all_special_operating_times = OperatingTime.special.by_place_id(self.id).in_range(startAt..endAt).find(:all) puts "\nRegular OperatingTimes: #{all_regular_operating_times.inspect}" if DEBUG puts "\nSpecial OperatingTimes: #{all_special_operating_times.inspect}" if DEBUG regular_times = [] special_times = [] special_ranges = [] all_special_operating_times.each do |ot| puts "\nSpecial Scheduling for: #{ot.inspect}" if DEBUG # Special Case: Overriding with NO times (e.g. closed all day) if ot.start == 0 and ot.length == 0 and startAt.to_date <= ot.startDate # Block out the range, but don't add the "null Times" special_ranges << Range.new(ot.startDate,ot.endDate) next end # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt.midnight : startAt - 1.day puts "EarlyStart: #{earlyStart.inspect}" if DEBUG # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do if DEBUG puts "Open: #{open}" puts "Close: #{close}" puts "Start Date: #{ot.startDate} (#{ot.startDate.class})" puts "End Date: #{ot.endDate} (#{ot.endDate.class})" end if close < startAt # Skip forward to the first occurrance in our time range puts "Seeking: #{close} < #{startAt}" if DEBUG open,close = ot.next_times(close) next end special_times << [open,close] special_ranges << Range.new(ot.startDate,ot.endDate) open,close = ot.next_times(close) end end puts "\nSpecial Times: #{special_times.inspect}" if DEBUG puts "\nSpecial Ranges: #{special_ranges.inspect}" if DEBUG all_regular_operating_times.each do |ot| puts "\nRegular Scheduling for: #{ot.inspect}" if DEBUG # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day puts "EarlyStart: #{earlyStart.inspect}" if DEBUG # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) if DEBUG puts "" puts "Open: #{open}" puts "Close: #{close}" end if open.nil? # No valid occurrences in the future puts "Skipping: No valid occurrences in the future." if DEBUG next end while not open.nil? and open <= endAt do if DEBUG puts "" puts "Open: #{open}" puts "Close: #{close}" end if close < startAt # Skip forward to the first occurrance in our time range puts "Seeking: #{close} < #{startAt}" if DEBUG open,close = ot.next_times(close) next end overridden = false special_ranges.each do |sr| overridden ||= sr.member?(open.to_date) end if overridden puts "Overridden" if DEBUG open,close = ot.next_times(close) next end # FIXME Causing an infinite loop; would be nice if this worked #open = startAt if open < startAt #close = endAt if close > endAt regular_times << [open,close] open,close = ot.next_times(close) end end puts "\nRegular Times: #{regular_times.inspect}" if DEBUG # TODO Handle schedule overrides # TODO Handle combinations (i.e. part special, part regular) final_schedule = (regular_times+special_times).sort{|a,b|a[0] <=> b[0]} + ## Truncate times larger than range ## + if opts[:truncate] + final_schedule.each_index do |i| + final_schedule[i][0] = startAt.dup if final_schedule[i][0] < startAt + final_schedule[i][1] = endAt.dup if final_schedule[i][1] > endAt + end + end + ## End truncating ## + ## Caching ## @schedules ||= {} - @schedules[startAt.xmlschema] ||= {} - @schedules[startAt.xmlschema][endAt.xmlschema] = final_schedule - ## End Caching ## + @schedules[(startAt.xmlschema+endAt.xmlschema+opts.to_s).hash] = final_schedule + ## End caching ## final_schedule end - def daySchedule(at = Date.today) + def daySchedule(at = Date.today, opts={}) at = at.to_date if at.class == Time or at.class == DateTime + # Allow daySchedule(:truncate => true) + if at.class == Hash + opts = at + at = Date.today + end + opts[:truncate] ||= false - day_schedule = schedule(at.midnight,(at+1).midnight) + day_schedule = schedule(at.midnight,(at+1).midnight, :truncate => opts[:truncate]) #schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } #schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end =end day_schedule.sort{|a,b|a[0] <=> b[0]} end def currentSchedule(at = Time.now) puts "At(cS): #{at}" if DEBUG daySchedule(at).select { |open,close| puts "Open(cS): #{open}" if DEBUG puts "Close(cS): #{close}" if DEBUG open <= at and at <= close }[0] end def open?(at = Time.now) a = currentSchedule(at) return a ? true : false end alias :open :open? def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end def to_xml(options = {}) #super(options.merge({:only => [:id, :name, :location, :phone], :methods => [ :open, :daySchedule ] })) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] options[:skip_instruct] = true xml.place do xml.id(self.id) xml.name(self.name) xml.location(self.location) xml.building_id(self.building_id) xml.phone(self.phone) xml.tags do |xml| self.tag_list.each do |tag| xml.tag(tag) end end self.dining_extension.to_xml(options.merge({:no_id => true})) unless self.dining_extension.nil? xml.open(self.open?) if options[:schedule_from] and options[:schedule_to] sched = schedule(options[:schedule_from],options[:schedule_to]) sched_opts = {:from => options[:schedule_from].xmlschema, :to => options[:schedule_to].xmlschema } elsif options[:schedule_for_date] sched = daySchedule(options[:schedule_for_date]) sched_opts = {:on => options[:schedule_for_date].xmlschema} else sched = daySchedule(Date.today) sched_opts = {:on => Date.today} end if sched.nil? or sched.empty? xml.schedule(sched_opts) else xml.schedule(sched_opts) do |xml| sched.each do |open,close| xml.open(open.xmlschema) xml.close(close.xmlschema) end end end end end end
michaelansel/dukenow
b998c800406da2a386c158b41517bfaa98505d95
Use named_scopes for OperatingTime database queries
diff --git a/app/models/operating_time.rb b/app/models/operating_time.rb index 14a651a..fa55b13 100644 --- a/app/models/operating_time.rb +++ b/app/models/operating_time.rb @@ -1,238 +1,244 @@ class OperatingTime < ActiveRecord::Base belongs_to :place acts_as_taggable_on :operating_time_tags validates_presence_of :place_id, :endDate, :startDate validates_associated :place validate :end_after_start, :days_of_week_valid validate {|ot| 0 <= ot.length and ot.length <= 1.days } + named_scope :by_place_id, lambda {|place_id|{:conditions => {:place_id => place_id}}} + named_scope :by_place, lambda {|place|{:conditions => {:place_id => place.id}}} + named_scope :regular, :conditions => {:override => 0} + named_scope :special, :conditions => {:override => 1} + named_scope :in_range, lambda {|range|{:conditions => ["startDate <= ? AND ? <= endDate",range.last.to_date+1,range.first.to_date-1]}} + ## DaysOfWeek Constants ## SUNDAY = 0b00000001 MONDAY = 0b00000010 TUESDAY = 0b00000100 WEDNESDAY = 0b00001000 THURSDAY = 0b00010000 FRIDAY = 0b00100000 SATURDAY = 0b01000000 ALL_DAYS = (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) ## Validations ## def end_after_start if endDate < startDate errors.add_to_base("End date cannot preceed start date") end end def days_of_week_valid days_of_week == days_of_week & (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) end ## End Validations ## # TODO Is this OperatingTime applicable at +time+ def valid_at(time=Time.now) raise NotImplementedError end # Tag Helpers %w{tag_list tags tag_counts tag_ids tag_tagging_ids tag_taggings}.each do |m| [m,m+"="].each do |m| if self.instance_methods.include?("operating_time_"+m) self.class_eval "alias #{m.to_sym} #{"operating_time_#{m}".to_sym}" end end ; end def tags_from ; operating_time_tags_from ; end def override read_attribute(:override) == 1 end def override=(mode) if mode == true or mode == "true" or mode == 1 write_attribute(:override, true) elsif mode == false or mode == "false" or mode == 0 write_attribute(:override, false) else raise ArgumentError, "Invalid override value (#{mode.inspect}); Accepts true/false, 1/0" end end def days_of_week=(newDow) if not ( newDow & ALL_DAYS == newDow ) # Invalid input raise ArgumentError, "Not a valid value for days_of_week (#{newDow.inspect})" end write_attribute(:days_of_week, newDow & ALL_DAYS) @days_of_weekHash = nil @days_of_weekArray = nil @days_of_weekString = nil end ## days_of_week Helpers ## # Hash mapping day of week (Symbol) to valid(true)/invalid(false) def days_of_week_hash @days_of_week_hash ||= { :sunday => (days_of_week & SUNDAY ) > 0, :monday => (days_of_week & MONDAY ) > 0, :tuesday => (days_of_week & TUESDAY ) > 0, :wednesday => (days_of_week & WEDNESDAY ) > 0, :thursday => (days_of_week & THURSDAY ) > 0, :friday => (days_of_week & FRIDAY ) > 0, :saturday => (days_of_week & SATURDAY ) > 0 } end # Array beginning with Sunday of valid(true)/inactive(false) values def days_of_week_array dow = days_of_week_hash @days_of_week_array ||= [ dow[:sunday], dow[:monday], dow[:tuesday], dow[:wednesday], dow[:thursday], dow[:friday], dow[:saturday] ] end # Human-readable string of applicable days of week def days_of_week_string dow = days_of_week_hash @days_of_week_string ||= (dow[:sunday] ? "Su" : "") + (dow[:monday] ? "M" : "") + (dow[:tuesday] ? "Tu" : "") + (dow[:wednesday] ? "W" : "") + (dow[:thursday] ? "Th" : "") + (dow[:friday] ? "F" : "") + (dow[:saturday] ? "Sa" : "") end ## End days_of_week Helpers ## # Returns the next full occurrence of these operating time rule. # If we are currently within a valid time range, it will look forward for the # <em>next</em> opening time def next_times(at = Time.now) at = at.midnight unless at.respond_to? :offset return nil if length == 0 return nil if at.to_date > endDate # Schedules end at 23:59 of the stored endDate at = startDate.midnight if at < startDate # This schedule hasn't started yet, skip to startDate # Next occurrence is later today # This is the only time the "time" actually matters; # after today, all we care about is the date if days_of_week_array[at.wday] and start >= at.offset open = at.midnight + start close = open + length return [open,close] end # We don't care about the time offset anymore, jump to the next midnight at = at.midnight + 1.day # NOTE This also has the added benefit of preventing an infinite loop # from occurring if +at+ gets shifted by 0.days further down. # Shift days_of_weekArray so that +at+ is first element dow = days_of_week_array[at.wday..-1] + days_of_week_array[0..(at.wday-1)] # NOTE The above call does something a little quirky: # In the event that at.wday = 0, it concatenates the array with itself. # Since we are only interested in the first true value, this does not # cause a problem, but could probably be cleaned up if done so carefully. # Next day of the week this schedule is valid for (relative to current day) shift = dow.index(true) if shift # Skip forward at = at + shift.days else # Give up, there are no more occurrences # TODO Test edge case: valid for 1 day/week return nil end # Recurse to rerun the validation routines return next_times(at) end alias :to_times :next_times def to_xml(options = {}) #super(params.merge({:only => [:id, :place_id], :methods => [ {:times => :next_times}, :start, :length, :startDate, :endDate ]})) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] options[:skip_instruct] = true xml.tag!(self.class.to_s.underscore.dasherize) do xml.id(self.id) xml.place_id(self.place_id) #xml.place_name(self.place.name) #xml.place_location(self.place.location) #xml.place_phone(self.place.phone) xml.details(self.details) xml.tags do |xml| self.tag_list.each do |tag| xml.tag(tag) end end xml.start(self.start) xml.length(self.length) self.days_of_week_hash.to_xml(options.merge(:root => :days_of_week)) xml.startDate(self.startDate) xml.endDate(self.endDate) xml.override(self.override) open,close = self.next_times(Date.today) if open.nil? or close.nil? xml.tag!(:next_times.to_s.dasherize, :for => Date.today) else xml.tag!(:next_times.to_s.dasherize, :for => Date.today) do |xml| xml.open(open.xmlschema) xml.close(close.xmlschema) end end end end ##### TODO DEPRECATED METHODS ##### # Returns a RelativeTime object representing this OperatingTime def relativeTime @relativeTime ||= RelativeTime.new(self, :opensAt, :length) end; protected :relativeTime # Backwards compatibility with old database schema # TODO GET RID OF THIS!!! def flags ( (override ? 1 : 0) << 7) | read_attribute(:days_of_week) end # FIXME Deprecated, use +override+ instead def special override end # Input: isSpecial = true/false # FIXME Deprecated, use +override=+ instead def special=(isSpecial) if isSpecial == true or isSpecial == "true" or isSpecial == 1 self.override = true elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 self.override = false end end end diff --git a/app/models/place.rb b/app/models/place.rb index c92fa85..74ac245 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,246 +1,249 @@ class Place < ActiveRecord::Base DEBUG = false has_many :operating_times has_one :dining_extension acts_as_taggable_on :tags validates_presence_of :name def special_operating_times - OperatingTime.find( :all, :conditions => {:place_id => id, :override => 1}) + OperatingTime.special.by_place(self).find(:all) end def regular_operating_times - OperatingTime.find( :all, :conditions => {:place_id => id, :override => 0}) + OperatingTime.regular.by_place(self).find(:all) end # Returns an array of Times representing the opening and closing times # of this Place between +startAt+ and +endAt+ def schedule(startAt,endAt) ## Caching ## @schedules ||= {} if @schedules[startAt.xmlschema] and @schedules[startAt.xmlschema][endAt.xmlschema] return @schedules[startAt.xmlschema][endAt.xmlschema] end ## End Caching ## # TODO Handle events starting within the range but ending outside of it? # TODO Offload this selection to the database; okay for testing though + # NOTE This is actually faster thanks to the query cache for small numbers of operating times, but not very scalable + #all_regular_operating_times = OperatingTime.find(:all, :conditions => {:place_id => self.id, :override => 0}).select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} + #all_special_operating_times = OperatingTime.find(:all, :conditions => {:place_id => self.id, :override => 1}).select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} # Select all relevant times (1 day buffer on each end) # NOTE Make sure to use generous date comparisons to allow for midnight rollovers - all_regular_operating_times = regular_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} - all_special_operating_times = special_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} + all_regular_operating_times = OperatingTime.regular.by_place_id(self.id).in_range(startAt..endAt).find(:all) + all_special_operating_times = OperatingTime.special.by_place_id(self.id).in_range(startAt..endAt).find(:all) puts "\nRegular OperatingTimes: #{all_regular_operating_times.inspect}" if DEBUG puts "\nSpecial OperatingTimes: #{all_special_operating_times.inspect}" if DEBUG regular_times = [] special_times = [] special_ranges = [] all_special_operating_times.each do |ot| puts "\nSpecial Scheduling for: #{ot.inspect}" if DEBUG # Special Case: Overriding with NO times (e.g. closed all day) if ot.start == 0 and ot.length == 0 and startAt.to_date <= ot.startDate # Block out the range, but don't add the "null Times" special_ranges << Range.new(ot.startDate,ot.endDate) next end # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt.midnight : startAt - 1.day puts "EarlyStart: #{earlyStart.inspect}" if DEBUG # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do if DEBUG puts "Open: #{open}" puts "Close: #{close}" puts "Start Date: #{ot.startDate} (#{ot.startDate.class})" puts "End Date: #{ot.endDate} (#{ot.endDate.class})" end if close < startAt # Skip forward to the first occurrance in our time range puts "Seeking: #{close} < #{startAt}" if DEBUG open,close = ot.next_times(close) next end special_times << [open,close] special_ranges << Range.new(ot.startDate,ot.endDate) open,close = ot.next_times(close) end end puts "\nSpecial Times: #{special_times.inspect}" if DEBUG puts "\nSpecial Ranges: #{special_ranges.inspect}" if DEBUG all_regular_operating_times.each do |ot| puts "\nRegular Scheduling for: #{ot.inspect}" if DEBUG # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day puts "EarlyStart: #{earlyStart.inspect}" if DEBUG # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) if DEBUG puts "" puts "Open: #{open}" puts "Close: #{close}" end if open.nil? # No valid occurrences in the future puts "Skipping: No valid occurrences in the future." if DEBUG next end while not open.nil? and open <= endAt do if DEBUG puts "" puts "Open: #{open}" puts "Close: #{close}" end if close < startAt # Skip forward to the first occurrance in our time range puts "Seeking: #{close} < #{startAt}" if DEBUG open,close = ot.next_times(close) next end overridden = false special_ranges.each do |sr| overridden ||= sr.member?(open.to_date) end if overridden puts "Overridden" if DEBUG open,close = ot.next_times(close) next end # FIXME Causing an infinite loop; would be nice if this worked #open = startAt if open < startAt #close = endAt if close > endAt regular_times << [open,close] open,close = ot.next_times(close) end end puts "\nRegular Times: #{regular_times.inspect}" if DEBUG # TODO Handle schedule overrides # TODO Handle combinations (i.e. part special, part regular) final_schedule = (regular_times+special_times).sort{|a,b|a[0] <=> b[0]} ## Caching ## @schedules ||= {} @schedules[startAt.xmlschema] ||= {} @schedules[startAt.xmlschema][endAt.xmlschema] = final_schedule ## End Caching ## final_schedule end def daySchedule(at = Date.today) at = at.to_date if at.class == Time or at.class == DateTime day_schedule = schedule(at.midnight,(at+1).midnight) #schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } #schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end =end day_schedule.sort{|a,b|a[0] <=> b[0]} end def currentSchedule(at = Time.now) puts "At(cS): #{at}" if DEBUG daySchedule(at).select { |open,close| puts "Open(cS): #{open}" if DEBUG puts "Close(cS): #{close}" if DEBUG open <= at and at <= close }[0] end def open?(at = Time.now) a = currentSchedule(at) return a ? true : false end alias :open :open? def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end def to_xml(options = {}) #super(options.merge({:only => [:id, :name, :location, :phone], :methods => [ :open, :daySchedule ] })) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] options[:skip_instruct] = true xml.place do xml.id(self.id) xml.name(self.name) xml.location(self.location) xml.building_id(self.building_id) xml.phone(self.phone) xml.tags do |xml| self.tag_list.each do |tag| xml.tag(tag) end end self.dining_extension.to_xml(options.merge({:no_id => true})) unless self.dining_extension.nil? xml.open(self.open?) if options[:schedule_from] and options[:schedule_to] sched = schedule(options[:schedule_from],options[:schedule_to]) sched_opts = {:from => options[:schedule_from].xmlschema, :to => options[:schedule_to].xmlschema } elsif options[:schedule_for_date] sched = daySchedule(options[:schedule_for_date]) sched_opts = {:on => options[:schedule_for_date].xmlschema} else sched = daySchedule(Date.today) sched_opts = {:on => Date.today} end if sched.nil? or sched.empty? xml.schedule(sched_opts) else xml.schedule(sched_opts) do |xml| sched.each do |open,close| xml.open(open.xmlschema) xml.close(close.xmlschema) end end end end end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index f168177..3302c9a 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,172 +1,161 @@ # This file is copied to ~/spec when you run 'ruby script/generate rspec' # from the project root directory. ENV["RAILS_ENV"] ||= 'test' require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT) require 'spec/autorun' require 'spec/rails' require 'spec/capabilities' Spec::Runner.configure do |config| # If you're not using ActiveRecord you should remove these # lines, delete config/database.yml and disable :active_record # in your config/boot.rb config.use_transactional_fixtures = true config.use_instantiated_fixtures = false config.fixture_path = RAILS_ROOT + '/spec/fixtures/' # == Fixtures # # You can declare fixtures for each example_group like this: # describe "...." do # fixtures :table_a, :table_b # # Alternatively, if you prefer to declare them only once, you can # do so right here. Just uncomment the next line and replace the fixture # names with your fixtures. # # config.global_fixtures = :table_a, :table_b # # If you declare global fixtures, be aware that they will be declared # for all of your examples, even those that don't use them. # # You can also declare which fixtures to use (for example fixtures for test/fixtures): # # config.fixture_path = RAILS_ROOT + '/spec/fixtures/' # # == Mock Framework # # RSpec uses it's own mocking framework by default. If you prefer to # use mocha, flexmock or RR, uncomment the appropriate line: # # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr # # == Notes # # For more information take a look at Spec::Runner::Configuration and Spec::Runner end ConstraintDebugging = false def add_scheduling_spec_helpers(place) place.instance_eval do def operating_times regular_operating_times + special_operating_times end - def regular_operating_times - @regular_operating_times ||= [] - end - def special_operating_times - @special_operating_times ||= [] - end def constraints @constraints ||= [] end def times @times ||= [] end def add_constraint(&block) puts "Adding constraint: #{block.to_s.sub(/^[^\@]*\@/,'')[0..-2]}" if ConstraintDebugging self.constraints << block end # Test +time+ against all constraints for +place+ def acceptable_time(time) if ConstraintDebugging puts "Testing Time: #{time.inspect}" end matched_all = true self.constraints.each do |c| matched = c.call(time) if ConstraintDebugging if matched puts "++ Time accepted by constraint" else puts "-- Time rejected by constraint" end puts " Constraint: #{c.to_s.sub(/^[^\@]*\@/,'')[0..-2]}" end matched_all &= matched end if ConstraintDebugging if matched_all puts "++ Time Accepted" else puts "-- Time Rejected" end puts "" end matched_all end def add_times(new_times = []) new_times.each do |t| unless t[:start] and t[:length] raise ArgumentError, "Must specify a valid start offset and length" end end times.concat(new_times) end def build(at = Time.now) if ConstraintDebugging puts "Rebuilding #{self}" puts "Constraints:" constraints.each do |c| puts " #{c.to_s.sub(/^[^\@]*\@/,'')[0..-2]}" end puts "Times:" times.each do |t| puts " #{t.inspect}" end end - regular_operating_times.clear - special_operating_times.clear - operating_times.clear + OperatingTime.by_place(self).destroy_all + @schedule = nil self.times.each do |t| t=t.dup if acceptable_time(t) t[:override] ||= false t[:startDate] ||= at.to_date - 2 t[:endDate] ||= at.to_date + 2 t[:days_of_week] ||= OperatingTime::ALL_DAYS t[:place_id] ||= self.id ot = OperatingTime.new t.each{|k,v| ot.send(k.to_s+'=',v)} + ot.save! puts "Added time: #{ot.inspect}" if ConstraintDebugging - if t[:override] - self.special_operating_times << ot - else - self.regular_operating_times << ot - end end end if ConstraintDebugging puts "Regular Times: #{self.regular_operating_times.inspect}" puts "Special Times: #{self.special_operating_times.inspect}" end self end alias :build! :build alias :rebuild :build alias :rebuild! :build end end # add_scheduling_spec_helpers(place)
michaelansel/dukenow
273262199cdb27944a4f04d9f735be7d1ae92d9a
Upgrade to Rails 2.3.2
diff --git a/app/controllers/application.rb b/app/controllers/application_controller.rb similarity index 100% rename from app/controllers/application.rb rename to app/controllers/application_controller.rb diff --git a/config/boot.rb b/config/boot.rb index 0a51688..0ad0f78 100644 --- a/config/boot.rb +++ b/config/boot.rb @@ -1,109 +1,110 @@ # Don't change this file! # Configure your app in config/environment.rb and config/environments/*.rb RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT) module Rails class << self def boot! unless booted? preinitialize pick_boot.run end end def booted? defined? Rails::Initializer end def pick_boot (vendor_rails? ? VendorBoot : GemBoot).new end def vendor_rails? File.exist?("#{RAILS_ROOT}/vendor/rails") end def preinitialize load(preinitializer_path) if File.exist?(preinitializer_path) end def preinitializer_path "#{RAILS_ROOT}/config/preinitializer.rb" end end class Boot def run load_initializer Rails::Initializer.run(:set_load_path) end end class VendorBoot < Boot def load_initializer require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer" Rails::Initializer.run(:install_gem_spec_stubs) + Rails::GemDependency.add_frozen_gem_path end end class GemBoot < Boot def load_initializer self.class.load_rubygems load_rails_gem require 'initializer' end def load_rails_gem if version = self.class.gem_version gem 'rails', version else gem 'rails' end rescue Gem::LoadError => load_error $stderr.puts %(Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.) exit 1 end class << self def rubygems_version Gem::RubyGemsVersion rescue nil end def gem_version if defined? RAILS_GEM_VERSION RAILS_GEM_VERSION elsif ENV.include?('RAILS_GEM_VERSION') ENV['RAILS_GEM_VERSION'] else parse_gem_version(read_environment_rb) end end def load_rubygems require 'rubygems' min_version = '1.3.1' unless rubygems_version >= min_version $stderr.puts %Q(Rails requires RubyGems >= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.) exit 1 end rescue LoadError $stderr.puts %Q(Rails requires RubyGems >= #{min_version}. Please install RubyGems and try again: http://rubygems.rubyforge.org) exit 1 end def parse_gem_version(text) $1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*["']([!~<>=]*\s*[\d.]+)["']/ end private def read_environment_rb File.read("#{RAILS_ROOT}/config/environment.rb") end end end end # All that for this: Rails.boot! diff --git a/config/environment.rb b/config/environment.rb index d5d6455..8d769f6 100644 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,81 +1,81 @@ # Be sure to restart your server when you modify this file # Uncomment below to force Rails into production mode when # you don't control web/app server and can't set it the proper way # ENV['RAILS_ENV'] ||= 'production' # Specifies gem version of Rails to use when vendor/rails is not present -RAILS_GEM_VERSION = '2.2.2' unless defined? RAILS_GEM_VERSION +RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # Version number for REST API APPLICATION_API_VERSION = 1 # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # See Rails::Configuration for more options. # Skip frameworks you're not going to use. To use Rails without a database # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Specify gems that this application depends on. # They can then be installed with "rake gems:install" on new installations. # You have to specify the :lib option for libraries, where the Gem name (sqlite3-ruby) differs from the file itself (sqlite3) # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" config.gem "mbleigh-acts-as-taggable-on", :source => "http://gems.github.com", :lib => "acts-as-taggable-on" # Only load the plugins named here, in the order given. By default, all plugins # in vendor/plugins are loaded in alphabetical order. # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) require 'date_time' # Force all environments to use the same logger level # (by default production uses :info, the others :debug) # config.log_level = :debug # Make Time.zone default to the specified zone, and make Active Record store time values # in the database in UTC, and return them converted to the specified local zone. # Run "rake -D time" for a list of tasks for finding time zone names. Comment line to use default local time. #config.time_zone = 'UTC' # The internationalization framework can be changed to have another default locale (standard is :en) or more load paths. # All files from config/locales/*.rb,yml are added automatically. # config.i18n.load_path << Dir[File.join(RAILS_ROOT, 'my', 'locales', '*.{rb,yml}')] # config.i18n.default_locale = :de # Your secret key for verifying cookie session data integrity. # If you change this key, all old sessions will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. config.action_controller.session = { :session_key => '_DukeNow_session', :secret => '8e8355b37da6a989cc5989da3b5bcb79f4b30d3e4b02ecf47ba68d716292194eb939ea71e068c13f3676158f16dd74577017f3838505ef7ed8043f3a65e87741' } # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rake db:sessions:create") # config.action_controller.session_store = :active_record_store # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Activate observers that should always be running # Please note that observers generated using script/generate observer need to have an _observer suffix # config.active_record.observers = :cacher, :garbage_collector, :forum_observer end
michaelansel/dukenow
102c9dfaa647014194fa86be929382b625a1de85
Minimal fixes for OperatingTimes views
diff --git a/app/views/operating_times/_entryform.html.erb b/app/views/operating_times/_entryform.html.erb index 2f06e22..e352275 100644 --- a/app/views/operating_times/_entryform.html.erb +++ b/app/views/operating_times/_entryform.html.erb @@ -1,74 +1,74 @@ <p> <%= f.label :place %><br /> <%= f.collection_select :place_id, @places, :id, :name %> </p> <p> <%= f.label :details %><br /> <%= f.text_field :details %><br /> </p> <p> - <%= f.label :opensAt %><br /> - <%= select_time f.object.opensAt, :prefix => "#{f.object_name}[opensAt]" %> + <%= f.label :start %><br /> + <%= f.text_field :start %><br /> </p> <p> - <%= f.label :closesAt %><br /> - <%= select_time f.object.closesAt, :prefix => "#{f.object_name}[closesAt]" %> + <%= f.label :length %><br /> + <%= f.text_field :length %><br /> </p> <p> <%= f.label :daysOfWeek %><br /> <table style="height:+3em;"><tr> <% Date::DAYNAMES.each_index do |i| %> <td onclick="toggleCheckbox('daysOfWeek_<%=h Date::DAYNAMES[i].to_s.capitalize %>')"> - <label id="daysOfWeek_<%=h Date::DAYNAMES[i].to_s.capitalize%>" style="font-weight:<%= f.object.daysOfWeekArray[i] ? "bold" : "normal" %>;font-size:<%= f.object.daysOfWeekArray[i] ? "+2em" : "+1em" %>;"> + <label id="daysOfWeek_<%=h Date::DAYNAMES[i].to_s.capitalize%>" style="font-weight:<%= f.object.days_of_week_array[i] ? "bold" : "normal" %>;font-size:<%= f.object.days_of_week_array[i] ? "+2em" : "+1em" %>;"> <%=h Date::DAYNAMES[i].to_s.capitalize %> <%= check_box_tag "#{f.object_name}[daysOfWeekHash][]", - Date::DAYNAMES[i].downcase.to_sym, f.object.daysOfWeekArray[i], :style => 'display:none;' %> + Date::DAYNAMES[i].downcase.to_sym, f.object.days_of_week_array[i], :style => 'display:none;' %> </label> </span> <% end %> </tr></table> </p> <script> function toggleCheckbox(element_id) { a=document.getElementById(element_id); b=document.getElementById(element_id).getElementsByTagName('input')[0]; if(b.checked) { a.style['fontWeight']='bold'; a.style['fontSize']='+2em'; } else { a.style['fontWeight']='normal'; a.style['fontSize']='+1em'; } } function updateSpecialForm() { if(document.getElementById("operating_time_special").checked) { <%= visual_effect(:appear, "specialForm", :duration => 0) %> } else { <%= visual_effect(:fade, "specialForm", :duration => 0) %> } } </script> <p> <label>Special? <%= f.check_box :special, {:onchange => 'updateSpecialForm()'}, "true", "false" %> </label> </p> <span id="specialForm" style="display:<%= f.object.special ? "" : "none" %>;"> <p> <%= f.label :start %><br /> <%= f.date_select :startDate %> </p> <p> <%= f.label :end %><br /> <%= f.date_select :endDate %> </p> </span> diff --git a/app/views/operating_times/index.html.erb b/app/views/operating_times/index.html.erb index f4d6d01..79bf9d3 100644 --- a/app/views/operating_times/index.html.erb +++ b/app/views/operating_times/index.html.erb @@ -1,34 +1,34 @@ <h2>Listing operating_times</h2> <table> <tr> <th>Place</th> <th>Start</th> <th>Length</th> <th>Details</th> <th>Days Of Week</th> - <th>Flags</th> + <th>Override?</th> <th>Start Date</th> <th>End Date</th> </tr> <% for operating_time in @operating_times %> <tr> <td><%=h operating_time.place.name %></td> <td><%=h operating_time.start %></td> <td><%=h operating_time.length %></td> <td><%=h operating_time.details %></td> - <td><%=h operating_time.daysOfWeekString %></td> - <td><%=h operating_time.flags %></td> + <td><%=h operating_time.days_of_week_string %></td> + <td><%=h operating_time.override %></td> <td><%=h operating_time.startDate %></td> <td><%=h operating_time.endDate %></td> <td><%= link_to 'Show', operating_time %></td> <td><%= link_to 'Edit', edit_operating_time_path(operating_time) %></td> <td><%= link_to 'Destroy', operating_time, :confirm => 'Are you sure?', :method => :delete %></td> </tr> <% end %> </table> <br /> <%= link_to 'New operating_time', new_operating_time_path %> diff --git a/app/views/operating_times/show.html.erb b/app/views/operating_times/show.html.erb index cd5c686..2cf1242 100644 --- a/app/views/operating_times/show.html.erb +++ b/app/views/operating_times/show.html.erb @@ -1,48 +1,48 @@ <p> <b>Place:</b> <%= link_to @operating_time.place.name, @operating_time.place %> </p> <p> <b>Details:</b> <%=h @operating_time.details %> </p> <p> <b>Start:</b> <%=h @operating_time.start %> </p> <p> <b>Length:</b> <%=h @operating_time.length %> </p> <p> <b>Details:</b> <%=h @operating_time.details %> </p> <p> <b>Days of Week:</b> - <%=h @operating_time.daysOfWeekString %> + <%=h @operating_time.days_of_week_string %> </p> <p> - <b>Flags:</b> - <%=h @operating_time.flags %> + <b>Override?</b> + <%=h @operating_time.override %> </p> <p> <b>Startdate:</b> <%=h @operating_time.startDate %> </p> <p> <b>Enddate:</b> <%=h @operating_time.endDate %> </p> <%= link_to 'Edit', edit_operating_time_path(@operating_time) %> | <%= link_to 'Back', operating_times_path %>
michaelansel/dukenow
0451aa18baf59f1a8907defc22d73be8170fb836
Convert from/to Time objects to XML schema instead of String
diff --git a/app/models/place.rb b/app/models/place.rb index 08dc86a..c92fa85 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,246 +1,246 @@ class Place < ActiveRecord::Base DEBUG = false has_many :operating_times has_one :dining_extension acts_as_taggable_on :tags validates_presence_of :name def special_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 1}) end def regular_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 0}) end # Returns an array of Times representing the opening and closing times # of this Place between +startAt+ and +endAt+ def schedule(startAt,endAt) ## Caching ## @schedules ||= {} if @schedules[startAt.xmlschema] and @schedules[startAt.xmlschema][endAt.xmlschema] return @schedules[startAt.xmlschema][endAt.xmlschema] end ## End Caching ## # TODO Handle events starting within the range but ending outside of it? # TODO Offload this selection to the database; okay for testing though # Select all relevant times (1 day buffer on each end) # NOTE Make sure to use generous date comparisons to allow for midnight rollovers all_regular_operating_times = regular_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} all_special_operating_times = special_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} puts "\nRegular OperatingTimes: #{all_regular_operating_times.inspect}" if DEBUG puts "\nSpecial OperatingTimes: #{all_special_operating_times.inspect}" if DEBUG regular_times = [] special_times = [] special_ranges = [] all_special_operating_times.each do |ot| puts "\nSpecial Scheduling for: #{ot.inspect}" if DEBUG # Special Case: Overriding with NO times (e.g. closed all day) if ot.start == 0 and ot.length == 0 and startAt.to_date <= ot.startDate # Block out the range, but don't add the "null Times" special_ranges << Range.new(ot.startDate,ot.endDate) next end # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt.midnight : startAt - 1.day puts "EarlyStart: #{earlyStart.inspect}" if DEBUG # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do if DEBUG puts "Open: #{open}" puts "Close: #{close}" puts "Start Date: #{ot.startDate} (#{ot.startDate.class})" puts "End Date: #{ot.endDate} (#{ot.endDate.class})" end if close < startAt # Skip forward to the first occurrance in our time range puts "Seeking: #{close} < #{startAt}" if DEBUG open,close = ot.next_times(close) next end special_times << [open,close] special_ranges << Range.new(ot.startDate,ot.endDate) open,close = ot.next_times(close) end end puts "\nSpecial Times: #{special_times.inspect}" if DEBUG puts "\nSpecial Ranges: #{special_ranges.inspect}" if DEBUG all_regular_operating_times.each do |ot| puts "\nRegular Scheduling for: #{ot.inspect}" if DEBUG # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day puts "EarlyStart: #{earlyStart.inspect}" if DEBUG # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) if DEBUG puts "" puts "Open: #{open}" puts "Close: #{close}" end if open.nil? # No valid occurrences in the future puts "Skipping: No valid occurrences in the future." if DEBUG next end while not open.nil? and open <= endAt do if DEBUG puts "" puts "Open: #{open}" puts "Close: #{close}" end if close < startAt # Skip forward to the first occurrance in our time range puts "Seeking: #{close} < #{startAt}" if DEBUG open,close = ot.next_times(close) next end overridden = false special_ranges.each do |sr| overridden ||= sr.member?(open.to_date) end if overridden puts "Overridden" if DEBUG open,close = ot.next_times(close) next end # FIXME Causing an infinite loop; would be nice if this worked #open = startAt if open < startAt #close = endAt if close > endAt regular_times << [open,close] open,close = ot.next_times(close) end end puts "\nRegular Times: #{regular_times.inspect}" if DEBUG # TODO Handle schedule overrides # TODO Handle combinations (i.e. part special, part regular) final_schedule = (regular_times+special_times).sort{|a,b|a[0] <=> b[0]} ## Caching ## @schedules ||= {} @schedules[startAt.xmlschema] ||= {} @schedules[startAt.xmlschema][endAt.xmlschema] = final_schedule ## End Caching ## final_schedule end def daySchedule(at = Date.today) at = at.to_date if at.class == Time or at.class == DateTime day_schedule = schedule(at.midnight,(at+1).midnight) #schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } #schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end =end day_schedule.sort{|a,b|a[0] <=> b[0]} end def currentSchedule(at = Time.now) puts "At(cS): #{at}" if DEBUG daySchedule(at).select { |open,close| puts "Open(cS): #{open}" if DEBUG puts "Close(cS): #{close}" if DEBUG open <= at and at <= close }[0] end def open?(at = Time.now) a = currentSchedule(at) return a ? true : false end alias :open :open? def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end def to_xml(options = {}) #super(options.merge({:only => [:id, :name, :location, :phone], :methods => [ :open, :daySchedule ] })) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] options[:skip_instruct] = true xml.place do xml.id(self.id) xml.name(self.name) xml.location(self.location) xml.building_id(self.building_id) xml.phone(self.phone) xml.tags do |xml| self.tag_list.each do |tag| xml.tag(tag) end end self.dining_extension.to_xml(options.merge({:no_id => true})) unless self.dining_extension.nil? xml.open(self.open?) if options[:schedule_from] and options[:schedule_to] sched = schedule(options[:schedule_from],options[:schedule_to]) - sched_opts = {:from => options[:schedule_from], - :to => options[:schedule_to] } + sched_opts = {:from => options[:schedule_from].xmlschema, + :to => options[:schedule_to].xmlschema } elsif options[:schedule_for_date] sched = daySchedule(options[:schedule_for_date]) - sched_opts = {:on => options[:schedule_for_date]} + sched_opts = {:on => options[:schedule_for_date].xmlschema} else sched = daySchedule(Date.today) sched_opts = {:on => Date.today} end if sched.nil? or sched.empty? xml.schedule(sched_opts) else xml.schedule(sched_opts) do |xml| sched.each do |open,close| xml.open(open.xmlschema) xml.close(close.xmlschema) end end end end end end
michaelansel/dukenow
7aa3100cec46caf939f6274188695c91b6878588
Minor bugfixes
diff --git a/app/controllers/places_controller.rb b/app/controllers/places_controller.rb index af9cf31..1930e53 100644 --- a/app/controllers/places_controller.rb +++ b/app/controllers/places_controller.rb @@ -1,192 +1,191 @@ class PlacesController < ApplicationController ActionView::Base.send :include, TagsHelper before_filter :map_params, :parse_dates_and_times, :filter_xml_params, :get_at_date def get_at_date - params[:schedule_for_date] = Date.today.to_s if params[:schedule_for_date].nil? - @at = Date.parse(params[:schedule_for_date]) + @at = params[:schedule_for_date] || Date.today end def map_params map = {:from => :schedule_from, :to => :schedule_to, :on => :schedule_for_date, :at => :schedule_for_date} params.each{|k,v| params[map[k.to_sym]] = v if map.has_key?(k.to_sym) } end def parse_dates_and_times times = [:schedule_from, :schedule_to, :schedule_for_date] params[:schedule_from] = Time.parse(params[:schedule_from]) if params[:schedule_from] params[:schedule_to] = Time.parse(params[:schedule_to]) if params[:schedule_to] params[:schedule_for_date] = Date.parse(params[:schedule_for_date]) if params[:schedule_for_date] end def filter_xml_params safe = [:schedule_from, :schedule_to, :schedule_for_date] @xml_params ||= {} params.each{|k,v| @xml_params[k.to_sym] = v if safe.include?(k.to_sym) } RAILS_DEFAULT_LOGGER.info "XML Params: #{@xml_params.inspect}" end # GET /places # GET /places.xml def index @places = Place.find(:all, :order => "name ASC") if params[:tags] @selected_tags = params[:tags].split(/[,+ ][ ]*/) else @selected_tags = [] end # Restrict to specific tags @selected_tags.each do |tag| RAILS_DEFAULT_LOGGER.debug "Restricting by tag: #{tag}" @places = @places & Place.tagged_with(tag, :on => :tags) end # Don't display machineAdded Places on the main listing @places = @places - Place.tagged_with("machineAdded", :on => :tags) unless @selected_tags.include?("machineAdded") # Calculate tag count for all Places with Tags #@tags = Place.tag_counts_on(:tags, :at_least => 1) # Manually calculate tag counts for only displayed places tags = [] @places.each do |place| tags = tags + place.tag_list end # Remove already selected tags tags = tags - @selected_tags # Count tags and make a set of [name,count] pairs @tag_counts = tags.uniq.collect {|tag| [tag,tags.select{|a|a == tag}.size] } # Filter out single tags @tag_counts = @tag_counts.select{|name,count| count > 1} # Make the count arrays act like tags for the tag cloud @tag_counts.each do |a| a.instance_eval <<-RUBY def count self[1] end def name self[0] end RUBY end respond_to do |format| format.html # index.html.erb format.iphone # index.iphone.erb format.json { render :json => @places } format.xml { render :xml => @places.to_xml(@xml_params) } end end def tag redirect_to :action => :index, :tags => params.delete(:id) end # GET /places/1 # GET /places/1.xml def show @place = Place.find(params[:id]) request.format = :html if request.format == :iphone respond_to do |format| format.html # show.html.erb format.xml { render :xml => @place.to_xml(@xml_params) } end end # GET /places/new # GET /places/new.xml def new @place = Place.new request.format = :html if request.format == :iphone respond_to do |format| format.html # new.html.erb format.xml { render :xml => @place } end end # GET /places/1/edit def edit @place = Place.find(params[:id]) request.format = :html if request.format == :iphone end # POST /places # POST /places.xml def create if params[:place] and params[:place][:tag_list] params[:place][:tag_list].strip! params[:place][:tag_list].gsub!(/( )+/,', ') end @place = Place.new(params[:place]) request.format = :html if request.format == :iphone respond_to do |format| if @place.save flash[:notice] = 'Place was successfully created.' format.html { redirect_to(@place) } format.xml { render :xml => @place, :status => :created, :location => @place } else format.html { render :action => "new" } format.xml { render :xml => @place.errors, :status => :unprocessable_entity } end end end # PUT /places/1 # PUT /places/1.xml def update @place = Place.find(params[:id]) if params[:place] and params[:place][:tag_list] params[:place][:tag_list].strip! params[:place][:tag_list].gsub!(/( )+/,', ') end request.format = :html if request.format == :iphone respond_to do |format| if @place.update_attributes(params[:place]) flash[:notice] = 'Place was successfully updated.' format.html { redirect_to(@place) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @place.errors, :status => :unprocessable_entity } end end end # DELETE /places/1 # DELETE /places/1.xml def destroy @place = Place.find(params[:id]) @place.destroy request.format = :html if request.format == :iphone respond_to do |format| format.html { redirect_to(places_url) } format.xml { head :ok } end end # GET /places/open # GET /places/open.xml def open @place = Place.find(params[:id]) request.format = :html if request.format == :iphone respond_to do |format| format.html # open.html.erb format.xml { render :xml => @place } end end end diff --git a/config/routes.rb b/config/routes.rb index ac3e961..aadebf1 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,58 +1,58 @@ ActionController::Routing::Routes.draw do |map| map.with_options( :name_prefix => "api_v#{APPLICATION_API_VERSION}_", :path_prefix => "/api/v#{APPLICATION_API_VERSION}") do |api| api.resources :places, :has_many => :operating_times api.resources :dining_extensions api.resources :operating_times - api.root :controller => "places" + api.root :controller => "places", :format => :xml end map.resources :places, :has_many => :operating_times map.resources :dining_extensions map.resources :operating_times map.root :controller => "places" # The priority is based upon order of creation: first created -> highest priority. # Sample of regular route: # map.connect 'products/:id', :controller => 'catalog', :action => 'view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase' # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # map.resources :products # Sample resource route with options: # map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get } # Sample resource route with sub-resources: # map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller # Sample resource route with more complex sub-resources # map.resources :products do |products| # products.resources :comments # products.resources :sales, :collection => { :recent => :get } # end # Sample resource route within a namespace: # map.namespace :admin do |admin| # # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb) # admin.resources :products # end # You can have the root of your site routed with map.root -- just remember to delete public/index.html. # map.root :controller => "welcome" # See how all your routes lay out with "rake routes" # Install the default routes as the lowest priority. # Note: These default routes make all actions in every controller accessible via GET requests. You should # consider removing the them or commenting them out if you're using named routes and resources. #map.connect ':controller/:action/:id' #map.connect ':controller/:action/:id.:format' end
michaelansel/dukenow
bc0397e4d24605c304eaf017fd4ab3c50ed8bd99
Add basic API versioning
diff --git a/config/environment.rb b/config/environment.rb index 15305cd..d5d6455 100644 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,78 +1,81 @@ # Be sure to restart your server when you modify this file # Uncomment below to force Rails into production mode when # you don't control web/app server and can't set it the proper way # ENV['RAILS_ENV'] ||= 'production' # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.2.2' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| + # Version number for REST API + APPLICATION_API_VERSION = 1 + # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # See Rails::Configuration for more options. # Skip frameworks you're not going to use. To use Rails without a database # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Specify gems that this application depends on. # They can then be installed with "rake gems:install" on new installations. # You have to specify the :lib option for libraries, where the Gem name (sqlite3-ruby) differs from the file itself (sqlite3) # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" config.gem "mbleigh-acts-as-taggable-on", :source => "http://gems.github.com", :lib => "acts-as-taggable-on" # Only load the plugins named here, in the order given. By default, all plugins # in vendor/plugins are loaded in alphabetical order. # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) require 'date_time' # Force all environments to use the same logger level # (by default production uses :info, the others :debug) # config.log_level = :debug # Make Time.zone default to the specified zone, and make Active Record store time values # in the database in UTC, and return them converted to the specified local zone. # Run "rake -D time" for a list of tasks for finding time zone names. Comment line to use default local time. #config.time_zone = 'UTC' # The internationalization framework can be changed to have another default locale (standard is :en) or more load paths. # All files from config/locales/*.rb,yml are added automatically. # config.i18n.load_path << Dir[File.join(RAILS_ROOT, 'my', 'locales', '*.{rb,yml}')] # config.i18n.default_locale = :de # Your secret key for verifying cookie session data integrity. # If you change this key, all old sessions will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. config.action_controller.session = { :session_key => '_DukeNow_session', :secret => '8e8355b37da6a989cc5989da3b5bcb79f4b30d3e4b02ecf47ba68d716292194eb939ea71e068c13f3676158f16dd74577017f3838505ef7ed8043f3a65e87741' } # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rake db:sessions:create") # config.action_controller.session_store = :active_record_store # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Activate observers that should always be running # Please note that observers generated using script/generate observer need to have an _observer suffix # config.active_record.observers = :cacher, :garbage_collector, :forum_observer end diff --git a/config/routes.rb b/config/routes.rb index cb864f0..ac3e961 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,51 +1,58 @@ ActionController::Routing::Routes.draw do |map| - map.resources :dining_extensions - map.resources :places + map.with_options( :name_prefix => "api_v#{APPLICATION_API_VERSION}_", + :path_prefix => "/api/v#{APPLICATION_API_VERSION}") do |api| + api.resources :places, :has_many => :operating_times + api.resources :dining_extensions + api.resources :operating_times + api.root :controller => "places" + end + + map.resources :places, :has_many => :operating_times + map.resources :dining_extensions map.resources :operating_times - map.connect 'operating_times/place/:place_id', :controller => 'operating_times', :action => 'index' map.root :controller => "places" # The priority is based upon order of creation: first created -> highest priority. # Sample of regular route: # map.connect 'products/:id', :controller => 'catalog', :action => 'view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase' # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # map.resources :products # Sample resource route with options: # map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get } # Sample resource route with sub-resources: # map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller # Sample resource route with more complex sub-resources # map.resources :products do |products| # products.resources :comments # products.resources :sales, :collection => { :recent => :get } # end # Sample resource route within a namespace: # map.namespace :admin do |admin| # # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb) # admin.resources :products # end # You can have the root of your site routed with map.root -- just remember to delete public/index.html. # map.root :controller => "welcome" # See how all your routes lay out with "rake routes" # Install the default routes as the lowest priority. # Note: These default routes make all actions in every controller accessible via GET requests. You should # consider removing the them or commenting them out if you're using named routes and resources. - map.connect ':controller/:action/:id' - map.connect ':controller/:action/:id.:format' + #map.connect ':controller/:action/:id' + #map.connect ':controller/:action/:id.:format' end
michaelansel/dukenow
26bc92525de10da460ff187af16ce2fec8900ef0
Minimal required changes to get Place views working again
diff --git a/app/controllers/places_controller.rb b/app/controllers/places_controller.rb index ebd4ae6..af9cf31 100644 --- a/app/controllers/places_controller.rb +++ b/app/controllers/places_controller.rb @@ -1,192 +1,192 @@ class PlacesController < ApplicationController ActionView::Base.send :include, TagsHelper - before_filter :map_params, :parse_dates_and_times, :filter_xml_params + before_filter :map_params, :parse_dates_and_times, :filter_xml_params, :get_at_date def get_at_date - params[:at] = Date.today.to_s if params[:at].nil? - @at = Date.parse(params[:at]) + params[:schedule_for_date] = Date.today.to_s if params[:schedule_for_date].nil? + @at = Date.parse(params[:schedule_for_date]) end def map_params map = {:from => :schedule_from, :to => :schedule_to, :on => :schedule_for_date, :at => :schedule_for_date} params.each{|k,v| params[map[k.to_sym]] = v if map.has_key?(k.to_sym) } end def parse_dates_and_times times = [:schedule_from, :schedule_to, :schedule_for_date] params[:schedule_from] = Time.parse(params[:schedule_from]) if params[:schedule_from] params[:schedule_to] = Time.parse(params[:schedule_to]) if params[:schedule_to] params[:schedule_for_date] = Date.parse(params[:schedule_for_date]) if params[:schedule_for_date] end def filter_xml_params safe = [:schedule_from, :schedule_to, :schedule_for_date] @xml_params ||= {} params.each{|k,v| @xml_params[k.to_sym] = v if safe.include?(k.to_sym) } RAILS_DEFAULT_LOGGER.info "XML Params: #{@xml_params.inspect}" end # GET /places # GET /places.xml def index @places = Place.find(:all, :order => "name ASC") if params[:tags] @selected_tags = params[:tags].split(/[,+ ][ ]*/) else @selected_tags = [] end # Restrict to specific tags @selected_tags.each do |tag| RAILS_DEFAULT_LOGGER.debug "Restricting by tag: #{tag}" @places = @places & Place.tagged_with(tag, :on => :tags) end # Don't display machineAdded Places on the main listing @places = @places - Place.tagged_with("machineAdded", :on => :tags) unless @selected_tags.include?("machineAdded") # Calculate tag count for all Places with Tags #@tags = Place.tag_counts_on(:tags, :at_least => 1) # Manually calculate tag counts for only displayed places tags = [] @places.each do |place| tags = tags + place.tag_list end # Remove already selected tags tags = tags - @selected_tags # Count tags and make a set of [name,count] pairs @tag_counts = tags.uniq.collect {|tag| [tag,tags.select{|a|a == tag}.size] } # Filter out single tags @tag_counts = @tag_counts.select{|name,count| count > 1} # Make the count arrays act like tags for the tag cloud @tag_counts.each do |a| a.instance_eval <<-RUBY def count self[1] end def name self[0] end RUBY end respond_to do |format| format.html # index.html.erb format.iphone # index.iphone.erb format.json { render :json => @places } format.xml { render :xml => @places.to_xml(@xml_params) } end end def tag redirect_to :action => :index, :tags => params.delete(:id) end # GET /places/1 # GET /places/1.xml def show @place = Place.find(params[:id]) request.format = :html if request.format == :iphone respond_to do |format| format.html # show.html.erb format.xml { render :xml => @place.to_xml(@xml_params) } end end # GET /places/new # GET /places/new.xml def new @place = Place.new request.format = :html if request.format == :iphone respond_to do |format| format.html # new.html.erb format.xml { render :xml => @place } end end # GET /places/1/edit def edit @place = Place.find(params[:id]) request.format = :html if request.format == :iphone end # POST /places # POST /places.xml def create if params[:place] and params[:place][:tag_list] params[:place][:tag_list].strip! params[:place][:tag_list].gsub!(/( )+/,', ') end @place = Place.new(params[:place]) request.format = :html if request.format == :iphone respond_to do |format| if @place.save flash[:notice] = 'Place was successfully created.' format.html { redirect_to(@place) } format.xml { render :xml => @place, :status => :created, :location => @place } else format.html { render :action => "new" } format.xml { render :xml => @place.errors, :status => :unprocessable_entity } end end end # PUT /places/1 # PUT /places/1.xml def update @place = Place.find(params[:id]) if params[:place] and params[:place][:tag_list] params[:place][:tag_list].strip! params[:place][:tag_list].gsub!(/( )+/,', ') end request.format = :html if request.format == :iphone respond_to do |format| if @place.update_attributes(params[:place]) flash[:notice] = 'Place was successfully updated.' format.html { redirect_to(@place) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @place.errors, :status => :unprocessable_entity } end end end # DELETE /places/1 # DELETE /places/1.xml def destroy @place = Place.find(params[:id]) @place.destroy request.format = :html if request.format == :iphone respond_to do |format| format.html { redirect_to(places_url) } format.xml { head :ok } end end # GET /places/open # GET /places/open.xml def open @place = Place.find(params[:id]) request.format = :html if request.format == :iphone respond_to do |format| format.html # open.html.erb format.xml { render :xml => @place } end end end diff --git a/app/helpers/places_helper.rb b/app/helpers/places_helper.rb index cf09357..f75ae98 100644 --- a/app/helpers/places_helper.rb +++ b/app/helpers/places_helper.rb @@ -1,147 +1,148 @@ module PlacesHelper # TODO: clean and remove def settimes length end def startTime @startTime ||= Date.today.midnight end def endTime @endTime ||= (Date.today + 1).midnight end def length @length ||= endTime - startTime end def time_block_style(time_block_or_start_offset,end_offset = nil, opts = {}) # Accept "time_block_style(time_block,:direction => :vertical)" if end_offset.class == Hash and opts == {} opts = end_offset end_offset = nil end direction = :vertical if opts[:direction] == :vertical direction = :horizontal if opts[:direction] == :horizontal direction ||= :horizontal if opts[:day] != nil @startTime = opts[:day].midnight @endTime = startTime + 1.days end settimes if end_offset.nil? if time_block_or_start_offset.class == OperatingTime # Generate style for OperatingTime object open = time_block_or_start_offset.opensAt close = time_block_or_start_offset.closesAt else return time_label_style(time_block_or_start_offset) end else # Generate style for block spanning given time range open = startTime.midnight + time_block_or_start_offset close = startTime.midnight + end_offset end if open >= startTime and close <= endTime offset = (open - startTime) * 100.0 / length size = (close - open) * 100.0 / length elsif open >= startTime and close >= endTime offset = (open - startTime) * 100.0 / length size = (endTime - open) * 100.0 / length end case direction when :horizontal "left: #{offset.to_s}%; width: #{size.to_s}%;" when :vertical "top: #{offset.to_s}%; height: #{size.to_s}%;" else "" end end # TODO: clean and remove def time_label_style(at) settimes case at - when Time + when Date + time = at.midnight + when Time,DateTime time = at.hour.hours + at.min.minutes when Integer,Fixnum,Float time = at.to_i.hours end left = (time - startTime) * 100.0 / length "left: #{left.to_s}%;" end # TODO: clean and remove def vertical_now_indicator(at=Time.now) settimes offset = 48; # offset to beginning of dayGraph == width of data cells start = (at.hour.hours + at.min.minutes) * 100.0 / length start = (100.0 - offset) * start/100.0 + offset # incorporate offset "<div class=\"verticalNowIndicator\" style=\"left:#{start.to_s}%;\"></div>" end # TODO: clean and remove def now_indicator(at=Time.now, opts={}) settimes start = (at.hour.hours + at.min.minutes) * 100.0 / length "<div class=\"nowIndicator\" style=\"top:#{start.to_s}%;\"></div>" end def placeClasses(place) classes = ["place"] if place.open? classes << "open" else classes << "closed" end classes += place.tag_list.split(/,/) classes.join(' ') end def short_time_string(time) if time.min == 0 # time has no minutes time.strftime('%I%p').sub(/^0+/,'') else # time has minutes time.strftime('%I:%M%p').sub(/^0+/,'') end end # Returns [words,time] -- both are strings def next_time(place, at=Time.now) - place.daySchedule(at).each do |schedule| + place.daySchedule(at).each do |open,close| # If the whole time period has already passed - next if schedule.opensAt < at and - schedule.closesAt < at + next if close < at - if schedule.opensAt <= at # Open now + if open <= at # Open now # TODO: Handle late-night rollovers - return ["Open until", short_time_string(schedule.closesAt)] + return ["Open until", short_time_string(close)] end - if schedule.closesAt >= at # Closed now - return ["Opens at", short_time_string(schedule.opensAt)] + if close >= at # Closed now + return ["Opens at", short_time_string(open)] end return "ERROR in next_time" # TODO: How could we possibly get here? end return "","Closed" # No more state time changes for today end end diff --git a/app/views/operating_times/index.html.erb b/app/views/operating_times/index.html.erb index 58319b1..f4d6d01 100644 --- a/app/views/operating_times/index.html.erb +++ b/app/views/operating_times/index.html.erb @@ -1,34 +1,34 @@ <h2>Listing operating_times</h2> <table> <tr> <th>Place</th> - <th>Opens At</th> - <th>Closes At</th> + <th>Start</th> + <th>Length</th> <th>Details</th> <th>Days Of Week</th> <th>Flags</th> <th>Start Date</th> <th>End Date</th> </tr> <% for operating_time in @operating_times %> <tr> <td><%=h operating_time.place.name %></td> - <td><%=h operating_time.opensAt %></td> - <td><%=h operating_time.closesAt %></td> + <td><%=h operating_time.start %></td> + <td><%=h operating_time.length %></td> <td><%=h operating_time.details %></td> <td><%=h operating_time.daysOfWeekString %></td> <td><%=h operating_time.flags %></td> <td><%=h operating_time.startDate %></td> <td><%=h operating_time.endDate %></td> <td><%= link_to 'Show', operating_time %></td> <td><%= link_to 'Edit', edit_operating_time_path(operating_time) %></td> <td><%= link_to 'Destroy', operating_time, :confirm => 'Are you sure?', :method => :delete %></td> </tr> <% end %> </table> <br /> <%= link_to 'New operating_time', new_operating_time_path %> diff --git a/app/views/operating_times/show.html.erb b/app/views/operating_times/show.html.erb index 10b4488..cd5c686 100644 --- a/app/views/operating_times/show.html.erb +++ b/app/views/operating_times/show.html.erb @@ -1,48 +1,48 @@ <p> <b>Place:</b> <%= link_to @operating_time.place.name, @operating_time.place %> </p> <p> <b>Details:</b> <%=h @operating_time.details %> </p> <p> - <b>Opensat:</b> - <%=h @operating_time.opensAt %> + <b>Start:</b> + <%=h @operating_time.start %> </p> <p> - <b>Closesat:</b> - <%=h @operating_time.closesAt %> + <b>Length:</b> + <%=h @operating_time.length %> </p> <p> <b>Details:</b> <%=h @operating_time.details %> </p> <p> <b>Days of Week:</b> <%=h @operating_time.daysOfWeekString %> </p> <p> <b>Flags:</b> <%=h @operating_time.flags %> </p> <p> <b>Startdate:</b> <%=h @operating_time.startDate %> </p> <p> <b>Enddate:</b> <%=h @operating_time.endDate %> </p> <%= link_to 'Edit', edit_operating_time_path(@operating_time) %> | <%= link_to 'Back', operating_times_path %> diff --git a/app/views/places/index.html.erb b/app/views/places/index.html.erb index c26ca09..12e9cf3 100644 --- a/app/views/places/index.html.erb +++ b/app/views/places/index.html.erb @@ -1,110 +1,110 @@ <% @places.each do |place| %> <% if RAILS_ENV == 'development' %> <!-- TODO: Remove the following comment (for debugging only) --> <!-- <%= place.inspect %> --> <% end %> <div class="<%=h placeClasses(place) %>" id="place<%=h place.id %>"> <div class="place_short"> <a class="place_name" title="<%=h place.name %>" onclick="toggle_drawer('place<%=h place.id %>',event);return false;" href="<%=h url_for(place) %>"> <span class="bubble-left"></span> <span class="name"><%=h place.name %></span> <span class="bubble-right"></span> </a> <div class="next_time"> <% next_time_words,next_time_time = next_time place %> <div class="next_time_words"><%=h next_time_words %></div> <div class="next_time_time"><%=h next_time_time %></div> </div> </div> <div class="place_long" style="display:none;"> <div class="details"> <div class="location">Location: <span><%=h place.location %></span></div> <div class="phone">Phone: <span><%=h place.phone %></span></div> <%= link_to 'More Info', place, :class => "more_info" %> <a class="weekly_schedule" href="#weekly_schedule">Weekly Schedule</a> <div class="tags"> <span>Tags</span> <% if place.tags != [] %> <% place.tags[0..-2].each do |tag| %> <a class="tag" href="#tag=<%=h tag.name %>"><%=h tag.name %></a>, <% end %> <a class="tag" href="#tag=<%=h place.tags[-1].name %>"><%=h place.tags[-1].name %></a> <% end # if place.tags != [] %> </div> </div> <!-- TODO: Load schedule info to generate timeblocks --> <div class="schedule"><div class="inner-schedule"> <div class="nowindicator"></div> <!-- // Test timeblock <div class="timeblock" id="timeblock_<%=h place.id %>_0" style="left: 0%; width: 100%;"> <div class="bubble-left"></div> <div class="bubble-middle"></div> <div class="bubble-right"></div> </div> --> - <% place.daySchedule.each do |schedule| %> - <div class="timeblock" id="timeblock_<%=h place.id %>_<%=h schedule.id %>" style="<%=h time_block_style(schedule) %>"> + <% place.daySchedule.each do |open,close| %> + <div class="timeblock" id="timeblock_<%=h place.id %>_<%=h rand %>" style="<%=h time_block_style(open.offset,close.offset) %>"> <div class="bubble-left"></div> <div class="bubble-middle"></div> <div class="bubble-right"></div> </div> <% end # place.daySchedule.each %> </div></div> <!-- div.schedule, div.inner-schedule --> </div> </div> <% end # @places.each %> <% =begin %> <!-- TODO: Reimplement under new design --> <div class="tagCloud"> <div style="font-size:2em;font-weight:bold;text-align:center;line-height:1.5em;">Tags</div> <div id="selectedTags" style="border-top: 1px solid black; padding-top:5px;"> <% @selected_tags.each do |tag_name| %> <%= link_to tag_name, { :action => :tag, :id => tag_name }, :id => "selected_tag_#{tag_name}", :class => "selectedTag", :onclick => "handleTagClick('#{h tag_name}',event);return false;" %> <% end %> </div> <script> // <%= @selected_tags.inspect %> <% if not @selected_tags.nil? %> document.lockedTags = <%= @selected_tags.join(", ").inspect %>; <% else %> document.lockedTags = ""; <% end %> </script> <div style="border-top: 1px solid black;padding-top:5px;"> <% tag_cloud @tag_counts, %w(size1 size2 size3 size4 size5 size6) do |tag, css_class| %> <%= link_to tag.name, { :action => :tag, :id => tag.name }, :id => "tag_#{tag.name}", :class => css_class, :onclick => "handleTagClick('#{h tag.name}',event);return false;" %> <% end %> </div> </div> <!-- TODO: Reimplement under new design --> <div style="position:absolute; right:0; top:0;"> <%= link_to "Yesterday", :at => Date.today - 1.day %><br/> <%= link_to "Today", :at => Date.today %><br/> <%= link_to "Tomorrow", :at => Date.today + 1.day %><br/> <%= link_to Date::DAYNAMES[(Date.today + 2.day).wday], :at => Date.today + 2.day %><br/> </div> <% =end %> diff --git a/app/views/places/show.html.erb b/app/views/places/show.html.erb index fe60f2e..2028bbb 100644 --- a/app/views/places/show.html.erb +++ b/app/views/places/show.html.erb @@ -1,76 +1,76 @@ <%= stylesheet_link_tag 'places' %> <p> <b>Name:</b> <%=h @place.name %> </p> <p> <b>Location:</b> <%=h @place.location %> </p> <p> <b>Phone:</b> <%=h @place.phone %> </p> <p> <b>Tags:</b> <%=h @place.tag_list %> </p> <p> <b>Open Now?</b> <%=h (@place.open?(@at) ? "Yes" : "No") %> </p> <p> <b><%= link_to 'All Operating Times', '/operating_times/place/'[email protected]_s %></b> </p> <p> <b>Schedule for this week:</b><br/> <div class="weekSchedule"> <div class="header"> <div class="labelColumn"></div> <% 7.times do |i| %> <div class="dayColumn"> <%= Date::DAYNAMES[(@at + i.days).wday] %> </div> <% end %> </div> <div class="data"> <div class="labelColumn"> <% 24.times do |hour| -%> <div class="color<%= hour % 2 + 1 %>" class="timeblock" style="<%= time_block_style(hour.hours,(hour+1).hours, :direction => :vertical) %> z-index: 2;"><%= hour.to_s %></div> <% end -%> <%= now_indicator %> </div> <% 7.times do |i| %> <div class="dayColumn"> <%= now_indicator if i == 0 %> - <% @place.daySchedule(@at + i.days).each do |schedule| %> - <div class="timeblock" style="<%= time_block_style(schedule, :day => (@at+i.days), :direction => :vertical) %>"> - <div class="opensat"><%=h short_time_string(schedule.opensAt) %></div> - <div class="details"><%=h schedule.details if schedule.length >= 2.hours %></div> - <div class="closesat"><%=h short_time_string(schedule.closesAt) %></div> + <% @place.daySchedule(@at + i.days).each do |open,close| %> + <div class="timeblock" style="<%= time_block_style(open.offset, close.offset, :day => (@at+i.days), :direction => :vertical) %>"> + <div class="opensat"><%=h short_time_string(open) %></div> + <div class="details"><%#=h schedule.details if (close-open) >= 2.hours %></div> + <div class="closesat"><%=h short_time_string(close) %></div> <%#= link_to "#{short_time_string(schedule.opensAt)} - #{short_time_string(schedule.closesAt)}", schedule %> </div> <% end %> </div> <% end %> </div> </div> </p> <%= link_to 'Edit', edit_place_path(@place) %> | <%= link_to 'Back', places_path %>
michaelansel/dukenow
d79abe56a4323e165d80de6c3a7bee1ab9e1cd06
Rename OperatingTime.opensAt to ".start"
diff --git a/app/models/operating_time.rb b/app/models/operating_time.rb index e0f9230..14a651a 100644 --- a/app/models/operating_time.rb +++ b/app/models/operating_time.rb @@ -1,279 +1,238 @@ class OperatingTime < ActiveRecord::Base belongs_to :place acts_as_taggable_on :operating_time_tags validates_presence_of :place_id, :endDate, :startDate validates_associated :place validate :end_after_start, :days_of_week_valid validate {|ot| 0 <= ot.length and ot.length <= 1.days } ## DaysOfWeek Constants ## SUNDAY = 0b00000001 MONDAY = 0b00000010 TUESDAY = 0b00000100 WEDNESDAY = 0b00001000 THURSDAY = 0b00010000 FRIDAY = 0b00100000 SATURDAY = 0b01000000 ALL_DAYS = (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) ## Validations ## def end_after_start if endDate < startDate errors.add_to_base("End date cannot preceed start date") end end def days_of_week_valid days_of_week == days_of_week & (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) end ## End Validations ## # TODO Is this OperatingTime applicable at +time+ def valid_at(time=Time.now) raise NotImplementedError end # Tag Helpers %w{tag_list tags tag_counts tag_ids tag_tagging_ids tag_taggings}.each do |m| [m,m+"="].each do |m| if self.instance_methods.include?("operating_time_"+m) self.class_eval "alias #{m.to_sym} #{"operating_time_#{m}".to_sym}" end end ; end def tags_from ; operating_time_tags_from ; end def override read_attribute(:override) == 1 end def override=(mode) if mode == true or mode == "true" or mode == 1 write_attribute(:override, true) elsif mode == false or mode == "false" or mode == 0 write_attribute(:override, false) else raise ArgumentError, "Invalid override value (#{mode.inspect}); Accepts true/false, 1/0" end end def days_of_week=(newDow) if not ( newDow & ALL_DAYS == newDow ) # Invalid input raise ArgumentError, "Not a valid value for days_of_week (#{newDow.inspect})" end write_attribute(:days_of_week, newDow & ALL_DAYS) @days_of_weekHash = nil @days_of_weekArray = nil @days_of_weekString = nil end ## days_of_week Helpers ## # Hash mapping day of week (Symbol) to valid(true)/invalid(false) def days_of_week_hash @days_of_week_hash ||= { :sunday => (days_of_week & SUNDAY ) > 0, :monday => (days_of_week & MONDAY ) > 0, :tuesday => (days_of_week & TUESDAY ) > 0, :wednesday => (days_of_week & WEDNESDAY ) > 0, :thursday => (days_of_week & THURSDAY ) > 0, :friday => (days_of_week & FRIDAY ) > 0, :saturday => (days_of_week & SATURDAY ) > 0 } end # Array beginning with Sunday of valid(true)/inactive(false) values def days_of_week_array dow = days_of_week_hash @days_of_week_array ||= [ dow[:sunday], dow[:monday], dow[:tuesday], dow[:wednesday], dow[:thursday], dow[:friday], dow[:saturday] ] end # Human-readable string of applicable days of week def days_of_week_string dow = days_of_week_hash @days_of_week_string ||= (dow[:sunday] ? "Su" : "") + (dow[:monday] ? "M" : "") + (dow[:tuesday] ? "Tu" : "") + (dow[:wednesday] ? "W" : "") + (dow[:thursday] ? "Th" : "") + (dow[:friday] ? "F" : "") + (dow[:saturday] ? "Sa" : "") end ## End days_of_week Helpers ## # Returns the next full occurrence of these operating time rule. # If we are currently within a valid time range, it will look forward for the # <em>next</em> opening time def next_times(at = Time.now) at = at.midnight unless at.respond_to? :offset return nil if length == 0 return nil if at.to_date > endDate # Schedules end at 23:59 of the stored endDate at = startDate.midnight if at < startDate # This schedule hasn't started yet, skip to startDate # Next occurrence is later today # This is the only time the "time" actually matters; # after today, all we care about is the date if days_of_week_array[at.wday] and start >= at.offset open = at.midnight + start close = open + length return [open,close] end # We don't care about the time offset anymore, jump to the next midnight at = at.midnight + 1.day # NOTE This also has the added benefit of preventing an infinite loop # from occurring if +at+ gets shifted by 0.days further down. # Shift days_of_weekArray so that +at+ is first element dow = days_of_week_array[at.wday..-1] + days_of_week_array[0..(at.wday-1)] # NOTE The above call does something a little quirky: # In the event that at.wday = 0, it concatenates the array with itself. # Since we are only interested in the first true value, this does not # cause a problem, but could probably be cleaned up if done so carefully. # Next day of the week this schedule is valid for (relative to current day) shift = dow.index(true) if shift # Skip forward at = at + shift.days else # Give up, there are no more occurrences # TODO Test edge case: valid for 1 day/week return nil end # Recurse to rerun the validation routines return next_times(at) end alias :to_times :next_times def to_xml(options = {}) #super(params.merge({:only => [:id, :place_id], :methods => [ {:times => :next_times}, :start, :length, :startDate, :endDate ]})) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] options[:skip_instruct] = true xml.tag!(self.class.to_s.underscore.dasherize) do xml.id(self.id) xml.place_id(self.place_id) #xml.place_name(self.place.name) #xml.place_location(self.place.location) #xml.place_phone(self.place.phone) xml.details(self.details) xml.tags do |xml| self.tag_list.each do |tag| xml.tag(tag) end end xml.start(self.start) xml.length(self.length) self.days_of_week_hash.to_xml(options.merge(:root => :days_of_week)) xml.startDate(self.startDate) xml.endDate(self.endDate) xml.override(self.override) open,close = self.next_times(Date.today) if open.nil? or close.nil? xml.tag!(:next_times.to_s.dasherize, :for => Date.today) else xml.tag!(:next_times.to_s.dasherize, :for => Date.today) do |xml| xml.open(open.xmlschema) xml.close(close.xmlschema) end end end end ##### TODO DEPRECATED METHODS ##### - def at - @at - end - def at=(time) - @opensAt = nil - @closesAt = nil - @at = time - end - - # Returns a Time object representing the beginning of this OperatingTime - def opensAt - @opensAt ||= relativeTime.openTime(at) - end - def closesAt - @closesAt ||= relativeTime.closeTime(at) - end - - # Sets the beginning of this OperatingTime - # Input: params = { :hour => 12, :minute => 45 } - def opensAt=(time) - if time.class == Time - @opensAt = relativeTime.openTime = time - else - super - end - end - - # Sets the end of this OperatingTime - def closesAt=(time) - @closesAt = relativeTime.closeTime = time - end - - - def start - read_attribute(:opensAt) - end - - def start=(offset) - write_attribute(:opensAt,offset) - end - # Returns a RelativeTime object representing this OperatingTime def relativeTime @relativeTime ||= RelativeTime.new(self, :opensAt, :length) end; protected :relativeTime # Backwards compatibility with old database schema # TODO GET RID OF THIS!!! def flags ( (override ? 1 : 0) << 7) | read_attribute(:days_of_week) end # FIXME Deprecated, use +override+ instead def special override end # Input: isSpecial = true/false # FIXME Deprecated, use +override=+ instead def special=(isSpecial) if isSpecial == true or isSpecial == "true" or isSpecial == 1 self.override = true elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 self.override = false end end end diff --git a/db/migrate/20090708211509_rename_opens_at_to_start.rb b/db/migrate/20090708211509_rename_opens_at_to_start.rb new file mode 100644 index 0000000..5c96fd8 --- /dev/null +++ b/db/migrate/20090708211509_rename_opens_at_to_start.rb @@ -0,0 +1,9 @@ +class RenameOpensAtToStart < ActiveRecord::Migration + def self.up + rename_column("operating_times", "opensAt", "start") + end + + def self.down + rename_column("operating_times", "start", "opensAt") + end +end diff --git a/db/schema.rb b/db/schema.rb index 8ca8a6f..6f153d0 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,109 +1,109 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20090707194216) do +ActiveRecord::Schema.define(:version => 20090708211509) do create_table "dining_extensions", :force => true do |t| t.integer "place_id" t.string "logo_url" t.string "more_info_url" t.string "owner_operator" t.string "payment_methods" t.datetime "created_at" t.datetime "updated_at" t.string "menu_url" end create_table "eateries", :force => true do |t| t.string "name" t.string "location" t.string "phone" t.datetime "created_at" t.datetime "updated_at" end create_table "operating_time_taggings", :force => true do |t| t.integer "tag_id" t.integer "taggable_id" t.integer "tagger_id" t.string "tagger_type" t.string "taggable_type" t.string "context" t.datetime "created_at" end add_index "operating_time_taggings", ["tag_id"], :name => "index_operating_time_taggings_on_tag_id" add_index "operating_time_taggings", ["taggable_id", "taggable_type", "context"], :name => "index_operating_time_taggings_on_taggable_id_and_taggable_type_and_context" create_table "operating_time_tags", :force => true do |t| t.string "name" end create_table "operating_times", :force => true do |t| t.integer "place_id" - t.integer "opensAt" + t.integer "start" t.integer "length" t.text "details" t.date "startDate" t.date "endDate" t.datetime "created_at" t.datetime "updated_at" t.integer "override", :default => 0, :null => false t.integer "days_of_week", :default => 0, :null => false end create_table "places", :force => true do |t| t.string "name" t.string "location" t.string "phone" t.datetime "created_at" t.datetime "updated_at" t.integer "building_id" end create_table "regular_operating_times", :force => true do |t| t.integer "eatery_id" t.integer "opensAt" t.integer "closesAt" t.integer "daysOfWeek" t.datetime "created_at" t.datetime "updated_at" end create_table "special_operating_times", :force => true do |t| t.integer "eatery_id" t.integer "opensAt" t.integer "closesAt" t.integer "daysOfWeek" t.date "start" t.date "end" t.datetime "created_at" t.datetime "updated_at" end create_table "taggings", :force => true do |t| t.integer "tag_id" t.integer "taggable_id" t.integer "tagger_id" t.string "tagger_type" t.string "taggable_type" t.string "context" t.datetime "created_at" end add_index "taggings", ["tag_id"], :name => "index_taggings_on_tag_id" add_index "taggings", ["taggable_id", "taggable_type", "context"], :name => "index_taggings_on_taggable_id_and_taggable_type_and_context" create_table "tags", :force => true do |t| t.string "name" end end
michaelansel/dukenow
728d86bf5cb52e190052e6bd25cf6eb8b18dacff
Scheduling spec fixes
diff --git a/app/models/place.rb b/app/models/place.rb index b0a2b14..08dc86a 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,235 +1,246 @@ class Place < ActiveRecord::Base DEBUG = false has_many :operating_times has_one :dining_extension acts_as_taggable_on :tags validates_presence_of :name def special_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 1}) end def regular_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 0}) end # Returns an array of Times representing the opening and closing times # of this Place between +startAt+ and +endAt+ def schedule(startAt,endAt) ## Caching ## @schedules ||= {} if @schedules[startAt.xmlschema] and @schedules[startAt.xmlschema][endAt.xmlschema] return @schedules[startAt.xmlschema][endAt.xmlschema] end ## End Caching ## # TODO Handle events starting within the range but ending outside of it? # TODO Offload this selection to the database; okay for testing though # Select all relevant times (1 day buffer on each end) # NOTE Make sure to use generous date comparisons to allow for midnight rollovers all_regular_operating_times = regular_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} all_special_operating_times = special_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} puts "\nRegular OperatingTimes: #{all_regular_operating_times.inspect}" if DEBUG puts "\nSpecial OperatingTimes: #{all_special_operating_times.inspect}" if DEBUG regular_times = [] special_times = [] special_ranges = [] all_special_operating_times.each do |ot| puts "\nSpecial Scheduling for: #{ot.inspect}" if DEBUG # Special Case: Overriding with NO times (e.g. closed all day) if ot.start == 0 and ot.length == 0 and startAt.to_date <= ot.startDate # Block out the range, but don't add the "null Times" special_ranges << Range.new(ot.startDate,ot.endDate) next end # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt.midnight : startAt - 1.day puts "EarlyStart: #{earlyStart.inspect}" if DEBUG # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do if DEBUG puts "Open: #{open}" puts "Close: #{close}" puts "Start Date: #{ot.startDate} (#{ot.startDate.class})" puts "End Date: #{ot.endDate} (#{ot.endDate.class})" end if close < startAt # Skip forward to the first occurrance in our time range puts "Seeking: #{close} < #{startAt}" if DEBUG open,close = ot.next_times(close) next end special_times << [open,close] special_ranges << Range.new(ot.startDate,ot.endDate) open,close = ot.next_times(close) end end puts "\nSpecial Times: #{special_times.inspect}" if DEBUG puts "\nSpecial Ranges: #{special_ranges.inspect}" if DEBUG all_regular_operating_times.each do |ot| puts "\nRegular Scheduling for: #{ot.inspect}" if DEBUG # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day + puts "EarlyStart: #{earlyStart.inspect}" if DEBUG + # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) - next if open.nil? # No valid occurrences in the future + if DEBUG + puts "" + puts "Open: #{open}" + puts "Close: #{close}" + end + + if open.nil? # No valid occurrences in the future + puts "Skipping: No valid occurrences in the future." if DEBUG + next + end while not open.nil? and open <= endAt do if DEBUG puts "" puts "Open: #{open}" puts "Close: #{close}" end if close < startAt # Skip forward to the first occurrance in our time range puts "Seeking: #{close} < #{startAt}" if DEBUG open,close = ot.next_times(close) next end overridden = false special_ranges.each do |sr| overridden ||= sr.member?(open.to_date) end if overridden puts "Overridden" if DEBUG open,close = ot.next_times(close) next end # FIXME Causing an infinite loop; would be nice if this worked #open = startAt if open < startAt #close = endAt if close > endAt regular_times << [open,close] open,close = ot.next_times(close) end end puts "\nRegular Times: #{regular_times.inspect}" if DEBUG # TODO Handle schedule overrides # TODO Handle combinations (i.e. part special, part regular) final_schedule = (regular_times+special_times).sort{|a,b|a[0] <=> b[0]} ## Caching ## @schedules ||= {} @schedules[startAt.xmlschema] ||= {} @schedules[startAt.xmlschema][endAt.xmlschema] = final_schedule ## End Caching ## final_schedule end def daySchedule(at = Date.today) at = at.to_date if at.class == Time or at.class == DateTime day_schedule = schedule(at.midnight,(at+1).midnight) #schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } #schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end =end day_schedule.sort{|a,b|a[0] <=> b[0]} end def currentSchedule(at = Time.now) puts "At(cS): #{at}" if DEBUG daySchedule(at).select { |open,close| puts "Open(cS): #{open}" if DEBUG puts "Close(cS): #{close}" if DEBUG open <= at and at <= close }[0] end def open?(at = Time.now) a = currentSchedule(at) return a ? true : false end alias :open :open? def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end def to_xml(options = {}) #super(options.merge({:only => [:id, :name, :location, :phone], :methods => [ :open, :daySchedule ] })) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] options[:skip_instruct] = true xml.place do xml.id(self.id) xml.name(self.name) xml.location(self.location) xml.building_id(self.building_id) xml.phone(self.phone) xml.tags do |xml| self.tag_list.each do |tag| xml.tag(tag) end end self.dining_extension.to_xml(options.merge({:no_id => true})) unless self.dining_extension.nil? xml.open(self.open?) if options[:schedule_from] and options[:schedule_to] sched = schedule(options[:schedule_from],options[:schedule_to]) sched_opts = {:from => options[:schedule_from], :to => options[:schedule_to] } elsif options[:schedule_for_date] sched = daySchedule(options[:schedule_for_date]) sched_opts = {:on => options[:schedule_for_date]} else sched = daySchedule(Date.today) sched_opts = {:on => Date.today} end if sched.nil? or sched.empty? xml.schedule(sched_opts) else xml.schedule(sched_opts) do |xml| sched.each do |open,close| xml.open(open.xmlschema) xml.close(close.xmlschema) end end end end end end diff --git a/spec/models/schedules.rb b/spec/models/schedules.rb index 0f6d39f..8784fb9 100644 --- a/spec/models/schedules.rb +++ b/spec/models/schedules.rb @@ -1,385 +1,385 @@ ###################### ##### Scheduling ##### ###################### describe "a Place with scheduling capabilities", :shared => true do before(:each) do add_scheduling_spec_helpers(@place) end validate_setup do before(:each) do - @place.build + @place.build(@at || Time.now) end end it "should be clean" do @place.regular_operating_times.should == [] @place.special_operating_times.should == [] @place.constraints.should == [] @place.times.should == [] end in_order_to "be open now" do before(:each) do @place.add_times([ {:start => 6.hours, :length => 2.hours, :override => false}, {:start => 6.hours, :length => 2.hours, :override => true} ]) @at = @at || (Time.now.midnight + 7.hours) end it "should have operating times" do @place.build(@at) @place.operating_times.should_not be_empty end it "should have a schedule" do @place.build(@at) @place.schedule(@at.midnight, @at.midnight + 1.day).should_not be_empty end it "should have a daySchedule" do @place.build(@at) @place.daySchedule(@at).should_not be_empty end it "should have a currentSchedule" do @place.build(@at) @place.currentSchedule(@at).should_not be_nil end it "should be open on Sunday" do @at = @at - @at.wday.days # Set to previous Sunday - @place.rebuild + @place.rebuild(@at) @place.open(@at).should == true end it "should be open on Wednesday" do @at = @at - @at.wday.days + 3.days # Set to Wednesday after last Sunday @place.rebuild(@at) begin @place.open(@at).should == true rescue Exception => e puts "" puts "At: #{@at}" puts "Times: #{@place.times.inspect}" puts "OperatingTimes: #{@place.operating_times.inspect}" puts "daySchedule: #{@place.daySchedule(@at)}" raise e end end it "should be open on Saturday" do @at = @at - @at.wday.days + 6.days# Set to Saturday after last Sunday @place.rebuild(@at) @place.open(@at).should == true end it "should be open on only one day every week" do @at = @at - @at.wday.days + 6.days# Set to Saturday after last Sunday @place.times.each do |t| t[:days_of_week] = OperatingTime::SATURDAY t[:startDate] = @at.to_date - 2.days t[:endDate] = @at.to_date + 3.weeks end @place.rebuild(@at) @place.schedule(@at-1.day, @at+15.days).should have(3).times @place.schedule(@at-1.day, @at+15.days).collect{|a,b|[a.xmlschema,b.xmlschema]}.uniq.should have(3).unique_times end end in_order_to "be open 24 hours" do before(:each) do @place.add_times([ {:start => 0, :length => 24.hours, :override => false}, {:start => 0, :length => 24.hours, :override => true} ]) @at = @at || (Time.now.midnight + 12.hours) @place.build(@at) end it "should be open during the day" do @place.open(@at).should == true end it "should be open at midnight" do @place.open(@at.midnight).should == true end end in_order_to "be open later in the day" do before(:each) do @place.add_times([ {:start => 16.hours, :length => 2.hours, :override => false}, {:start => 16.hours, :length => 2.hours, :override => true} ]) @at = @at || (Time.now.midnight + 12.hours) @place.build(@at) end it "should be closed now" do @place.open(@at).should == false end it "should have a schedule later in the day" do @place.schedule(@at,@at.midnight + 24.hours).should_not be_empty end it "should not have a schedule earlier in the day" do @place.schedule(@at.midnight,@at).should be_empty end end in_order_to "be closed for the day" do before(:each) do @place.add_times([ {:start => 4.hours, :length => 2.hours, :override => false}, {:start => 4.hours, :length => 2.hours, :override => true} ]) @at = @at || (Time.now.midnight + 12.hours) @place.build(@at) end it "should be closed now" do @place.open(@at).should == false end it "should have a schedule earlier in the day" do @place.schedule(@at.midnight,@at).should_not be_empty end it "should not have a schedule later in the day" do @place.schedule(@at, @at.midnight + 24.hours).should be_empty end end in_order_to "be open past midnight" do before(:each) do @at = @at || (Time.now.midnight + 12.hours) @place.add_times([ {:start => 23.hours, :length => 4.hours, :override => true}, {:start => 23.hours, :length => 4.hours, :override => false} ]) @place.times.each do |t| t[:startDate] = @at.to_date t[:endDate] = @at.to_date end @place.build(@at) end it "should be open early the next morning" do @place.open(@at.midnight + 1.days + 2.hours).should == true end it "should not be open early that morning" do @place.open(@at.midnight + 2.hours).should == false end it "should not be open late the next night" do @place.open(@at.midnight + 2.days + 2.hours).should == false end end in_order_to "be closed now" do before(:each) do @place.add_constraint {|t| ( t[:start] > @at.offset ) or ( (t[:start] + t[:length]) < @at.offset ) } @place.add_times([ {:start => 6.hours, :length => 2.hours, :override => false}, {:start => 6.hours, :length => 2.hours, :override => true} ]) @at = @at || (Time.now.midnight + 12.hours) - @place.build + @place.build(@at) end it "should be closed" do @place.open(@at).should == false end end in_order_to "be closed all day" do before(:each) do @at ||= Time.now @place.add_times([ {:start => 0, :length => 0, :startDate => @at.to_date, :endDate => @at.to_date, :override => false}, {:start => 0, :length => 0, :startDate => @at.to_date, :endDate => @at.to_date, :override => true} ]) @place.build(@at) end it "should be closed now" do @place.open(@at).should == false end it "should not have a schedule earlier in the day" do @place.schedule(@at.midnight,@at).should be_empty end it "should not have a schedule later in the day" do @place.schedule(@at, @at.midnight + 24.hours).should be_empty end it "should not have a schedule at all for the day" do @place.daySchedule(@at).should be_empty end end in_order_to "have a valid schedule" do it "should not have any overlapping times" it "should have all times within the specified time range" end end describe "a Place with valid times", :shared => true do describe "with only regular times" do before(:each) do @place.add_constraint {|t| t[:override] == false } @place.build end validate_setup do it "should have regular times" do #puts "Regular Times: #{@place.regular_operating_times.inspect}" @place.regular_operating_times.should_not be_empty end it "should not have any special times" do #puts "Special Times: #{@place.special_operating_times.inspect}" @place.special_operating_times.should be_empty end end it_can "be open now" it_can "be open 24 hours" it_can "be open past midnight" it_can "be open later in the day" it_can "be closed for the day" it_can "be closed now" it_can "be closed all day" end describe "with only special times" do before(:each) do @place.add_constraint {|t| t[:override] == true } @place.build end validate_setup do it "should not have regular times" do @place.regular_operating_times.should be_empty end it "should have special times" do @place.special_operating_times.should_not be_empty end end it_can "be open now" it_can "be open 24 hours" it_can "be open past midnight" it_can "be open later in the day" it_can "be closed for the day" it_can "be closed now" it_can "be closed all day" end describe "with regular and special times" do validate_setup do it "should have regular times" do @place.regular_operating_times.should_not be_empty end it "should have special times" do @place.special_operating_times.should_not be_empty end end describe "where the special times are overriding the regular times" do #it_can "be open now" #it_can "be open 24 hours" #it_can "be open past midnight" #it_can "be open later in the day" #it_can "be closed for the day" #it_can "be closed now" #it_can "be closed all day" end describe "where the special times are not overriding the regular times" do #it_can "be open now" #it_can "be open 24 hours" #it_can "be open past midnight" #it_can "be open later in the day" #it_can "be closed for the day" #it_can "be closed now" #it_can "be closed all day" end end describe "with special times" do describe "extending normal hours" do #it_can "be open now" #it_can "be open 24 hours" #it_can "be open past midnight" #it_can "be open later in the day" #it_can "be closed for the day" #it_can "be closed now" #it_can "be closed all day" end describe "reducing normal hours" do #it_can "be open now" #it_can "be open 24 hours" #it_can "be open past midnight" #it_can "be open later in the day" #it_can "be closed for the day" #it_can "be closed now" #it_can "be closed all day" end describe "removing all hours" do before(:each) do @at = @at || (Time.now.midnight + 8.hours) @place.add_times([ {:start => 6.hours, :length => 9.hours, :override => false}, {:start => 0, :length => 0, :override => true, :startDate => @at.to_date, :endDate => @at.to_date} ]) - @place.build + @place.build(@at) end it_can "be closed now" it_can "be closed all day" end describe "moving normal hours (extending and reducing)" do #it_can "be open now" #it_can "be open 24 hours" #it_can "be open past midnight" #it_can "be open later in the day" #it_can "be closed for the day" #it_can "be closed now" #it_can "be closed all day" end end end
michaelansel/dukenow
d84a316d4d0cdbd2c9a1393ef6666b7587e9c0ac
Extend specs and fix bug when overridding to close a location all day which is normally open
diff --git a/app/models/place.rb b/app/models/place.rb index 4e609d2..b0a2b14 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,215 +1,235 @@ class Place < ActiveRecord::Base DEBUG = false has_many :operating_times has_one :dining_extension acts_as_taggable_on :tags validates_presence_of :name def special_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 1}) end def regular_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 0}) end # Returns an array of Times representing the opening and closing times # of this Place between +startAt+ and +endAt+ def schedule(startAt,endAt) ## Caching ## @schedules ||= {} if @schedules[startAt.xmlschema] and @schedules[startAt.xmlschema][endAt.xmlschema] return @schedules[startAt.xmlschema][endAt.xmlschema] end ## End Caching ## # TODO Handle events starting within the range but ending outside of it? # TODO Offload this selection to the database; okay for testing though # Select all relevant times (1 day buffer on each end) # NOTE Make sure to use generous date comparisons to allow for midnight rollovers all_regular_operating_times = regular_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} all_special_operating_times = special_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} puts "\nRegular OperatingTimes: #{all_regular_operating_times.inspect}" if DEBUG puts "\nSpecial OperatingTimes: #{all_special_operating_times.inspect}" if DEBUG regular_times = [] special_times = [] special_ranges = [] all_special_operating_times.each do |ot| puts "\nSpecial Scheduling for: #{ot.inspect}" if DEBUG + # Special Case: Overriding with NO times (e.g. closed all day) + if ot.start == 0 and ot.length == 0 and startAt.to_date <= ot.startDate + # Block out the range, but don't add the "null Times" + special_ranges << Range.new(ot.startDate,ot.endDate) + next + end + # Start a day early if possible - earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day + earlyStart = startAt-1.day < ot.startDate.midnight ? startAt.midnight : startAt - 1.day + puts "EarlyStart: #{earlyStart.inspect}" if DEBUG + # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do if DEBUG puts "Open: #{open}" puts "Close: #{close}" puts "Start Date: #{ot.startDate} (#{ot.startDate.class})" puts "End Date: #{ot.endDate} (#{ot.endDate.class})" end if close < startAt # Skip forward to the first occurrance in our time range + puts "Seeking: #{close} < #{startAt}" if DEBUG open,close = ot.next_times(close) next end special_times << [open,close] special_ranges << Range.new(ot.startDate,ot.endDate) open,close = ot.next_times(close) end end puts "\nSpecial Times: #{special_times.inspect}" if DEBUG puts "\nSpecial Ranges: #{special_ranges.inspect}" if DEBUG all_regular_operating_times.each do |ot| puts "\nRegular Scheduling for: #{ot.inspect}" if DEBUG # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do - puts "Open: #{open}" if DEBUG - puts "Close: #{close}" if DEBUG + if DEBUG + puts "" + puts "Open: #{open}" + puts "Close: #{close}" + end if close < startAt # Skip forward to the first occurrance in our time range + puts "Seeking: #{close} < #{startAt}" if DEBUG open,close = ot.next_times(close) next end + overridden = false special_ranges.each do |sr| - next if sr.member?(open) + overridden ||= sr.member?(open.to_date) + end + if overridden + puts "Overridden" if DEBUG + open,close = ot.next_times(close) + next end # FIXME Causing an infinite loop; would be nice if this worked #open = startAt if open < startAt #close = endAt if close > endAt regular_times << [open,close] open,close = ot.next_times(close) end end puts "\nRegular Times: #{regular_times.inspect}" if DEBUG # TODO Handle schedule overrides # TODO Handle combinations (i.e. part special, part regular) final_schedule = (regular_times+special_times).sort{|a,b|a[0] <=> b[0]} ## Caching ## @schedules ||= {} @schedules[startAt.xmlschema] ||= {} @schedules[startAt.xmlschema][endAt.xmlschema] = final_schedule ## End Caching ## final_schedule end def daySchedule(at = Date.today) at = at.to_date if at.class == Time or at.class == DateTime day_schedule = schedule(at.midnight,(at+1).midnight) #schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } #schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end =end day_schedule.sort{|a,b|a[0] <=> b[0]} end def currentSchedule(at = Time.now) puts "At(cS): #{at}" if DEBUG daySchedule(at).select { |open,close| puts "Open(cS): #{open}" if DEBUG puts "Close(cS): #{close}" if DEBUG open <= at and at <= close }[0] end def open?(at = Time.now) a = currentSchedule(at) return a ? true : false end alias :open :open? def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end def to_xml(options = {}) #super(options.merge({:only => [:id, :name, :location, :phone], :methods => [ :open, :daySchedule ] })) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] options[:skip_instruct] = true xml.place do xml.id(self.id) xml.name(self.name) xml.location(self.location) xml.building_id(self.building_id) xml.phone(self.phone) xml.tags do |xml| self.tag_list.each do |tag| xml.tag(tag) end end self.dining_extension.to_xml(options.merge({:no_id => true})) unless self.dining_extension.nil? xml.open(self.open?) if options[:schedule_from] and options[:schedule_to] sched = schedule(options[:schedule_from],options[:schedule_to]) sched_opts = {:from => options[:schedule_from], :to => options[:schedule_to] } elsif options[:schedule_for_date] sched = daySchedule(options[:schedule_for_date]) sched_opts = {:on => options[:schedule_for_date]} else sched = daySchedule(Date.today) sched_opts = {:on => Date.today} end if sched.nil? or sched.empty? xml.schedule(sched_opts) else xml.schedule(sched_opts) do |xml| sched.each do |open,close| xml.open(open.xmlschema) xml.close(close.xmlschema) end end end end end end diff --git a/spec/models/schedules.rb b/spec/models/schedules.rb index fb2cd8f..0f6d39f 100644 --- a/spec/models/schedules.rb +++ b/spec/models/schedules.rb @@ -1,380 +1,385 @@ ###################### ##### Scheduling ##### ###################### describe "a Place with scheduling capabilities", :shared => true do before(:each) do add_scheduling_spec_helpers(@place) end validate_setup do before(:each) do @place.build end end it "should be clean" do @place.regular_operating_times.should == [] @place.special_operating_times.should == [] @place.constraints.should == [] @place.times.should == [] end in_order_to "be open now" do before(:each) do @place.add_times([ {:start => 6.hours, :length => 2.hours, :override => false}, {:start => 6.hours, :length => 2.hours, :override => true} ]) - @at = (@at || Time.now).midnight + 7.hours + @at = @at || (Time.now.midnight + 7.hours) end it "should have operating times" do @place.build(@at) @place.operating_times.should_not be_empty end it "should have a schedule" do @place.build(@at) @place.schedule(@at.midnight, @at.midnight + 1.day).should_not be_empty end it "should have a daySchedule" do @place.build(@at) @place.daySchedule(@at).should_not be_empty end it "should have a currentSchedule" do @place.build(@at) @place.currentSchedule(@at).should_not be_nil end it "should be open on Sunday" do @at = @at - @at.wday.days # Set to previous Sunday @place.rebuild @place.open(@at).should == true end it "should be open on Wednesday" do @at = @at - @at.wday.days + 3.days # Set to Wednesday after last Sunday @place.rebuild(@at) begin @place.open(@at).should == true rescue Exception => e puts "" puts "At: #{@at}" puts "Times: #{@place.times.inspect}" puts "OperatingTimes: #{@place.operating_times.inspect}" puts "daySchedule: #{@place.daySchedule(@at)}" raise e end end it "should be open on Saturday" do @at = @at - @at.wday.days + 6.days# Set to Saturday after last Sunday @place.rebuild(@at) @place.open(@at).should == true end it "should be open on only one day every week" do @at = @at - @at.wday.days + 6.days# Set to Saturday after last Sunday @place.times.each do |t| t[:days_of_week] = OperatingTime::SATURDAY t[:startDate] = @at.to_date - 2.days t[:endDate] = @at.to_date + 3.weeks end @place.rebuild(@at) @place.schedule(@at-1.day, @at+15.days).should have(3).times @place.schedule(@at-1.day, @at+15.days).collect{|a,b|[a.xmlschema,b.xmlschema]}.uniq.should have(3).unique_times end end in_order_to "be open 24 hours" do before(:each) do @place.add_times([ {:start => 0, :length => 24.hours, :override => false}, {:start => 0, :length => 24.hours, :override => true} ]) - @at = (@at || Time.now).midnight + 12.hours + @at = @at || (Time.now.midnight + 12.hours) @place.build(@at) end it "should be open during the day" do @place.open(@at).should == true end it "should be open at midnight" do @place.open(@at.midnight).should == true end end in_order_to "be open later in the day" do before(:each) do @place.add_times([ {:start => 16.hours, :length => 2.hours, :override => false}, {:start => 16.hours, :length => 2.hours, :override => true} ]) - @at = (@at || Time.now).midnight + 12.hours + @at = @at || (Time.now.midnight + 12.hours) @place.build(@at) end it "should be closed now" do @place.open(@at).should == false end it "should have a schedule later in the day" do @place.schedule(@at,@at.midnight + 24.hours).should_not be_empty end it "should not have a schedule earlier in the day" do @place.schedule(@at.midnight,@at).should be_empty end end in_order_to "be closed for the day" do before(:each) do @place.add_times([ {:start => 4.hours, :length => 2.hours, :override => false}, {:start => 4.hours, :length => 2.hours, :override => true} ]) - @at = (@at || Time.now).midnight + 12.hours + @at = @at || (Time.now.midnight + 12.hours) @place.build(@at) end it "should be closed now" do @place.open(@at).should == false end it "should have a schedule earlier in the day" do @place.schedule(@at.midnight,@at).should_not be_empty end it "should not have a schedule later in the day" do @place.schedule(@at, @at.midnight + 24.hours).should be_empty end end in_order_to "be open past midnight" do before(:each) do - @at = (@at || Time.now).midnight + 12.hours + @at = @at || (Time.now.midnight + 12.hours) @place.add_times([ {:start => 23.hours, :length => 4.hours, :override => true}, {:start => 23.hours, :length => 4.hours, :override => false} ]) @place.times.each do |t| t[:startDate] = @at.to_date t[:endDate] = @at.to_date end @place.build(@at) end it "should be open early the next morning" do @place.open(@at.midnight + 1.days + 2.hours).should == true end it "should not be open early that morning" do @place.open(@at.midnight + 2.hours).should == false end it "should not be open late the next night" do @place.open(@at.midnight + 2.days + 2.hours).should == false end end in_order_to "be closed now" do before(:each) do @place.add_constraint {|t| ( t[:start] > @at.offset ) or ( (t[:start] + t[:length]) < @at.offset ) } @place.add_times([ {:start => 6.hours, :length => 2.hours, :override => false}, {:start => 6.hours, :length => 2.hours, :override => true} ]) - @at = Time.now.midnight + 12.hours + @at = @at || (Time.now.midnight + 12.hours) @place.build end it "should be closed" do @place.open(@at).should == false end end in_order_to "be closed all day" do before(:each) do @at ||= Time.now @place.add_times([ {:start => 0, :length => 0, :startDate => @at.to_date, :endDate => @at.to_date, :override => false}, {:start => 0, :length => 0, :startDate => @at.to_date, :endDate => @at.to_date, :override => true} ]) @place.build(@at) end it "should be closed now" do @place.open(@at).should == false end it "should not have a schedule earlier in the day" do @place.schedule(@at.midnight,@at).should be_empty end it "should not have a schedule later in the day" do @place.schedule(@at, @at.midnight + 24.hours).should be_empty end it "should not have a schedule at all for the day" do @place.daySchedule(@at).should be_empty end end in_order_to "have a valid schedule" do it "should not have any overlapping times" it "should have all times within the specified time range" end end describe "a Place with valid times", :shared => true do describe "with only regular times" do before(:each) do @place.add_constraint {|t| t[:override] == false } @place.build end validate_setup do it "should have regular times" do #puts "Regular Times: #{@place.regular_operating_times.inspect}" @place.regular_operating_times.should_not be_empty end it "should not have any special times" do #puts "Special Times: #{@place.special_operating_times.inspect}" @place.special_operating_times.should be_empty end end it_can "be open now" it_can "be open 24 hours" it_can "be open past midnight" it_can "be open later in the day" it_can "be closed for the day" it_can "be closed now" it_can "be closed all day" end describe "with only special times" do before(:each) do @place.add_constraint {|t| t[:override] == true } @place.build end validate_setup do it "should not have regular times" do @place.regular_operating_times.should be_empty end it "should have special times" do @place.special_operating_times.should_not be_empty end end it_can "be open now" it_can "be open 24 hours" it_can "be open past midnight" it_can "be open later in the day" it_can "be closed for the day" it_can "be closed now" it_can "be closed all day" end describe "with regular and special times" do validate_setup do it "should have regular times" do @place.regular_operating_times.should_not be_empty end it "should have special times" do @place.special_operating_times.should_not be_empty end end describe "where the special times are overriding the regular times" do #it_can "be open now" #it_can "be open 24 hours" #it_can "be open past midnight" #it_can "be open later in the day" #it_can "be closed for the day" #it_can "be closed now" #it_can "be closed all day" end describe "where the special times are not overriding the regular times" do #it_can "be open now" #it_can "be open 24 hours" #it_can "be open past midnight" #it_can "be open later in the day" #it_can "be closed for the day" #it_can "be closed now" #it_can "be closed all day" end end describe "with special times" do describe "extending normal hours" do #it_can "be open now" #it_can "be open 24 hours" #it_can "be open past midnight" #it_can "be open later in the day" #it_can "be closed for the day" #it_can "be closed now" #it_can "be closed all day" end describe "reducing normal hours" do #it_can "be open now" #it_can "be open 24 hours" #it_can "be open past midnight" #it_can "be open later in the day" #it_can "be closed for the day" #it_can "be closed now" #it_can "be closed all day" end describe "removing all hours" do - #it_can "be open now" - #it_can "be open 24 hours" - #it_can "be open past midnight" - #it_can "be open later in the day" - #it_can "be closed for the day" - #it_can "be closed now" - #it_can "be closed all day" + before(:each) do + @at = @at || (Time.now.midnight + 8.hours) + + @place.add_times([ + {:start => 6.hours, :length => 9.hours, :override => false}, + {:start => 0, :length => 0, :override => true, :startDate => @at.to_date, :endDate => @at.to_date} + ]) + + @place.build + end + it_can "be closed now" + it_can "be closed all day" end describe "moving normal hours (extending and reducing)" do #it_can "be open now" #it_can "be open 24 hours" #it_can "be open past midnight" #it_can "be open later in the day" #it_can "be closed for the day" #it_can "be closed now" #it_can "be closed all day" end end end
michaelansel/dukenow
2045eefefb064c2cd0b13d3b09d2c7b32c06dc41
Rework DiningExtensions XML to be more flexible; Bugfix in OperatingTime.to_xml
diff --git a/app/models/dining_extension.rb b/app/models/dining_extension.rb index 4e0e0c7..5ad0089 100644 --- a/app/models/dining_extension.rb +++ b/app/models/dining_extension.rb @@ -1,16 +1,24 @@ class DiningExtension < ActiveRecord::Base belongs_to :place def to_xml(options = {}) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] - xml.tag!(self.class.to_s.underscore.dasherize) do |xml| - xml.tag!(:place_id.to_s.dasherize, place_id) unless options[:no_id] - xml.tag!(:logo_url.to_s.dasherize, logo_url) - xml.tag!(:more_info_url.to_s.dasherize, more_info_url) - xml.tag!(:owner_operator.to_s.dasherize, owner_operator) - xml.tag!(:payment_methods.to_s.dasherize, payment_methods) + xml.tag!(self.class.to_s.pluralize.underscore.dasherize) do |xml| + attrs = self.attributes() + + # Remove attributes we don't want to include + attrs.delete(:id.to_s) + attrs.delete(:created_at.to_s) + attrs.delete(:updated_at.to_s) + + attrs.delete(:place_id.to_s) if options[:no_id] + + # Build dining-extensions tag + attrs.each do |attr,val| + xml.tag!(attr.to_s.dasherize, {:label => attr.titleize}, val) + end end end end diff --git a/app/models/operating_time.rb b/app/models/operating_time.rb index 7076def..e0f9230 100644 --- a/app/models/operating_time.rb +++ b/app/models/operating_time.rb @@ -1,278 +1,279 @@ class OperatingTime < ActiveRecord::Base belongs_to :place acts_as_taggable_on :operating_time_tags validates_presence_of :place_id, :endDate, :startDate validates_associated :place validate :end_after_start, :days_of_week_valid validate {|ot| 0 <= ot.length and ot.length <= 1.days } ## DaysOfWeek Constants ## SUNDAY = 0b00000001 MONDAY = 0b00000010 TUESDAY = 0b00000100 WEDNESDAY = 0b00001000 THURSDAY = 0b00010000 FRIDAY = 0b00100000 SATURDAY = 0b01000000 ALL_DAYS = (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) ## Validations ## def end_after_start if endDate < startDate errors.add_to_base("End date cannot preceed start date") end end def days_of_week_valid days_of_week == days_of_week & (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) end ## End Validations ## # TODO Is this OperatingTime applicable at +time+ def valid_at(time=Time.now) raise NotImplementedError end # Tag Helpers %w{tag_list tags tag_counts tag_ids tag_tagging_ids tag_taggings}.each do |m| [m,m+"="].each do |m| if self.instance_methods.include?("operating_time_"+m) self.class_eval "alias #{m.to_sym} #{"operating_time_#{m}".to_sym}" end end ; end def tags_from ; operating_time_tags_from ; end def override read_attribute(:override) == 1 end def override=(mode) if mode == true or mode == "true" or mode == 1 write_attribute(:override, true) elsif mode == false or mode == "false" or mode == 0 write_attribute(:override, false) else raise ArgumentError, "Invalid override value (#{mode.inspect}); Accepts true/false, 1/0" end end def days_of_week=(newDow) if not ( newDow & ALL_DAYS == newDow ) # Invalid input raise ArgumentError, "Not a valid value for days_of_week (#{newDow.inspect})" end write_attribute(:days_of_week, newDow & ALL_DAYS) @days_of_weekHash = nil @days_of_weekArray = nil @days_of_weekString = nil end ## days_of_week Helpers ## # Hash mapping day of week (Symbol) to valid(true)/invalid(false) def days_of_week_hash @days_of_week_hash ||= { :sunday => (days_of_week & SUNDAY ) > 0, :monday => (days_of_week & MONDAY ) > 0, :tuesday => (days_of_week & TUESDAY ) > 0, :wednesday => (days_of_week & WEDNESDAY ) > 0, :thursday => (days_of_week & THURSDAY ) > 0, :friday => (days_of_week & FRIDAY ) > 0, :saturday => (days_of_week & SATURDAY ) > 0 } end # Array beginning with Sunday of valid(true)/inactive(false) values def days_of_week_array dow = days_of_week_hash @days_of_week_array ||= [ dow[:sunday], dow[:monday], dow[:tuesday], dow[:wednesday], dow[:thursday], dow[:friday], dow[:saturday] ] end # Human-readable string of applicable days of week def days_of_week_string dow = days_of_week_hash @days_of_week_string ||= (dow[:sunday] ? "Su" : "") + (dow[:monday] ? "M" : "") + (dow[:tuesday] ? "Tu" : "") + (dow[:wednesday] ? "W" : "") + (dow[:thursday] ? "Th" : "") + (dow[:friday] ? "F" : "") + (dow[:saturday] ? "Sa" : "") end ## End days_of_week Helpers ## # Returns the next full occurrence of these operating time rule. # If we are currently within a valid time range, it will look forward for the # <em>next</em> opening time def next_times(at = Time.now) at = at.midnight unless at.respond_to? :offset return nil if length == 0 return nil if at.to_date > endDate # Schedules end at 23:59 of the stored endDate at = startDate.midnight if at < startDate # This schedule hasn't started yet, skip to startDate # Next occurrence is later today # This is the only time the "time" actually matters; # after today, all we care about is the date if days_of_week_array[at.wday] and start >= at.offset open = at.midnight + start close = open + length return [open,close] end # We don't care about the time offset anymore, jump to the next midnight at = at.midnight + 1.day # NOTE This also has the added benefit of preventing an infinite loop # from occurring if +at+ gets shifted by 0.days further down. # Shift days_of_weekArray so that +at+ is first element dow = days_of_week_array[at.wday..-1] + days_of_week_array[0..(at.wday-1)] # NOTE The above call does something a little quirky: # In the event that at.wday = 0, it concatenates the array with itself. # Since we are only interested in the first true value, this does not # cause a problem, but could probably be cleaned up if done so carefully. # Next day of the week this schedule is valid for (relative to current day) shift = dow.index(true) if shift # Skip forward at = at + shift.days else # Give up, there are no more occurrences # TODO Test edge case: valid for 1 day/week return nil end # Recurse to rerun the validation routines return next_times(at) end alias :to_times :next_times def to_xml(options = {}) #super(params.merge({:only => [:id, :place_id], :methods => [ {:times => :next_times}, :start, :length, :startDate, :endDate ]})) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] + options[:skip_instruct] = true xml.tag!(self.class.to_s.underscore.dasherize) do xml.id(self.id) xml.place_id(self.place_id) #xml.place_name(self.place.name) #xml.place_location(self.place.location) #xml.place_phone(self.place.phone) xml.details(self.details) xml.tags do |xml| self.tag_list.each do |tag| xml.tag(tag) end end xml.start(self.start) xml.length(self.length) self.days_of_week_hash.to_xml(options.merge(:root => :days_of_week)) xml.startDate(self.startDate) xml.endDate(self.endDate) xml.override(self.override) open,close = self.next_times(Date.today) if open.nil? or close.nil? xml.tag!(:next_times.to_s.dasherize, :for => Date.today) else xml.tag!(:next_times.to_s.dasherize, :for => Date.today) do |xml| xml.open(open.xmlschema) xml.close(close.xmlschema) end end end end ##### TODO DEPRECATED METHODS ##### def at @at end def at=(time) @opensAt = nil @closesAt = nil @at = time end # Returns a Time object representing the beginning of this OperatingTime def opensAt @opensAt ||= relativeTime.openTime(at) end def closesAt @closesAt ||= relativeTime.closeTime(at) end # Sets the beginning of this OperatingTime # Input: params = { :hour => 12, :minute => 45 } def opensAt=(time) if time.class == Time @opensAt = relativeTime.openTime = time else super end end # Sets the end of this OperatingTime def closesAt=(time) @closesAt = relativeTime.closeTime = time end def start read_attribute(:opensAt) end def start=(offset) write_attribute(:opensAt,offset) end # Returns a RelativeTime object representing this OperatingTime def relativeTime @relativeTime ||= RelativeTime.new(self, :opensAt, :length) end; protected :relativeTime # Backwards compatibility with old database schema # TODO GET RID OF THIS!!! def flags ( (override ? 1 : 0) << 7) | read_attribute(:days_of_week) end # FIXME Deprecated, use +override+ instead def special override end # Input: isSpecial = true/false # FIXME Deprecated, use +override=+ instead def special=(isSpecial) if isSpecial == true or isSpecial == "true" or isSpecial == 1 self.override = true elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 self.override = false end end end diff --git a/db/migrate/20090707194216_add_menu_url.rb b/db/migrate/20090707194216_add_menu_url.rb new file mode 100644 index 0000000..c7ba07d --- /dev/null +++ b/db/migrate/20090707194216_add_menu_url.rb @@ -0,0 +1,9 @@ +class AddMenuUrl < ActiveRecord::Migration + def self.up + add_column("dining_extensions", "menu_url", :string) + end + + def self.down + remove_column("dining_extensions", "menu_url") + end +end diff --git a/db/schema.rb b/db/schema.rb index 73717ca..8ca8a6f 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,108 +1,109 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20090707155143) do +ActiveRecord::Schema.define(:version => 20090707194216) do create_table "dining_extensions", :force => true do |t| t.integer "place_id" t.string "logo_url" t.string "more_info_url" t.string "owner_operator" t.string "payment_methods" t.datetime "created_at" t.datetime "updated_at" + t.string "menu_url" end create_table "eateries", :force => true do |t| t.string "name" t.string "location" t.string "phone" t.datetime "created_at" t.datetime "updated_at" end create_table "operating_time_taggings", :force => true do |t| t.integer "tag_id" t.integer "taggable_id" t.integer "tagger_id" t.string "tagger_type" t.string "taggable_type" t.string "context" t.datetime "created_at" end add_index "operating_time_taggings", ["tag_id"], :name => "index_operating_time_taggings_on_tag_id" add_index "operating_time_taggings", ["taggable_id", "taggable_type", "context"], :name => "index_operating_time_taggings_on_taggable_id_and_taggable_type_and_context" create_table "operating_time_tags", :force => true do |t| t.string "name" end create_table "operating_times", :force => true do |t| t.integer "place_id" t.integer "opensAt" t.integer "length" t.text "details" t.date "startDate" t.date "endDate" t.datetime "created_at" t.datetime "updated_at" t.integer "override", :default => 0, :null => false t.integer "days_of_week", :default => 0, :null => false end create_table "places", :force => true do |t| t.string "name" t.string "location" t.string "phone" t.datetime "created_at" t.datetime "updated_at" t.integer "building_id" end create_table "regular_operating_times", :force => true do |t| t.integer "eatery_id" t.integer "opensAt" t.integer "closesAt" t.integer "daysOfWeek" t.datetime "created_at" t.datetime "updated_at" end create_table "special_operating_times", :force => true do |t| t.integer "eatery_id" t.integer "opensAt" t.integer "closesAt" t.integer "daysOfWeek" t.date "start" t.date "end" t.datetime "created_at" t.datetime "updated_at" end create_table "taggings", :force => true do |t| t.integer "tag_id" t.integer "taggable_id" t.integer "tagger_id" t.string "tagger_type" t.string "taggable_type" t.string "context" t.datetime "created_at" end add_index "taggings", ["tag_id"], :name => "index_taggings_on_tag_id" add_index "taggings", ["taggable_id", "taggable_type", "context"], :name => "index_taggings_on_taggable_id_and_taggable_type_and_context" create_table "tags", :force => true do |t| t.string "name" end end
michaelansel/dukenow
79cb37e482e836898eec38bc5fc1a96936678193
Bugfix: OperatingTime.to_xml arity incorrect
diff --git a/app/models/operating_time.rb b/app/models/operating_time.rb index 2896551..7076def 100644 --- a/app/models/operating_time.rb +++ b/app/models/operating_time.rb @@ -1,278 +1,278 @@ class OperatingTime < ActiveRecord::Base belongs_to :place acts_as_taggable_on :operating_time_tags validates_presence_of :place_id, :endDate, :startDate validates_associated :place validate :end_after_start, :days_of_week_valid validate {|ot| 0 <= ot.length and ot.length <= 1.days } ## DaysOfWeek Constants ## SUNDAY = 0b00000001 MONDAY = 0b00000010 TUESDAY = 0b00000100 WEDNESDAY = 0b00001000 THURSDAY = 0b00010000 FRIDAY = 0b00100000 SATURDAY = 0b01000000 ALL_DAYS = (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) ## Validations ## def end_after_start if endDate < startDate errors.add_to_base("End date cannot preceed start date") end end def days_of_week_valid days_of_week == days_of_week & (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) end ## End Validations ## # TODO Is this OperatingTime applicable at +time+ def valid_at(time=Time.now) raise NotImplementedError end # Tag Helpers %w{tag_list tags tag_counts tag_ids tag_tagging_ids tag_taggings}.each do |m| [m,m+"="].each do |m| if self.instance_methods.include?("operating_time_"+m) self.class_eval "alias #{m.to_sym} #{"operating_time_#{m}".to_sym}" end end ; end def tags_from ; operating_time_tags_from ; end def override read_attribute(:override) == 1 end def override=(mode) if mode == true or mode == "true" or mode == 1 write_attribute(:override, true) elsif mode == false or mode == "false" or mode == 0 write_attribute(:override, false) else raise ArgumentError, "Invalid override value (#{mode.inspect}); Accepts true/false, 1/0" end end def days_of_week=(newDow) if not ( newDow & ALL_DAYS == newDow ) # Invalid input raise ArgumentError, "Not a valid value for days_of_week (#{newDow.inspect})" end write_attribute(:days_of_week, newDow & ALL_DAYS) @days_of_weekHash = nil @days_of_weekArray = nil @days_of_weekString = nil end ## days_of_week Helpers ## # Hash mapping day of week (Symbol) to valid(true)/invalid(false) def days_of_week_hash @days_of_week_hash ||= { :sunday => (days_of_week & SUNDAY ) > 0, :monday => (days_of_week & MONDAY ) > 0, :tuesday => (days_of_week & TUESDAY ) > 0, :wednesday => (days_of_week & WEDNESDAY ) > 0, :thursday => (days_of_week & THURSDAY ) > 0, :friday => (days_of_week & FRIDAY ) > 0, :saturday => (days_of_week & SATURDAY ) > 0 } end # Array beginning with Sunday of valid(true)/inactive(false) values def days_of_week_array dow = days_of_week_hash @days_of_week_array ||= [ dow[:sunday], dow[:monday], dow[:tuesday], dow[:wednesday], dow[:thursday], dow[:friday], dow[:saturday] ] end # Human-readable string of applicable days of week def days_of_week_string dow = days_of_week_hash @days_of_week_string ||= (dow[:sunday] ? "Su" : "") + (dow[:monday] ? "M" : "") + (dow[:tuesday] ? "Tu" : "") + (dow[:wednesday] ? "W" : "") + (dow[:thursday] ? "Th" : "") + (dow[:friday] ? "F" : "") + (dow[:saturday] ? "Sa" : "") end ## End days_of_week Helpers ## # Returns the next full occurrence of these operating time rule. # If we are currently within a valid time range, it will look forward for the # <em>next</em> opening time def next_times(at = Time.now) at = at.midnight unless at.respond_to? :offset return nil if length == 0 return nil if at.to_date > endDate # Schedules end at 23:59 of the stored endDate at = startDate.midnight if at < startDate # This schedule hasn't started yet, skip to startDate # Next occurrence is later today # This is the only time the "time" actually matters; # after today, all we care about is the date if days_of_week_array[at.wday] and start >= at.offset open = at.midnight + start close = open + length return [open,close] end # We don't care about the time offset anymore, jump to the next midnight at = at.midnight + 1.day # NOTE This also has the added benefit of preventing an infinite loop # from occurring if +at+ gets shifted by 0.days further down. # Shift days_of_weekArray so that +at+ is first element dow = days_of_week_array[at.wday..-1] + days_of_week_array[0..(at.wday-1)] # NOTE The above call does something a little quirky: # In the event that at.wday = 0, it concatenates the array with itself. # Since we are only interested in the first true value, this does not # cause a problem, but could probably be cleaned up if done so carefully. # Next day of the week this schedule is valid for (relative to current day) shift = dow.index(true) if shift # Skip forward at = at + shift.days else # Give up, there are no more occurrences # TODO Test edge case: valid for 1 day/week return nil end # Recurse to rerun the validation routines return next_times(at) end alias :to_times :next_times - def to_xml(options) + def to_xml(options = {}) #super(params.merge({:only => [:id, :place_id], :methods => [ {:times => :next_times}, :start, :length, :startDate, :endDate ]})) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] xml.tag!(self.class.to_s.underscore.dasherize) do xml.id(self.id) xml.place_id(self.place_id) #xml.place_name(self.place.name) #xml.place_location(self.place.location) #xml.place_phone(self.place.phone) xml.details(self.details) xml.tags do |xml| self.tag_list.each do |tag| xml.tag(tag) end end xml.start(self.start) xml.length(self.length) self.days_of_week_hash.to_xml(options.merge(:root => :days_of_week)) xml.startDate(self.startDate) xml.endDate(self.endDate) xml.override(self.override) open,close = self.next_times(Date.today) if open.nil? or close.nil? xml.tag!(:next_times.to_s.dasherize, :for => Date.today) else xml.tag!(:next_times.to_s.dasherize, :for => Date.today) do |xml| xml.open(open.xmlschema) xml.close(close.xmlschema) end end end end ##### TODO DEPRECATED METHODS ##### def at @at end def at=(time) @opensAt = nil @closesAt = nil @at = time end # Returns a Time object representing the beginning of this OperatingTime def opensAt @opensAt ||= relativeTime.openTime(at) end def closesAt @closesAt ||= relativeTime.closeTime(at) end # Sets the beginning of this OperatingTime # Input: params = { :hour => 12, :minute => 45 } def opensAt=(time) if time.class == Time @opensAt = relativeTime.openTime = time else super end end # Sets the end of this OperatingTime def closesAt=(time) @closesAt = relativeTime.closeTime = time end def start read_attribute(:opensAt) end def start=(offset) write_attribute(:opensAt,offset) end # Returns a RelativeTime object representing this OperatingTime def relativeTime @relativeTime ||= RelativeTime.new(self, :opensAt, :length) end; protected :relativeTime # Backwards compatibility with old database schema # TODO GET RID OF THIS!!! def flags ( (override ? 1 : 0) << 7) | read_attribute(:days_of_week) end # FIXME Deprecated, use +override+ instead def special override end # Input: isSpecial = true/false # FIXME Deprecated, use +override=+ instead def special=(isSpecial) if isSpecial == true or isSpecial == "true" or isSpecial == 1 self.override = true elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 self.override = false end end end
michaelansel/dukenow
2099559544725b60ac997b7b7e7dd51aa23fa377
daysOfWeek -> days_of_week ; "dasherize" all XML elements to be consistent with default ActiveRecord serializer
diff --git a/app/controllers/operating_times_controller.rb b/app/controllers/operating_times_controller.rb index 59266ea..4509e79 100644 --- a/app/controllers/operating_times_controller.rb +++ b/app/controllers/operating_times_controller.rb @@ -1,138 +1,138 @@ class OperatingTimesController < ApplicationController # GET /operating_times # GET /operating_times.xml def index if params[:place_id] @operating_times = OperatingTime.find(:all, :conditions => ['place_id = ?',params[:place_id]]) else @operating_times = OperatingTime.find(:all) end request.format = :html if request.format == :iphone respond_to do |format| format.html # index.html.erb format.xml { render :xml => @operating_times } end end # GET /operating_times/1 # GET /operating_times/1.xml def show @operating_time = OperatingTime.find(params[:id]) request.format = :html if request.format == :iphone respond_to do |format| format.html # show.html.erb format.xml { render :xml => @operating_time } end end # GET /operating_times/new # GET /operating_times/new.xml def new @operating_time = OperatingTime.new @places = Place.find(:all, :order => "name ASC") request.format = :html if request.format == :iphone respond_to do |format| format.html # new.html.erb format.xml { render :xml => @operating_time } end end # GET /operating_times/1/edit def edit @operating_time = OperatingTime.find(params[:id]) @places = Place.find(:all, :order => "name ASC") request.format = :html if request.format == :iphone end # POST /operating_times # POST /operating_times.xml def create params[:operating_time] = operatingTimesFormHandler(params[:operating_time]) @operating_time = OperatingTime.new(params[:operating_time]) request.format = :html if request.format == :iphone respond_to do |format| if @operating_time.save flash[:notice] = 'OperatingTime was successfully created.' format.html { redirect_to(@operating_time) } format.xml { render :xml => @operating_time, :status => :created, :location => @operating_time } else format.html { render :action => "new" } format.xml { render :xml => @operating_time.errors, :status => :unprocessable_entity } end end end # PUT /operating_times/1 # PUT /operating_times/1.xml def update @operating_time = OperatingTime.find(params[:id]) params[:operating_time] = operatingTimesFormHandler(params[:operating_time]) request.format = :html if request.format == :iphone respond_to do |format| if @operating_time.update_attributes(params[:operating_time]) flash[:notice] = 'OperatingTime was successfully updated.' format.html { redirect_to(@operating_time) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @operating_time.errors, :status => :unprocessable_entity } end end end # DELETE /operating_times/1 # DELETE /operating_times/1.xml def destroy @operating_time = OperatingTime.find(params[:id]) @operating_time.destroy request.format = :html if request.format == :iphone respond_to do |format| format.html { redirect_to(operating_times_url) } format.xml { head :ok } end end ## Helpers ## def operatingTimesFormHandler(operatingTimesParams={}) operatingTimesParams ||= {} =begin params[:regular_operating_time][:opensAtOffset] = params[:regular_operating_time].delete('opensAtHour') * 3600 + params[:regular_operating_time].delete('opensAtMinute') * 60 params[:regular_operating_time][:closesAtOffset] = params[:regular_operating_time].delete('closesAtHour') * 3600 + params[:regular_operating_time].delete('closesAtMinute') * 60 =end - if operatingTimesParams[:daysOfWeekHash] != nil - daysOfWeek = 0 + if operatingTimesParams[:days_of_week_hash] != nil + days_of_week = 0 - operatingTimesParams[:daysOfWeekHash].each do |dayOfWeek| - daysOfWeek += 1 << Date::DAYNAMES.index(dayOfWeek.capitalize) + operatingTimesParams[:days_of_week_hash].each do |days_of_week| + days_of_week += 1 << Date::DAYNAMES.index(days_of_week.capitalize) end - operatingTimesParams.delete('daysOfWeekHash') + operatingTimesParams.delete('days_of_week_hash') operatingTimesParams[:flags] = 0 if operatingTimesParams[:flags].nil? operatingTimesParams[:flags] = operatingTimesParams[:flags] & ~OperatingTime::ALLDAYS_FLAG - operatingTimesParams[:flags] = operatingTimesParams[:flags] | daysOfWeek + operatingTimesParams[:flags] = operatingTimesParams[:flags] | days_of_week end return operatingTimesParams end end diff --git a/app/models/dining_extension.rb b/app/models/dining_extension.rb index cd84cf6..4e0e0c7 100644 --- a/app/models/dining_extension.rb +++ b/app/models/dining_extension.rb @@ -1,15 +1,16 @@ class DiningExtension < ActiveRecord::Base belongs_to :place def to_xml(options = {}) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] - xml.dining_extension do |xml| - xml.logo_url(logo_url) - xml.more_info_url(more_info_url) - xml.owner_operator(owner_operator) - xml.payment_methods(payment_methods) + xml.tag!(self.class.to_s.underscore.dasherize) do |xml| + xml.tag!(:place_id.to_s.dasherize, place_id) unless options[:no_id] + xml.tag!(:logo_url.to_s.dasherize, logo_url) + xml.tag!(:more_info_url.to_s.dasherize, more_info_url) + xml.tag!(:owner_operator.to_s.dasherize, owner_operator) + xml.tag!(:payment_methods.to_s.dasherize, payment_methods) end end end diff --git a/app/models/operating_time.rb b/app/models/operating_time.rb index e45e977..2896551 100644 --- a/app/models/operating_time.rb +++ b/app/models/operating_time.rb @@ -1,277 +1,278 @@ class OperatingTime < ActiveRecord::Base belongs_to :place acts_as_taggable_on :operating_time_tags validates_presence_of :place_id, :endDate, :startDate validates_associated :place - validate :end_after_start, :daysOfWeek_valid + validate :end_after_start, :days_of_week_valid validate {|ot| 0 <= ot.length and ot.length <= 1.days } ## DaysOfWeek Constants ## SUNDAY = 0b00000001 MONDAY = 0b00000010 TUESDAY = 0b00000100 WEDNESDAY = 0b00001000 THURSDAY = 0b00010000 FRIDAY = 0b00100000 SATURDAY = 0b01000000 ALL_DAYS = (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) ## Validations ## def end_after_start if endDate < startDate errors.add_to_base("End date cannot preceed start date") end end - def daysOfWeek_valid - daysOfWeek == daysOfWeek & (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) + def days_of_week_valid + days_of_week == days_of_week & (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) end ## End Validations ## # TODO Is this OperatingTime applicable at +time+ def valid_at(time=Time.now) raise NotImplementedError end # Tag Helpers %w{tag_list tags tag_counts tag_ids tag_tagging_ids tag_taggings}.each do |m| [m,m+"="].each do |m| if self.instance_methods.include?("operating_time_"+m) self.class_eval "alias #{m.to_sym} #{"operating_time_#{m}".to_sym}" end end ; end def tags_from ; operating_time_tags_from ; end def override read_attribute(:override) == 1 end def override=(mode) if mode == true or mode == "true" or mode == 1 write_attribute(:override, true) elsif mode == false or mode == "false" or mode == 0 write_attribute(:override, false) else raise ArgumentError, "Invalid override value (#{mode.inspect}); Accepts true/false, 1/0" end end - def daysOfWeek=(newDow) + def days_of_week=(newDow) if not ( newDow & ALL_DAYS == newDow ) # Invalid input - raise ArgumentError, "Not a valid value for daysOfWeek (#{newDow.inspect})" + raise ArgumentError, "Not a valid value for days_of_week (#{newDow.inspect})" end - write_attribute(:daysOfWeek, newDow & ALL_DAYS) - @daysOfWeekHash = nil - @daysOfWeekArray = nil - @daysOfWeekString = nil + write_attribute(:days_of_week, newDow & ALL_DAYS) + @days_of_weekHash = nil + @days_of_weekArray = nil + @days_of_weekString = nil end - ## daysOfWeek Helper/Accessors ## + ## days_of_week Helpers ## # Hash mapping day of week (Symbol) to valid(true)/invalid(false) - def daysOfWeekHash - @daysOfWeekHash ||= { - :sunday => (daysOfWeek & SUNDAY ) > 0, - :monday => (daysOfWeek & MONDAY ) > 0, - :tuesday => (daysOfWeek & TUESDAY ) > 0, - :wednesday => (daysOfWeek & WEDNESDAY ) > 0, - :thursday => (daysOfWeek & THURSDAY ) > 0, - :friday => (daysOfWeek & FRIDAY ) > 0, - :saturday => (daysOfWeek & SATURDAY ) > 0 + def days_of_week_hash + @days_of_week_hash ||= { + :sunday => (days_of_week & SUNDAY ) > 0, + :monday => (days_of_week & MONDAY ) > 0, + :tuesday => (days_of_week & TUESDAY ) > 0, + :wednesday => (days_of_week & WEDNESDAY ) > 0, + :thursday => (days_of_week & THURSDAY ) > 0, + :friday => (days_of_week & FRIDAY ) > 0, + :saturday => (days_of_week & SATURDAY ) > 0 } end # Array beginning with Sunday of valid(true)/inactive(false) values - def daysOfWeekArray - dow = daysOfWeekHash + def days_of_week_array + dow = days_of_week_hash - @daysOfWeekArray ||= [ + @days_of_week_array ||= [ dow[:sunday], dow[:monday], dow[:tuesday], dow[:wednesday], dow[:thursday], dow[:friday], dow[:saturday] ] end # Human-readable string of applicable days of week - def daysOfWeekString - dow = daysOfWeekHash - - @daysOfWeekString ||= (dow[:sunday] ? "Su" : "") + - (dow[:monday] ? "M" : "") + - (dow[:tuesday] ? "Tu" : "") + - (dow[:wednesday] ? "W" : "") + - (dow[:thursday] ? "Th" : "") + - (dow[:friday] ? "F" : "") + - (dow[:saturday] ? "Sa" : "") + def days_of_week_string + dow = days_of_week_hash + + @days_of_week_string ||= + (dow[:sunday] ? "Su" : "") + + (dow[:monday] ? "M" : "") + + (dow[:tuesday] ? "Tu" : "") + + (dow[:wednesday] ? "W" : "") + + (dow[:thursday] ? "Th" : "") + + (dow[:friday] ? "F" : "") + + (dow[:saturday] ? "Sa" : "") end - ## End daysOfWeek Helper/Accessors ## + ## End days_of_week Helpers ## # Returns the next full occurrence of these operating time rule. # If we are currently within a valid time range, it will look forward for the # <em>next</em> opening time def next_times(at = Time.now) at = at.midnight unless at.respond_to? :offset return nil if length == 0 return nil if at.to_date > endDate # Schedules end at 23:59 of the stored endDate at = startDate.midnight if at < startDate # This schedule hasn't started yet, skip to startDate # Next occurrence is later today # This is the only time the "time" actually matters; # after today, all we care about is the date - if daysOfWeekArray[at.wday] and + if days_of_week_array[at.wday] and start >= at.offset open = at.midnight + start close = open + length return [open,close] end # We don't care about the time offset anymore, jump to the next midnight at = at.midnight + 1.day # NOTE This also has the added benefit of preventing an infinite loop # from occurring if +at+ gets shifted by 0.days further down. - # Shift daysOfWeekArray so that +at+ is first element - dow = daysOfWeekArray[at.wday..-1] + daysOfWeekArray[0..(at.wday-1)] + # Shift days_of_weekArray so that +at+ is first element + dow = days_of_week_array[at.wday..-1] + days_of_week_array[0..(at.wday-1)] # NOTE The above call does something a little quirky: # In the event that at.wday = 0, it concatenates the array with itself. # Since we are only interested in the first true value, this does not # cause a problem, but could probably be cleaned up if done so carefully. # Next day of the week this schedule is valid for (relative to current day) shift = dow.index(true) if shift # Skip forward at = at + shift.days else # Give up, there are no more occurrences # TODO Test edge case: valid for 1 day/week return nil end # Recurse to rerun the validation routines return next_times(at) end alias :to_times :next_times def to_xml(options) #super(params.merge({:only => [:id, :place_id], :methods => [ {:times => :next_times}, :start, :length, :startDate, :endDate ]})) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] - xml.tag!("operating-time".to_sym) do + xml.tag!(self.class.to_s.underscore.dasherize) do xml.id(self.id) xml.place_id(self.place_id) #xml.place_name(self.place.name) #xml.place_location(self.place.location) #xml.place_phone(self.place.phone) xml.details(self.details) xml.tags do |xml| self.tag_list.each do |tag| xml.tag(tag) end end xml.start(self.start) xml.length(self.length) - xml.daysOfWeek(self.daysOfWeek) + self.days_of_week_hash.to_xml(options.merge(:root => :days_of_week)) xml.startDate(self.startDate) xml.endDate(self.endDate) xml.override(self.override) open,close = self.next_times(Date.today) if open.nil? or close.nil? - xml.next_times(:for => Date.today) + xml.tag!(:next_times.to_s.dasherize, :for => Date.today) else - xml.next_times(:for => Date.today) do |xml| + xml.tag!(:next_times.to_s.dasherize, :for => Date.today) do |xml| xml.open(open.xmlschema) xml.close(close.xmlschema) end end end end ##### TODO DEPRECATED METHODS ##### def at @at end def at=(time) @opensAt = nil @closesAt = nil @at = time end # Returns a Time object representing the beginning of this OperatingTime def opensAt @opensAt ||= relativeTime.openTime(at) end def closesAt @closesAt ||= relativeTime.closeTime(at) end # Sets the beginning of this OperatingTime # Input: params = { :hour => 12, :minute => 45 } def opensAt=(time) if time.class == Time @opensAt = relativeTime.openTime = time else super end end # Sets the end of this OperatingTime def closesAt=(time) @closesAt = relativeTime.closeTime = time end def start read_attribute(:opensAt) end def start=(offset) write_attribute(:opensAt,offset) end # Returns a RelativeTime object representing this OperatingTime def relativeTime @relativeTime ||= RelativeTime.new(self, :opensAt, :length) end; protected :relativeTime # Backwards compatibility with old database schema # TODO GET RID OF THIS!!! def flags - ( (override ? 1 : 0) << 7) | read_attribute(:daysOfWeek) + ( (override ? 1 : 0) << 7) | read_attribute(:days_of_week) end # FIXME Deprecated, use +override+ instead def special override end # Input: isSpecial = true/false # FIXME Deprecated, use +override=+ instead def special=(isSpecial) if isSpecial == true or isSpecial == "true" or isSpecial == 1 self.override = true elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 self.override = false end end end diff --git a/app/models/place.rb b/app/models/place.rb index de99a15..4e609d2 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,214 +1,215 @@ class Place < ActiveRecord::Base DEBUG = false has_many :operating_times has_one :dining_extension acts_as_taggable_on :tags validates_presence_of :name def special_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 1}) end def regular_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 0}) end # Returns an array of Times representing the opening and closing times # of this Place between +startAt+ and +endAt+ def schedule(startAt,endAt) ## Caching ## @schedules ||= {} if @schedules[startAt.xmlschema] and @schedules[startAt.xmlschema][endAt.xmlschema] return @schedules[startAt.xmlschema][endAt.xmlschema] end ## End Caching ## # TODO Handle events starting within the range but ending outside of it? # TODO Offload this selection to the database; okay for testing though # Select all relevant times (1 day buffer on each end) # NOTE Make sure to use generous date comparisons to allow for midnight rollovers all_regular_operating_times = regular_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} all_special_operating_times = special_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} puts "\nRegular OperatingTimes: #{all_regular_operating_times.inspect}" if DEBUG puts "\nSpecial OperatingTimes: #{all_special_operating_times.inspect}" if DEBUG regular_times = [] special_times = [] special_ranges = [] all_special_operating_times.each do |ot| puts "\nSpecial Scheduling for: #{ot.inspect}" if DEBUG # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do if DEBUG puts "Open: #{open}" puts "Close: #{close}" puts "Start Date: #{ot.startDate} (#{ot.startDate.class})" puts "End Date: #{ot.endDate} (#{ot.endDate.class})" end if close < startAt # Skip forward to the first occurrance in our time range open,close = ot.next_times(close) next end special_times << [open,close] special_ranges << Range.new(ot.startDate,ot.endDate) open,close = ot.next_times(close) end end puts "\nSpecial Times: #{special_times.inspect}" if DEBUG puts "\nSpecial Ranges: #{special_ranges.inspect}" if DEBUG all_regular_operating_times.each do |ot| puts "\nRegular Scheduling for: #{ot.inspect}" if DEBUG # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do puts "Open: #{open}" if DEBUG puts "Close: #{close}" if DEBUG if close < startAt # Skip forward to the first occurrance in our time range open,close = ot.next_times(close) next end special_ranges.each do |sr| next if sr.member?(open) end # FIXME Causing an infinite loop; would be nice if this worked #open = startAt if open < startAt #close = endAt if close > endAt regular_times << [open,close] open,close = ot.next_times(close) end end puts "\nRegular Times: #{regular_times.inspect}" if DEBUG # TODO Handle schedule overrides # TODO Handle combinations (i.e. part special, part regular) final_schedule = (regular_times+special_times).sort{|a,b|a[0] <=> b[0]} ## Caching ## @schedules ||= {} @schedules[startAt.xmlschema] ||= {} @schedules[startAt.xmlschema][endAt.xmlschema] = final_schedule ## End Caching ## final_schedule end def daySchedule(at = Date.today) at = at.to_date if at.class == Time or at.class == DateTime day_schedule = schedule(at.midnight,(at+1).midnight) #schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } #schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end =end day_schedule.sort{|a,b|a[0] <=> b[0]} end def currentSchedule(at = Time.now) puts "At(cS): #{at}" if DEBUG daySchedule(at).select { |open,close| puts "Open(cS): #{open}" if DEBUG puts "Close(cS): #{close}" if DEBUG open <= at and at <= close }[0] end def open?(at = Time.now) a = currentSchedule(at) return a ? true : false end alias :open :open? def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end def to_xml(options = {}) #super(options.merge({:only => [:id, :name, :location, :phone], :methods => [ :open, :daySchedule ] })) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] + options[:skip_instruct] = true xml.place do xml.id(self.id) xml.name(self.name) xml.location(self.location) xml.building_id(self.building_id) xml.phone(self.phone) xml.tags do |xml| self.tag_list.each do |tag| xml.tag(tag) end end - self.dining_extension.to_xml(options.merge({:skip_instruct => true})) unless self.dining_extension.nil? + self.dining_extension.to_xml(options.merge({:no_id => true})) unless self.dining_extension.nil? xml.open(self.open?) if options[:schedule_from] and options[:schedule_to] sched = schedule(options[:schedule_from],options[:schedule_to]) sched_opts = {:from => options[:schedule_from], :to => options[:schedule_to] } elsif options[:schedule_for_date] sched = daySchedule(options[:schedule_for_date]) sched_opts = {:on => options[:schedule_for_date]} else sched = daySchedule(Date.today) sched_opts = {:on => Date.today} end if sched.nil? or sched.empty? xml.schedule(sched_opts) else xml.schedule(sched_opts) do |xml| sched.each do |open,close| xml.open(open.xmlschema) xml.close(close.xmlschema) end end end end end end diff --git a/db/migrate/20090707155143_revert_days_of_week_to_days_of_week.rb b/db/migrate/20090707155143_revert_days_of_week_to_days_of_week.rb new file mode 100644 index 0000000..df46e85 --- /dev/null +++ b/db/migrate/20090707155143_revert_days_of_week_to_days_of_week.rb @@ -0,0 +1,9 @@ +class RevertDaysOfWeekToDaysOfWeek < ActiveRecord::Migration + def self.up + rename_column "operating_times", "daysOfWeek", "days_of_week" + end + + def self.down + rename_column "operating_times", "days_of_week", "daysOfWeek" + end +end diff --git a/db/schema.rb b/db/schema.rb index 586332b..73717ca 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,98 +1,108 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20090706175956) do +ActiveRecord::Schema.define(:version => 20090707155143) do + + create_table "dining_extensions", :force => true do |t| + t.integer "place_id" + t.string "logo_url" + t.string "more_info_url" + t.string "owner_operator" + t.string "payment_methods" + t.datetime "created_at" + t.datetime "updated_at" + end create_table "eateries", :force => true do |t| t.string "name" t.string "location" t.string "phone" t.datetime "created_at" t.datetime "updated_at" end create_table "operating_time_taggings", :force => true do |t| t.integer "tag_id" t.integer "taggable_id" t.integer "tagger_id" t.string "tagger_type" t.string "taggable_type" t.string "context" t.datetime "created_at" end add_index "operating_time_taggings", ["tag_id"], :name => "index_operating_time_taggings_on_tag_id" add_index "operating_time_taggings", ["taggable_id", "taggable_type", "context"], :name => "index_operating_time_taggings_on_taggable_id_and_taggable_type_and_context" create_table "operating_time_tags", :force => true do |t| t.string "name" end create_table "operating_times", :force => true do |t| t.integer "place_id" t.integer "opensAt" t.integer "length" t.text "details" t.date "startDate" t.date "endDate" t.datetime "created_at" t.datetime "updated_at" - t.integer "override", :default => 0, :null => false - t.integer "daysOfWeek", :default => 0, :null => false + t.integer "override", :default => 0, :null => false + t.integer "days_of_week", :default => 0, :null => false end create_table "places", :force => true do |t| t.string "name" t.string "location" t.string "phone" t.datetime "created_at" t.datetime "updated_at" t.integer "building_id" end create_table "regular_operating_times", :force => true do |t| t.integer "eatery_id" t.integer "opensAt" t.integer "closesAt" t.integer "daysOfWeek" t.datetime "created_at" t.datetime "updated_at" end create_table "special_operating_times", :force => true do |t| t.integer "eatery_id" t.integer "opensAt" t.integer "closesAt" t.integer "daysOfWeek" t.date "start" t.date "end" t.datetime "created_at" t.datetime "updated_at" end create_table "taggings", :force => true do |t| t.integer "tag_id" t.integer "taggable_id" t.integer "tagger_id" t.string "tagger_type" t.string "taggable_type" t.string "context" t.datetime "created_at" end add_index "taggings", ["tag_id"], :name => "index_taggings_on_tag_id" add_index "taggings", ["taggable_id", "taggable_type", "context"], :name => "index_taggings_on_taggable_id_and_taggable_type_and_context" create_table "tags", :force => true do |t| t.string "name" end end diff --git a/spec/models/operating_time_spec.rb b/spec/models/operating_time_spec.rb index 6ce4834..b39400f 100644 --- a/spec/models/operating_time_spec.rb +++ b/spec/models/operating_time_spec.rb @@ -1,209 +1,209 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe OperatingTime do before(:each) do @place = mock_model(Place) @valid_attributes = { - :place_id => @place.id, - :start => (Time.now - 1.hours).to_i, - :length => 2.hours, - :daysOfWeek => OperatingTime::ALL_DAYS, - :startDate => Date.yesterday, - :endDate => Date.tomorrow, - :override => false + :place_id => @place.id, + :start => (Time.now - 1.hours).to_i, + :length => 2.hours, + :days_of_week => OperatingTime::ALL_DAYS, + :startDate => Date.yesterday, + :endDate => Date.tomorrow, + :override => false } @operating_time = OperatingTime.create!(@valid_attributes) end it "should create a new instance given all valid attributes" do OperatingTime.create!(@valid_attributes) end describe "missing required attributes" do it "should not create a new instance without a valid start time" it "should not create a new instance without a valid length" it "should not create a new instance without a valid Place reference" it "should not create a new instance without a valid start date" it "should not create a new instance without a valid end date" end describe "missing default-able attributes" do - it "should default daysOfWeek to 0" do - @valid_attributes.delete(:daysOfWeek) if @valid_attributes[:daysOfWeek] - OperatingTime.create!(@valid_attributes).daysOfWeek.should == 0 + it "should default days_of_week to 0" do + @valid_attributes.delete(:days_of_week) if @valid_attributes[:days_of_week] + OperatingTime.create!(@valid_attributes).days_of_week.should == 0 end it "should default override to false" do @valid_attributes.delete(:override) if @valid_attributes[:override] OperatingTime.create!(@valid_attributes).override.should == false end end describe "given invalid attributes" do def create @operating_time = OperatingTime.create!(@valid_attributes) end =begin it "should create a new instance, but ignore an invalid override value" do @valid_attributes[:override] = "invalid" create @operating_time.override.should == false # where false is the default value @valid_attributes[:override] = 10 create @operating_time.override.should == false # where false is the default value end - it "should create a new instance, but ignore an invalid daysOfWeek value" do - @valid_attributes[:daysOfWeek] = 1000 + it "should create a new instance, but ignore an invalid days_of_week value" do + @valid_attributes[:days_of_week] = 1000 create - @operating_time.daysOfWeek.should == 0 # where 0 is the default value + @operating_time.days_of_week.should == 0 # where 0 is the default value end =end it "should not create a new instance with an invalid start time" it "should not create a new instance with an invalid length" it "should not create a new instance with an invalid Place reference" it "should not create a new instance with an invalid start date" it "should not create a new instance with an invalid end date" end it "should enable override mode" do @operating_time.should_receive(:write_attribute).with(:override, true).exactly(3).times @operating_time.override = true @operating_time.override = "true" @operating_time.override = 1 end it "should disable override mode" do @operating_time.should_receive(:write_attribute).with(:override, false).exactly(3).times @operating_time.override = false @operating_time.override = "false" @operating_time.override = 0 end it "should complain about invalid override values, but not change the value" do @operating_time.override = true @operating_time.override.should == true #TODO Should nil be ignored or errored? lambda { @operating_time.override = nil }.should raise_error(ArgumentError) @operating_time.override.should == true lambda { @operating_time.override = "invalid" }.should raise_error(ArgumentError) @operating_time.override.should == true lambda { @operating_time.override = false }.should_not raise_error @operating_time.override.should == false end - it "should complain about invalid daysOfWeek values, but not change the value" do - @operating_time.daysOfWeek = OperatingTime::SUNDAY - @operating_time.daysOfWeek.should == OperatingTime::SUNDAY + it "should complain about invalid days_of_week values, but not change the value" do + @operating_time.days_of_week = OperatingTime::SUNDAY + @operating_time.days_of_week.should == OperatingTime::SUNDAY #TODO Should nil be ignored or errored? - lambda { @operating_time.daysOfWeek = nil }.should raise_error(ArgumentError) - @operating_time.daysOfWeek.should == OperatingTime::SUNDAY + lambda { @operating_time.days_of_week = nil }.should raise_error(ArgumentError) + @operating_time.days_of_week.should == OperatingTime::SUNDAY - lambda { @operating_time.daysOfWeek = 200 }.should raise_error(ArgumentError) - @operating_time.daysOfWeek.should == OperatingTime::SUNDAY + lambda { @operating_time.days_of_week = 200 }.should raise_error(ArgumentError) + @operating_time.days_of_week.should == OperatingTime::SUNDAY - lambda { @operating_time.daysOfWeek= OperatingTime::MONDAY }.should_not raise_error - @operating_time.daysOfWeek.should == OperatingTime::MONDAY + lambda { @operating_time.days_of_week= OperatingTime::MONDAY }.should_not raise_error + @operating_time.days_of_week.should == OperatingTime::MONDAY end describe "with open and close times" do before(:each) do @now = Time.now.midnight + 15.minutes @open = @now.midnight + 23.hours + 30.minutes @close = @open + 1.hour start = @open - @open.midnight length = @close - @open @valid_attributes.update({ :start => start, :length => length }) @operating_time = OperatingTime.create!(@valid_attributes) end it "should return valid open and close times for 'now'" do Time.stub(:now).and_return(@now) open,close = @operating_time.next_times() open.to_s.should == @open.to_s close.to_s.should == @close.to_s end it "should return valid open and close times for a given time" do @open, @close, @now = [@open,@close,@now].collect{|t| t + 5.days} @operating_time.endDate += 5 open,close = @operating_time.next_times( @now ) open.to_s.should == @open.to_s close.to_s.should == @close.to_s end it "should return valid open/close times if open past midnight, but ending today" do @operating_time.endDate = @now.to_date open = @now.midnight + @operating_time.start close = open + @operating_time.length open,close = @operating_time.next_times(@now) close.should > (@now.to_date + 1).midnight open.to_s.should == @open.to_s close.to_s.should == @close.to_s end it "should return valid open/close times if open one day per week" do @operating_time.endDate = @now.to_date + 21 open = @now.midnight - pending("Look at next_times daysOfWeek array shifting") + pending("Look at next_times days_of_week array shifting") end end end ### Midnight Module Specs ### describe Date do before(:each) do @date = Date.today end it "should have a valid midnight" do @date.should respond_to(:midnight) @date.midnight.should == Time.mktime(@date.year, @date.month, @date.day, 0, 0, 0) end end describe Time do before(:each) do @time = Time.now end it "should have a valid midnight" do @time.should respond_to(:midnight) @time.midnight.should == Time.mktime(@time.year, @time.month, @time.day, 0, 0, 0) end it "should have a valid midnight offset" do @time.should respond_to(:offset) @time.offset.should == @time.hour.hours + @time.min.minutes + @time.sec end end describe DateTime do before(:each) do @dt = DateTime.now end it "should have a valid midnight" do @dt.should respond_to(:midnight) @dt.midnight.should == Time.mktime(@dt.year, @dt.month, @dt.day, 0, 0, 0) end end ### End Midnight Module Specs ### diff --git a/spec/models/schedules.rb b/spec/models/schedules.rb index dfed43d..fb2cd8f 100644 --- a/spec/models/schedules.rb +++ b/spec/models/schedules.rb @@ -1,380 +1,380 @@ ###################### ##### Scheduling ##### ###################### describe "a Place with scheduling capabilities", :shared => true do before(:each) do add_scheduling_spec_helpers(@place) end validate_setup do before(:each) do @place.build end end it "should be clean" do @place.regular_operating_times.should == [] @place.special_operating_times.should == [] @place.constraints.should == [] @place.times.should == [] end in_order_to "be open now" do before(:each) do @place.add_times([ {:start => 6.hours, :length => 2.hours, :override => false}, {:start => 6.hours, :length => 2.hours, :override => true} ]) @at = (@at || Time.now).midnight + 7.hours end it "should have operating times" do @place.build(@at) @place.operating_times.should_not be_empty end it "should have a schedule" do @place.build(@at) @place.schedule(@at.midnight, @at.midnight + 1.day).should_not be_empty end it "should have a daySchedule" do @place.build(@at) @place.daySchedule(@at).should_not be_empty end it "should have a currentSchedule" do @place.build(@at) @place.currentSchedule(@at).should_not be_nil end it "should be open on Sunday" do @at = @at - @at.wday.days # Set to previous Sunday @place.rebuild @place.open(@at).should == true end it "should be open on Wednesday" do @at = @at - @at.wday.days + 3.days # Set to Wednesday after last Sunday @place.rebuild(@at) begin @place.open(@at).should == true rescue Exception => e puts "" puts "At: #{@at}" puts "Times: #{@place.times.inspect}" puts "OperatingTimes: #{@place.operating_times.inspect}" puts "daySchedule: #{@place.daySchedule(@at)}" raise e end end it "should be open on Saturday" do @at = @at - @at.wday.days + 6.days# Set to Saturday after last Sunday @place.rebuild(@at) @place.open(@at).should == true end it "should be open on only one day every week" do @at = @at - @at.wday.days + 6.days# Set to Saturday after last Sunday @place.times.each do |t| - t[:daysOfWeek] = OperatingTime::SATURDAY + t[:days_of_week] = OperatingTime::SATURDAY t[:startDate] = @at.to_date - 2.days t[:endDate] = @at.to_date + 3.weeks end @place.rebuild(@at) @place.schedule(@at-1.day, @at+15.days).should have(3).times @place.schedule(@at-1.day, @at+15.days).collect{|a,b|[a.xmlschema,b.xmlschema]}.uniq.should have(3).unique_times end end in_order_to "be open 24 hours" do before(:each) do @place.add_times([ {:start => 0, :length => 24.hours, :override => false}, {:start => 0, :length => 24.hours, :override => true} ]) @at = (@at || Time.now).midnight + 12.hours @place.build(@at) end it "should be open during the day" do @place.open(@at).should == true end it "should be open at midnight" do @place.open(@at.midnight).should == true end end in_order_to "be open later in the day" do before(:each) do @place.add_times([ {:start => 16.hours, :length => 2.hours, :override => false}, {:start => 16.hours, :length => 2.hours, :override => true} ]) @at = (@at || Time.now).midnight + 12.hours @place.build(@at) end it "should be closed now" do @place.open(@at).should == false end it "should have a schedule later in the day" do @place.schedule(@at,@at.midnight + 24.hours).should_not be_empty end it "should not have a schedule earlier in the day" do @place.schedule(@at.midnight,@at).should be_empty end end in_order_to "be closed for the day" do before(:each) do @place.add_times([ {:start => 4.hours, :length => 2.hours, :override => false}, {:start => 4.hours, :length => 2.hours, :override => true} ]) @at = (@at || Time.now).midnight + 12.hours @place.build(@at) end it "should be closed now" do @place.open(@at).should == false end it "should have a schedule earlier in the day" do @place.schedule(@at.midnight,@at).should_not be_empty end it "should not have a schedule later in the day" do @place.schedule(@at, @at.midnight + 24.hours).should be_empty end end in_order_to "be open past midnight" do before(:each) do @at = (@at || Time.now).midnight + 12.hours @place.add_times([ {:start => 23.hours, :length => 4.hours, :override => true}, {:start => 23.hours, :length => 4.hours, :override => false} ]) @place.times.each do |t| t[:startDate] = @at.to_date t[:endDate] = @at.to_date end @place.build(@at) end it "should be open early the next morning" do @place.open(@at.midnight + 1.days + 2.hours).should == true end it "should not be open early that morning" do @place.open(@at.midnight + 2.hours).should == false end it "should not be open late the next night" do @place.open(@at.midnight + 2.days + 2.hours).should == false end end in_order_to "be closed now" do before(:each) do @place.add_constraint {|t| ( t[:start] > @at.offset ) or ( (t[:start] + t[:length]) < @at.offset ) } @place.add_times([ {:start => 6.hours, :length => 2.hours, :override => false}, {:start => 6.hours, :length => 2.hours, :override => true} ]) @at = Time.now.midnight + 12.hours @place.build end it "should be closed" do @place.open(@at).should == false end end in_order_to "be closed all day" do before(:each) do @at ||= Time.now @place.add_times([ {:start => 0, :length => 0, :startDate => @at.to_date, :endDate => @at.to_date, :override => false}, {:start => 0, :length => 0, :startDate => @at.to_date, :endDate => @at.to_date, :override => true} ]) @place.build(@at) end it "should be closed now" do @place.open(@at).should == false end it "should not have a schedule earlier in the day" do @place.schedule(@at.midnight,@at).should be_empty end it "should not have a schedule later in the day" do @place.schedule(@at, @at.midnight + 24.hours).should be_empty end it "should not have a schedule at all for the day" do @place.daySchedule(@at).should be_empty end end in_order_to "have a valid schedule" do it "should not have any overlapping times" it "should have all times within the specified time range" end end describe "a Place with valid times", :shared => true do describe "with only regular times" do before(:each) do @place.add_constraint {|t| t[:override] == false } @place.build end validate_setup do it "should have regular times" do #puts "Regular Times: #{@place.regular_operating_times.inspect}" @place.regular_operating_times.should_not be_empty end it "should not have any special times" do #puts "Special Times: #{@place.special_operating_times.inspect}" @place.special_operating_times.should be_empty end end it_can "be open now" it_can "be open 24 hours" it_can "be open past midnight" it_can "be open later in the day" it_can "be closed for the day" it_can "be closed now" it_can "be closed all day" end describe "with only special times" do before(:each) do @place.add_constraint {|t| t[:override] == true } @place.build end validate_setup do it "should not have regular times" do @place.regular_operating_times.should be_empty end it "should have special times" do @place.special_operating_times.should_not be_empty end end it_can "be open now" it_can "be open 24 hours" it_can "be open past midnight" it_can "be open later in the day" it_can "be closed for the day" it_can "be closed now" it_can "be closed all day" end describe "with regular and special times" do validate_setup do it "should have regular times" do @place.regular_operating_times.should_not be_empty end it "should have special times" do @place.special_operating_times.should_not be_empty end end describe "where the special times are overriding the regular times" do #it_can "be open now" #it_can "be open 24 hours" #it_can "be open past midnight" #it_can "be open later in the day" #it_can "be closed for the day" #it_can "be closed now" #it_can "be closed all day" end describe "where the special times are not overriding the regular times" do #it_can "be open now" #it_can "be open 24 hours" #it_can "be open past midnight" #it_can "be open later in the day" #it_can "be closed for the day" #it_can "be closed now" #it_can "be closed all day" end end describe "with special times" do describe "extending normal hours" do #it_can "be open now" #it_can "be open 24 hours" #it_can "be open past midnight" #it_can "be open later in the day" #it_can "be closed for the day" #it_can "be closed now" #it_can "be closed all day" end describe "reducing normal hours" do #it_can "be open now" #it_can "be open 24 hours" #it_can "be open past midnight" #it_can "be open later in the day" #it_can "be closed for the day" #it_can "be closed now" #it_can "be closed all day" end describe "removing all hours" do #it_can "be open now" #it_can "be open 24 hours" #it_can "be open past midnight" #it_can "be open later in the day" #it_can "be closed for the day" #it_can "be closed now" #it_can "be closed all day" end describe "moving normal hours (extending and reducing)" do #it_can "be open now" #it_can "be open 24 hours" #it_can "be open past midnight" #it_can "be open later in the day" #it_can "be closed for the day" #it_can "be closed now" #it_can "be closed all day" end end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 91a318e..f168177 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,172 +1,172 @@ # This file is copied to ~/spec when you run 'ruby script/generate rspec' # from the project root directory. ENV["RAILS_ENV"] ||= 'test' require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT) require 'spec/autorun' require 'spec/rails' require 'spec/capabilities' Spec::Runner.configure do |config| # If you're not using ActiveRecord you should remove these # lines, delete config/database.yml and disable :active_record # in your config/boot.rb config.use_transactional_fixtures = true config.use_instantiated_fixtures = false config.fixture_path = RAILS_ROOT + '/spec/fixtures/' # == Fixtures # # You can declare fixtures for each example_group like this: # describe "...." do # fixtures :table_a, :table_b # # Alternatively, if you prefer to declare them only once, you can # do so right here. Just uncomment the next line and replace the fixture # names with your fixtures. # # config.global_fixtures = :table_a, :table_b # # If you declare global fixtures, be aware that they will be declared # for all of your examples, even those that don't use them. # # You can also declare which fixtures to use (for example fixtures for test/fixtures): # # config.fixture_path = RAILS_ROOT + '/spec/fixtures/' # # == Mock Framework # # RSpec uses it's own mocking framework by default. If you prefer to # use mocha, flexmock or RR, uncomment the appropriate line: # # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr # # == Notes # # For more information take a look at Spec::Runner::Configuration and Spec::Runner end ConstraintDebugging = false def add_scheduling_spec_helpers(place) place.instance_eval do def operating_times regular_operating_times + special_operating_times end def regular_operating_times @regular_operating_times ||= [] end def special_operating_times @special_operating_times ||= [] end def constraints @constraints ||= [] end def times @times ||= [] end def add_constraint(&block) puts "Adding constraint: #{block.to_s.sub(/^[^\@]*\@/,'')[0..-2]}" if ConstraintDebugging self.constraints << block end # Test +time+ against all constraints for +place+ def acceptable_time(time) if ConstraintDebugging puts "Testing Time: #{time.inspect}" end matched_all = true self.constraints.each do |c| matched = c.call(time) if ConstraintDebugging if matched puts "++ Time accepted by constraint" else puts "-- Time rejected by constraint" end puts " Constraint: #{c.to_s.sub(/^[^\@]*\@/,'')[0..-2]}" end matched_all &= matched end if ConstraintDebugging if matched_all puts "++ Time Accepted" else puts "-- Time Rejected" end puts "" end matched_all end def add_times(new_times = []) new_times.each do |t| unless t[:start] and t[:length] raise ArgumentError, "Must specify a valid start offset and length" end end times.concat(new_times) end def build(at = Time.now) if ConstraintDebugging puts "Rebuilding #{self}" puts "Constraints:" constraints.each do |c| puts " #{c.to_s.sub(/^[^\@]*\@/,'')[0..-2]}" end puts "Times:" times.each do |t| puts " #{t.inspect}" end end regular_operating_times.clear special_operating_times.clear operating_times.clear self.times.each do |t| t=t.dup if acceptable_time(t) - t[:override] ||= false - t[:startDate] ||= at.to_date - 2 - t[:endDate] ||= at.to_date + 2 - t[:daysOfWeek] ||= OperatingTime::ALL_DAYS - t[:place_id] ||= self.id + t[:override] ||= false + t[:startDate] ||= at.to_date - 2 + t[:endDate] ||= at.to_date + 2 + t[:days_of_week] ||= OperatingTime::ALL_DAYS + t[:place_id] ||= self.id ot = OperatingTime.new t.each{|k,v| ot.send(k.to_s+'=',v)} puts "Added time: #{ot.inspect}" if ConstraintDebugging if t[:override] self.special_operating_times << ot else self.regular_operating_times << ot end end end if ConstraintDebugging puts "Regular Times: #{self.regular_operating_times.inspect}" puts "Special Times: #{self.special_operating_times.inspect}" end self end alias :build! :build alias :rebuild :build alias :rebuild! :build end end # add_scheduling_spec_helpers(place)
michaelansel/dukenow
f3dff0f5fdb93109cda99f9a0efa93f5cd42834d
XML bugfix and new parameter alias for Places controller (:on => :schedule_for_date)
diff --git a/app/controllers/places_controller.rb b/app/controllers/places_controller.rb index 50776a4..ebd4ae6 100644 --- a/app/controllers/places_controller.rb +++ b/app/controllers/places_controller.rb @@ -1,192 +1,192 @@ class PlacesController < ApplicationController ActionView::Base.send :include, TagsHelper before_filter :map_params, :parse_dates_and_times, :filter_xml_params def get_at_date params[:at] = Date.today.to_s if params[:at].nil? @at = Date.parse(params[:at]) end def map_params - map = {:from => :schedule_from, :to => :schedule_to, :at => :schedule_for_date} + map = {:from => :schedule_from, :to => :schedule_to, :on => :schedule_for_date, :at => :schedule_for_date} params.each{|k,v| params[map[k.to_sym]] = v if map.has_key?(k.to_sym) } end def parse_dates_and_times times = [:schedule_from, :schedule_to, :schedule_for_date] params[:schedule_from] = Time.parse(params[:schedule_from]) if params[:schedule_from] params[:schedule_to] = Time.parse(params[:schedule_to]) if params[:schedule_to] params[:schedule_for_date] = Date.parse(params[:schedule_for_date]) if params[:schedule_for_date] end def filter_xml_params safe = [:schedule_from, :schedule_to, :schedule_for_date] @xml_params ||= {} params.each{|k,v| @xml_params[k.to_sym] = v if safe.include?(k.to_sym) } RAILS_DEFAULT_LOGGER.info "XML Params: #{@xml_params.inspect}" end # GET /places # GET /places.xml def index @places = Place.find(:all, :order => "name ASC") if params[:tags] @selected_tags = params[:tags].split(/[,+ ][ ]*/) else @selected_tags = [] end # Restrict to specific tags @selected_tags.each do |tag| RAILS_DEFAULT_LOGGER.debug "Restricting by tag: #{tag}" @places = @places & Place.tagged_with(tag, :on => :tags) end # Don't display machineAdded Places on the main listing @places = @places - Place.tagged_with("machineAdded", :on => :tags) unless @selected_tags.include?("machineAdded") # Calculate tag count for all Places with Tags #@tags = Place.tag_counts_on(:tags, :at_least => 1) # Manually calculate tag counts for only displayed places tags = [] @places.each do |place| tags = tags + place.tag_list end # Remove already selected tags tags = tags - @selected_tags # Count tags and make a set of [name,count] pairs @tag_counts = tags.uniq.collect {|tag| [tag,tags.select{|a|a == tag}.size] } # Filter out single tags @tag_counts = @tag_counts.select{|name,count| count > 1} # Make the count arrays act like tags for the tag cloud @tag_counts.each do |a| a.instance_eval <<-RUBY def count self[1] end def name self[0] end RUBY end respond_to do |format| format.html # index.html.erb format.iphone # index.iphone.erb format.json { render :json => @places } format.xml { render :xml => @places.to_xml(@xml_params) } end end def tag redirect_to :action => :index, :tags => params.delete(:id) end # GET /places/1 # GET /places/1.xml def show @place = Place.find(params[:id]) request.format = :html if request.format == :iphone respond_to do |format| format.html # show.html.erb format.xml { render :xml => @place.to_xml(@xml_params) } end end # GET /places/new # GET /places/new.xml def new @place = Place.new request.format = :html if request.format == :iphone respond_to do |format| format.html # new.html.erb format.xml { render :xml => @place } end end # GET /places/1/edit def edit @place = Place.find(params[:id]) request.format = :html if request.format == :iphone end # POST /places # POST /places.xml def create if params[:place] and params[:place][:tag_list] params[:place][:tag_list].strip! params[:place][:tag_list].gsub!(/( )+/,', ') end @place = Place.new(params[:place]) request.format = :html if request.format == :iphone respond_to do |format| if @place.save flash[:notice] = 'Place was successfully created.' format.html { redirect_to(@place) } format.xml { render :xml => @place, :status => :created, :location => @place } else format.html { render :action => "new" } format.xml { render :xml => @place.errors, :status => :unprocessable_entity } end end end # PUT /places/1 # PUT /places/1.xml def update @place = Place.find(params[:id]) if params[:place] and params[:place][:tag_list] params[:place][:tag_list].strip! params[:place][:tag_list].gsub!(/( )+/,', ') end request.format = :html if request.format == :iphone respond_to do |format| if @place.update_attributes(params[:place]) flash[:notice] = 'Place was successfully updated.' format.html { redirect_to(@place) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @place.errors, :status => :unprocessable_entity } end end end # DELETE /places/1 # DELETE /places/1.xml def destroy @place = Place.find(params[:id]) @place.destroy request.format = :html if request.format == :iphone respond_to do |format| format.html { redirect_to(places_url) } format.xml { head :ok } end end # GET /places/open # GET /places/open.xml def open @place = Place.find(params[:id]) request.format = :html if request.format == :iphone respond_to do |format| format.html # open.html.erb format.xml { render :xml => @place } end end end diff --git a/app/models/place.rb b/app/models/place.rb index fc55592..de99a15 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,214 +1,214 @@ class Place < ActiveRecord::Base DEBUG = false has_many :operating_times has_one :dining_extension acts_as_taggable_on :tags validates_presence_of :name def special_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 1}) end def regular_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 0}) end # Returns an array of Times representing the opening and closing times # of this Place between +startAt+ and +endAt+ def schedule(startAt,endAt) ## Caching ## @schedules ||= {} if @schedules[startAt.xmlschema] and @schedules[startAt.xmlschema][endAt.xmlschema] return @schedules[startAt.xmlschema][endAt.xmlschema] end ## End Caching ## # TODO Handle events starting within the range but ending outside of it? # TODO Offload this selection to the database; okay for testing though # Select all relevant times (1 day buffer on each end) # NOTE Make sure to use generous date comparisons to allow for midnight rollovers all_regular_operating_times = regular_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} all_special_operating_times = special_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} puts "\nRegular OperatingTimes: #{all_regular_operating_times.inspect}" if DEBUG puts "\nSpecial OperatingTimes: #{all_special_operating_times.inspect}" if DEBUG regular_times = [] special_times = [] special_ranges = [] all_special_operating_times.each do |ot| puts "\nSpecial Scheduling for: #{ot.inspect}" if DEBUG # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do if DEBUG puts "Open: #{open}" puts "Close: #{close}" puts "Start Date: #{ot.startDate} (#{ot.startDate.class})" puts "End Date: #{ot.endDate} (#{ot.endDate.class})" end if close < startAt # Skip forward to the first occurrance in our time range open,close = ot.next_times(close) next end special_times << [open,close] special_ranges << Range.new(ot.startDate,ot.endDate) open,close = ot.next_times(close) end end puts "\nSpecial Times: #{special_times.inspect}" if DEBUG puts "\nSpecial Ranges: #{special_ranges.inspect}" if DEBUG all_regular_operating_times.each do |ot| puts "\nRegular Scheduling for: #{ot.inspect}" if DEBUG # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do puts "Open: #{open}" if DEBUG puts "Close: #{close}" if DEBUG if close < startAt # Skip forward to the first occurrance in our time range open,close = ot.next_times(close) next end special_ranges.each do |sr| next if sr.member?(open) end # FIXME Causing an infinite loop; would be nice if this worked #open = startAt if open < startAt #close = endAt if close > endAt regular_times << [open,close] open,close = ot.next_times(close) end end puts "\nRegular Times: #{regular_times.inspect}" if DEBUG # TODO Handle schedule overrides # TODO Handle combinations (i.e. part special, part regular) final_schedule = (regular_times+special_times).sort{|a,b|a[0] <=> b[0]} ## Caching ## @schedules ||= {} @schedules[startAt.xmlschema] ||= {} @schedules[startAt.xmlschema][endAt.xmlschema] = final_schedule ## End Caching ## final_schedule end def daySchedule(at = Date.today) at = at.to_date if at.class == Time or at.class == DateTime day_schedule = schedule(at.midnight,(at+1).midnight) #schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } #schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end =end day_schedule.sort{|a,b|a[0] <=> b[0]} end def currentSchedule(at = Time.now) puts "At(cS): #{at}" if DEBUG daySchedule(at).select { |open,close| puts "Open(cS): #{open}" if DEBUG puts "Close(cS): #{close}" if DEBUG open <= at and at <= close }[0] end def open?(at = Time.now) a = currentSchedule(at) return a ? true : false end alias :open :open? def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end def to_xml(options = {}) #super(options.merge({:only => [:id, :name, :location, :phone], :methods => [ :open, :daySchedule ] })) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] xml.place do xml.id(self.id) xml.name(self.name) xml.location(self.location) xml.building_id(self.building_id) xml.phone(self.phone) xml.tags do |xml| self.tag_list.each do |tag| xml.tag(tag) end end - self.dining_extension.to_xml(options) unless self.dining_extension.nil? + self.dining_extension.to_xml(options.merge({:skip_instruct => true})) unless self.dining_extension.nil? xml.open(self.open?) if options[:schedule_from] and options[:schedule_to] sched = schedule(options[:schedule_from],options[:schedule_to]) sched_opts = {:from => options[:schedule_from], :to => options[:schedule_to] } elsif options[:schedule_for_date] sched = daySchedule(options[:schedule_for_date]) sched_opts = {:on => options[:schedule_for_date]} else sched = daySchedule(Date.today) sched_opts = {:on => Date.today} end if sched.nil? or sched.empty? xml.schedule(sched_opts) else xml.schedule(sched_opts) do |xml| sched.each do |open,close| xml.open(open.xmlschema) xml.close(close.xmlschema) end end end end end end
michaelansel/dukenow
9b037651453ae6f93713fd6a9509f3681ddb4f31
Pass scheduling params to XML builder for Place.show
diff --git a/app/controllers/places_controller.rb b/app/controllers/places_controller.rb index 2272269..50776a4 100644 --- a/app/controllers/places_controller.rb +++ b/app/controllers/places_controller.rb @@ -1,192 +1,192 @@ class PlacesController < ApplicationController ActionView::Base.send :include, TagsHelper before_filter :map_params, :parse_dates_and_times, :filter_xml_params def get_at_date params[:at] = Date.today.to_s if params[:at].nil? @at = Date.parse(params[:at]) end def map_params map = {:from => :schedule_from, :to => :schedule_to, :at => :schedule_for_date} params.each{|k,v| params[map[k.to_sym]] = v if map.has_key?(k.to_sym) } end def parse_dates_and_times times = [:schedule_from, :schedule_to, :schedule_for_date] params[:schedule_from] = Time.parse(params[:schedule_from]) if params[:schedule_from] params[:schedule_to] = Time.parse(params[:schedule_to]) if params[:schedule_to] params[:schedule_for_date] = Date.parse(params[:schedule_for_date]) if params[:schedule_for_date] end def filter_xml_params safe = [:schedule_from, :schedule_to, :schedule_for_date] @xml_params ||= {} params.each{|k,v| @xml_params[k.to_sym] = v if safe.include?(k.to_sym) } RAILS_DEFAULT_LOGGER.info "XML Params: #{@xml_params.inspect}" end # GET /places # GET /places.xml def index @places = Place.find(:all, :order => "name ASC") if params[:tags] @selected_tags = params[:tags].split(/[,+ ][ ]*/) else @selected_tags = [] end # Restrict to specific tags @selected_tags.each do |tag| RAILS_DEFAULT_LOGGER.debug "Restricting by tag: #{tag}" @places = @places & Place.tagged_with(tag, :on => :tags) end # Don't display machineAdded Places on the main listing @places = @places - Place.tagged_with("machineAdded", :on => :tags) unless @selected_tags.include?("machineAdded") # Calculate tag count for all Places with Tags #@tags = Place.tag_counts_on(:tags, :at_least => 1) # Manually calculate tag counts for only displayed places tags = [] @places.each do |place| tags = tags + place.tag_list end # Remove already selected tags tags = tags - @selected_tags # Count tags and make a set of [name,count] pairs @tag_counts = tags.uniq.collect {|tag| [tag,tags.select{|a|a == tag}.size] } # Filter out single tags @tag_counts = @tag_counts.select{|name,count| count > 1} # Make the count arrays act like tags for the tag cloud @tag_counts.each do |a| a.instance_eval <<-RUBY def count self[1] end def name self[0] end RUBY end respond_to do |format| format.html # index.html.erb format.iphone # index.iphone.erb format.json { render :json => @places } format.xml { render :xml => @places.to_xml(@xml_params) } end end def tag redirect_to :action => :index, :tags => params.delete(:id) end # GET /places/1 # GET /places/1.xml def show @place = Place.find(params[:id]) request.format = :html if request.format == :iphone respond_to do |format| format.html # show.html.erb - format.xml { render :xml => @place } + format.xml { render :xml => @place.to_xml(@xml_params) } end end # GET /places/new # GET /places/new.xml def new @place = Place.new request.format = :html if request.format == :iphone respond_to do |format| format.html # new.html.erb format.xml { render :xml => @place } end end # GET /places/1/edit def edit @place = Place.find(params[:id]) request.format = :html if request.format == :iphone end # POST /places # POST /places.xml def create if params[:place] and params[:place][:tag_list] params[:place][:tag_list].strip! params[:place][:tag_list].gsub!(/( )+/,', ') end @place = Place.new(params[:place]) request.format = :html if request.format == :iphone respond_to do |format| if @place.save flash[:notice] = 'Place was successfully created.' format.html { redirect_to(@place) } format.xml { render :xml => @place, :status => :created, :location => @place } else format.html { render :action => "new" } format.xml { render :xml => @place.errors, :status => :unprocessable_entity } end end end # PUT /places/1 # PUT /places/1.xml def update @place = Place.find(params[:id]) if params[:place] and params[:place][:tag_list] params[:place][:tag_list].strip! params[:place][:tag_list].gsub!(/( )+/,', ') end request.format = :html if request.format == :iphone respond_to do |format| if @place.update_attributes(params[:place]) flash[:notice] = 'Place was successfully updated.' format.html { redirect_to(@place) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @place.errors, :status => :unprocessable_entity } end end end # DELETE /places/1 # DELETE /places/1.xml def destroy @place = Place.find(params[:id]) @place.destroy request.format = :html if request.format == :iphone respond_to do |format| format.html { redirect_to(places_url) } format.xml { head :ok } end end # GET /places/open # GET /places/open.xml def open @place = Place.find(params[:id]) request.format = :html if request.format == :iphone respond_to do |format| format.html # open.html.erb format.xml { render :xml => @place } end end end
michaelansel/dukenow
119817e57d259ec04b4f4c7b08127b2243029fd8
Add API support for arbitrary schedule boundaries in request parameters
diff --git a/app/controllers/places_controller.rb b/app/controllers/places_controller.rb index 7a64ac8..2272269 100644 --- a/app/controllers/places_controller.rb +++ b/app/controllers/places_controller.rb @@ -1,172 +1,192 @@ class PlacesController < ApplicationController ActionView::Base.send :include, TagsHelper - before_filter :get_at_date + before_filter :map_params, :parse_dates_and_times, :filter_xml_params def get_at_date params[:at] = Date.today.to_s if params[:at].nil? @at = Date.parse(params[:at]) end + def map_params + map = {:from => :schedule_from, :to => :schedule_to, :at => :schedule_for_date} + params.each{|k,v| params[map[k.to_sym]] = v if map.has_key?(k.to_sym) } + end + + def parse_dates_and_times + times = [:schedule_from, :schedule_to, :schedule_for_date] + params[:schedule_from] = Time.parse(params[:schedule_from]) if params[:schedule_from] + params[:schedule_to] = Time.parse(params[:schedule_to]) if params[:schedule_to] + params[:schedule_for_date] = Date.parse(params[:schedule_for_date]) if params[:schedule_for_date] + end + + def filter_xml_params + safe = [:schedule_from, :schedule_to, :schedule_for_date] + @xml_params ||= {} + + params.each{|k,v| @xml_params[k.to_sym] = v if safe.include?(k.to_sym) } + RAILS_DEFAULT_LOGGER.info "XML Params: #{@xml_params.inspect}" + end + # GET /places # GET /places.xml def index @places = Place.find(:all, :order => "name ASC") if params[:tags] @selected_tags = params[:tags].split(/[,+ ][ ]*/) else @selected_tags = [] end # Restrict to specific tags @selected_tags.each do |tag| RAILS_DEFAULT_LOGGER.debug "Restricting by tag: #{tag}" @places = @places & Place.tagged_with(tag, :on => :tags) end # Don't display machineAdded Places on the main listing @places = @places - Place.tagged_with("machineAdded", :on => :tags) unless @selected_tags.include?("machineAdded") # Calculate tag count for all Places with Tags #@tags = Place.tag_counts_on(:tags, :at_least => 1) # Manually calculate tag counts for only displayed places tags = [] @places.each do |place| tags = tags + place.tag_list end # Remove already selected tags tags = tags - @selected_tags # Count tags and make a set of [name,count] pairs @tag_counts = tags.uniq.collect {|tag| [tag,tags.select{|a|a == tag}.size] } # Filter out single tags @tag_counts = @tag_counts.select{|name,count| count > 1} # Make the count arrays act like tags for the tag cloud @tag_counts.each do |a| a.instance_eval <<-RUBY def count self[1] end def name self[0] end RUBY end respond_to do |format| format.html # index.html.erb format.iphone # index.iphone.erb format.json { render :json => @places } - format.xml { render :xml => @places } + format.xml { render :xml => @places.to_xml(@xml_params) } end end def tag redirect_to :action => :index, :tags => params.delete(:id) end # GET /places/1 # GET /places/1.xml def show @place = Place.find(params[:id]) request.format = :html if request.format == :iphone respond_to do |format| format.html # show.html.erb format.xml { render :xml => @place } end end # GET /places/new # GET /places/new.xml def new @place = Place.new request.format = :html if request.format == :iphone respond_to do |format| format.html # new.html.erb format.xml { render :xml => @place } end end # GET /places/1/edit def edit @place = Place.find(params[:id]) request.format = :html if request.format == :iphone end # POST /places # POST /places.xml def create if params[:place] and params[:place][:tag_list] params[:place][:tag_list].strip! params[:place][:tag_list].gsub!(/( )+/,', ') end @place = Place.new(params[:place]) request.format = :html if request.format == :iphone respond_to do |format| if @place.save flash[:notice] = 'Place was successfully created.' format.html { redirect_to(@place) } format.xml { render :xml => @place, :status => :created, :location => @place } else format.html { render :action => "new" } format.xml { render :xml => @place.errors, :status => :unprocessable_entity } end end end # PUT /places/1 # PUT /places/1.xml def update @place = Place.find(params[:id]) if params[:place] and params[:place][:tag_list] params[:place][:tag_list].strip! params[:place][:tag_list].gsub!(/( )+/,', ') end request.format = :html if request.format == :iphone respond_to do |format| if @place.update_attributes(params[:place]) flash[:notice] = 'Place was successfully updated.' format.html { redirect_to(@place) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @place.errors, :status => :unprocessable_entity } end end end # DELETE /places/1 # DELETE /places/1.xml def destroy @place = Place.find(params[:id]) @place.destroy request.format = :html if request.format == :iphone respond_to do |format| format.html { redirect_to(places_url) } format.xml { head :ok } end end # GET /places/open # GET /places/open.xml def open @place = Place.find(params[:id]) request.format = :html if request.format == :iphone respond_to do |format| format.html # open.html.erb format.xml { render :xml => @place } end end end diff --git a/app/models/place.rb b/app/models/place.rb index 042ea24..fc55592 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,200 +1,214 @@ class Place < ActiveRecord::Base DEBUG = false has_many :operating_times has_one :dining_extension acts_as_taggable_on :tags validates_presence_of :name def special_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 1}) end def regular_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 0}) end # Returns an array of Times representing the opening and closing times # of this Place between +startAt+ and +endAt+ def schedule(startAt,endAt) ## Caching ## @schedules ||= {} if @schedules[startAt.xmlschema] and @schedules[startAt.xmlschema][endAt.xmlschema] return @schedules[startAt.xmlschema][endAt.xmlschema] end ## End Caching ## # TODO Handle events starting within the range but ending outside of it? # TODO Offload this selection to the database; okay for testing though # Select all relevant times (1 day buffer on each end) # NOTE Make sure to use generous date comparisons to allow for midnight rollovers all_regular_operating_times = regular_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} all_special_operating_times = special_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} puts "\nRegular OperatingTimes: #{all_regular_operating_times.inspect}" if DEBUG puts "\nSpecial OperatingTimes: #{all_special_operating_times.inspect}" if DEBUG regular_times = [] special_times = [] special_ranges = [] all_special_operating_times.each do |ot| puts "\nSpecial Scheduling for: #{ot.inspect}" if DEBUG # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do if DEBUG puts "Open: #{open}" puts "Close: #{close}" puts "Start Date: #{ot.startDate} (#{ot.startDate.class})" puts "End Date: #{ot.endDate} (#{ot.endDate.class})" end if close < startAt # Skip forward to the first occurrance in our time range open,close = ot.next_times(close) next end special_times << [open,close] special_ranges << Range.new(ot.startDate,ot.endDate) open,close = ot.next_times(close) end end puts "\nSpecial Times: #{special_times.inspect}" if DEBUG puts "\nSpecial Ranges: #{special_ranges.inspect}" if DEBUG all_regular_operating_times.each do |ot| puts "\nRegular Scheduling for: #{ot.inspect}" if DEBUG # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do puts "Open: #{open}" if DEBUG puts "Close: #{close}" if DEBUG if close < startAt # Skip forward to the first occurrance in our time range open,close = ot.next_times(close) next end special_ranges.each do |sr| next if sr.member?(open) end # FIXME Causing an infinite loop; would be nice if this worked #open = startAt if open < startAt #close = endAt if close > endAt regular_times << [open,close] open,close = ot.next_times(close) end end puts "\nRegular Times: #{regular_times.inspect}" if DEBUG # TODO Handle schedule overrides # TODO Handle combinations (i.e. part special, part regular) final_schedule = (regular_times+special_times).sort{|a,b|a[0] <=> b[0]} ## Caching ## @schedules ||= {} @schedules[startAt.xmlschema] ||= {} @schedules[startAt.xmlschema][endAt.xmlschema] = final_schedule ## End Caching ## final_schedule end def daySchedule(at = Date.today) at = at.to_date if at.class == Time or at.class == DateTime day_schedule = schedule(at.midnight,(at+1).midnight) #schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } #schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end =end day_schedule.sort{|a,b|a[0] <=> b[0]} end def currentSchedule(at = Time.now) puts "At(cS): #{at}" if DEBUG daySchedule(at).select { |open,close| puts "Open(cS): #{open}" if DEBUG puts "Close(cS): #{close}" if DEBUG open <= at and at <= close }[0] end def open?(at = Time.now) a = currentSchedule(at) return a ? true : false end alias :open :open? def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end def to_xml(options = {}) #super(options.merge({:only => [:id, :name, :location, :phone], :methods => [ :open, :daySchedule ] })) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] xml.place do xml.id(self.id) xml.name(self.name) xml.location(self.location) xml.building_id(self.building_id) xml.phone(self.phone) xml.tags do |xml| self.tag_list.each do |tag| xml.tag(tag) end end self.dining_extension.to_xml(options) unless self.dining_extension.nil? xml.open(self.open?) - if daySchedule.nil? or daySchedule.empty? - xml.daySchedule + if options[:schedule_from] and options[:schedule_to] + sched = schedule(options[:schedule_from],options[:schedule_to]) + sched_opts = {:from => options[:schedule_from], + :to => options[:schedule_to] } + elsif options[:schedule_for_date] + sched = daySchedule(options[:schedule_for_date]) + sched_opts = {:on => options[:schedule_for_date]} else - xml.daySchedule(:for => Date.today) do |xml|; daySchedule.each do |open,close| + sched = daySchedule(Date.today) + sched_opts = {:on => Date.today} + end + + if sched.nil? or sched.empty? + xml.schedule(sched_opts) + else + xml.schedule(sched_opts) do |xml| + sched.each do |open,close| xml.open(open.xmlschema) xml.close(close.xmlschema) - end; end + end + end end end end end
michaelansel/dukenow
517afd035e72802d8ece4da699b8255b9306b361
Make operating_times model helper database agnostic
diff --git a/app/models/place.rb b/app/models/place.rb index 52113cc..042ea24 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,200 +1,200 @@ class Place < ActiveRecord::Base DEBUG = false has_many :operating_times has_one :dining_extension acts_as_taggable_on :tags validates_presence_of :name def special_operating_times - OperatingTime.find( :all, :conditions => {:place_id => id, :override => 1}, :order => "startDate ASC, opensAt ASC" ) + OperatingTime.find( :all, :conditions => {:place_id => id, :override => 1}) end def regular_operating_times - OperatingTime.find( :all, :conditions => {:place_id => id, :override => 0}, :order => "startDate ASC, opensAt ASC" ) + OperatingTime.find( :all, :conditions => {:place_id => id, :override => 0}) end # Returns an array of Times representing the opening and closing times # of this Place between +startAt+ and +endAt+ def schedule(startAt,endAt) ## Caching ## @schedules ||= {} if @schedules[startAt.xmlschema] and @schedules[startAt.xmlschema][endAt.xmlschema] return @schedules[startAt.xmlschema][endAt.xmlschema] end ## End Caching ## # TODO Handle events starting within the range but ending outside of it? # TODO Offload this selection to the database; okay for testing though # Select all relevant times (1 day buffer on each end) # NOTE Make sure to use generous date comparisons to allow for midnight rollovers all_regular_operating_times = regular_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} all_special_operating_times = special_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} puts "\nRegular OperatingTimes: #{all_regular_operating_times.inspect}" if DEBUG puts "\nSpecial OperatingTimes: #{all_special_operating_times.inspect}" if DEBUG regular_times = [] special_times = [] special_ranges = [] all_special_operating_times.each do |ot| puts "\nSpecial Scheduling for: #{ot.inspect}" if DEBUG # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do if DEBUG puts "Open: #{open}" puts "Close: #{close}" puts "Start Date: #{ot.startDate} (#{ot.startDate.class})" puts "End Date: #{ot.endDate} (#{ot.endDate.class})" end if close < startAt # Skip forward to the first occurrance in our time range open,close = ot.next_times(close) next end special_times << [open,close] special_ranges << Range.new(ot.startDate,ot.endDate) open,close = ot.next_times(close) end end puts "\nSpecial Times: #{special_times.inspect}" if DEBUG puts "\nSpecial Ranges: #{special_ranges.inspect}" if DEBUG all_regular_operating_times.each do |ot| puts "\nRegular Scheduling for: #{ot.inspect}" if DEBUG # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do puts "Open: #{open}" if DEBUG puts "Close: #{close}" if DEBUG if close < startAt # Skip forward to the first occurrance in our time range open,close = ot.next_times(close) next end special_ranges.each do |sr| next if sr.member?(open) end # FIXME Causing an infinite loop; would be nice if this worked #open = startAt if open < startAt #close = endAt if close > endAt regular_times << [open,close] open,close = ot.next_times(close) end end puts "\nRegular Times: #{regular_times.inspect}" if DEBUG # TODO Handle schedule overrides # TODO Handle combinations (i.e. part special, part regular) final_schedule = (regular_times+special_times).sort{|a,b|a[0] <=> b[0]} ## Caching ## @schedules ||= {} @schedules[startAt.xmlschema] ||= {} @schedules[startAt.xmlschema][endAt.xmlschema] = final_schedule ## End Caching ## final_schedule end def daySchedule(at = Date.today) at = at.to_date if at.class == Time or at.class == DateTime day_schedule = schedule(at.midnight,(at+1).midnight) #schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } #schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end =end day_schedule.sort{|a,b|a[0] <=> b[0]} end def currentSchedule(at = Time.now) puts "At(cS): #{at}" if DEBUG daySchedule(at).select { |open,close| puts "Open(cS): #{open}" if DEBUG puts "Close(cS): #{close}" if DEBUG open <= at and at <= close }[0] end def open?(at = Time.now) a = currentSchedule(at) return a ? true : false end alias :open :open? def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end def to_xml(options = {}) #super(options.merge({:only => [:id, :name, :location, :phone], :methods => [ :open, :daySchedule ] })) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] xml.place do xml.id(self.id) xml.name(self.name) xml.location(self.location) xml.building_id(self.building_id) xml.phone(self.phone) xml.tags do |xml| self.tag_list.each do |tag| xml.tag(tag) end end self.dining_extension.to_xml(options) unless self.dining_extension.nil? xml.open(self.open?) if daySchedule.nil? or daySchedule.empty? xml.daySchedule else xml.daySchedule(:for => Date.today) do |xml|; daySchedule.each do |open,close| xml.open(open.xmlschema) xml.close(close.xmlschema) end; end end end end end
michaelansel/dukenow
caa15f245733a567b2feed13639e2271c37d1efb
Add gem manifest for Heroku
diff --git a/.gems b/.gems new file mode 100644 index 0000000..d28eed0 --- /dev/null +++ b/.gems @@ -0,0 +1,2 @@ +mbleigh-acts-as-taggable-on --source http://gems.github.com +sqlite3-ruby
michaelansel/dukenow
534c0e25913c210a475d9a55841a32a99338939a
Add DiningExtensions and include in Place XML
diff --git a/TODO b/TODO index 6a9a698..8010228 100644 --- a/TODO +++ b/TODO @@ -1,115 +1,115 @@ vim:set syntax=todo: Database Places -- has_one :dining_extension \- name (string) -- location (lat/long) -- ?GeoKit Plugin? \- phone_number (string) DiningExtensions -- acts_as_taggable_on :dining_tags ## needs work -- **delivery/eat-in** ## operating_time details/tag -- more_info_url -- owner_operator -- payment_methods -- logo_url OperatingTimes \- place_id \- start (midnight offset in seconds) \- length (in seconds) \- startDate (Date) \- endDate (Date) \- details (String) \- override \- days_of_week (bit-wise AND of wday's) OperatingTimesTags - -- name + \- name OperatingTimesTaggings (clone auto-generated) - !- clone Taggings schema - -- operating_time_id - -- operating_times_tag_id + \- clone Taggings schema + \- operating_time_id + \- operating_times_tag_id TimePeriods -- name (String) -- startDate (Date) -- endDate (Date) API Versioning -- Subdirectories -- rake task for adding new versions and deprecating old versions Places OperatingTimes -- Array of DateTime objects for the next N hours/days/etc -- Bulk import Excel spreadsheet -- What qualifies as a Tag versus an Attribute? Timeline OperatingTimes StartLengthSchema \- Migration Feature-parity - -- schedule(from,to) - -- daySchedule(date) - -- currentSchedule(at) - -- open?(at) + \- schedule(from,to) + \- daySchedule(date) + \- currentSchedule(at) + \- open?(at) Testing Unit Tests -- Database accessors Model Validations -- Prevent overlapping time periods without "override" flag Extend API \- Generate Time objects (Enumerable?) -- Add versioning DiningExtensions -- Migration -- Full unit tests + validation DiningExtensions Tags -- Migrations -- Full unit tests + validation OperatingTimes Tags - -- Migration + \- Migration -- Full unit tests + validation -- Extend OperatingTimes.find to filter by tags -- Extend Places.open? to test delivery/dine-in tags TimePeriods -- Migration -- Full unit tests + validation -- Create integration -- View Integration API Versioning rake Tasks -- Clone for new version and increment version number -- Deprecate old version -- Hosting for web app/file server? -- Can I get help with the UI design, or will DukeMobile only be focusing on the iPhone side? -- Set "expiration" date; Send reminder emails; Show _nothing_ rather than inaccurate info Database Adjust schema to be more flexible !- Late nights: seamless midnight rollover -- Start,End => Start,Length (then, convert to real "Time"s based on @at) -- iCal RRULE (string) and parse with RiCal (pre-release) \- Add "midnight" method to Date, Time -- (?) Multiple "special"/override schedules (e.g. every weekday during Spring Break except Friday) -- Special: "normally open, but closed all day today" -- Semester-style schedules -- List of important dates (likely to be scheduling boundaries) Interface Index (Main Page) -- Hide nowIndicator after midnight instead of wrapping around -- JavaScript Tag Filtering -- Status @ DateTime Data Entry -- Bulk import (CSV, XML) -- Duke Dining PDF parser (?) -- Not worth the effort to get consistent data Web Form -- Text entry of times (drop downs, input fields) -- Quickly add/edit all times for a location -- Graphic schedule of current settings -- Show "normal" schedule in background if making an exception -- Drag/Drop/Resize-able blocks on schedule diff --git a/app/controllers/dining_extensions_controller.rb b/app/controllers/dining_extensions_controller.rb new file mode 100644 index 0000000..b5a9f23 --- /dev/null +++ b/app/controllers/dining_extensions_controller.rb @@ -0,0 +1,85 @@ +class DiningExtensionsController < ApplicationController + # GET /dining_extensions + # GET /dining_extensions.xml + def index + @dining_extensions = DiningExtension.find(:all) + + respond_to do |format| + format.html # index.html.erb + format.xml { render :xml => @dining_extensions } + end + end + + # GET /dining_extensions/1 + # GET /dining_extensions/1.xml + def show + @dining_extension = DiningExtension.find(params[:id]) + + respond_to do |format| + format.html # show.html.erb + format.xml { render :xml => @dining_extension } + end + end + + # GET /dining_extensions/new + # GET /dining_extensions/new.xml + def new + @dining_extension = DiningExtension.new + + respond_to do |format| + format.html # new.html.erb + format.xml { render :xml => @dining_extension } + end + end + + # GET /dining_extensions/1/edit + def edit + @dining_extension = DiningExtension.find(params[:id]) + end + + # POST /dining_extensions + # POST /dining_extensions.xml + def create + @dining_extension = DiningExtension.new(params[:dining_extension]) + + respond_to do |format| + if @dining_extension.save + flash[:notice] = 'DiningExtension was successfully created.' + format.html { redirect_to(@dining_extension) } + format.xml { render :xml => @dining_extension, :status => :created, :location => @dining_extension } + else + format.html { render :action => "new" } + format.xml { render :xml => @dining_extension.errors, :status => :unprocessable_entity } + end + end + end + + # PUT /dining_extensions/1 + # PUT /dining_extensions/1.xml + def update + @dining_extension = DiningExtension.find(params[:id]) + + respond_to do |format| + if @dining_extension.update_attributes(params[:dining_extension]) + flash[:notice] = 'DiningExtension was successfully updated.' + format.html { redirect_to(@dining_extension) } + format.xml { head :ok } + else + format.html { render :action => "edit" } + format.xml { render :xml => @dining_extension.errors, :status => :unprocessable_entity } + end + end + end + + # DELETE /dining_extensions/1 + # DELETE /dining_extensions/1.xml + def destroy + @dining_extension = DiningExtension.find(params[:id]) + @dining_extension.destroy + + respond_to do |format| + format.html { redirect_to(dining_extensions_url) } + format.xml { head :ok } + end + end +end diff --git a/app/helpers/dining_extensions_helper.rb b/app/helpers/dining_extensions_helper.rb new file mode 100644 index 0000000..390f2b1 --- /dev/null +++ b/app/helpers/dining_extensions_helper.rb @@ -0,0 +1,2 @@ +module DiningExtensionsHelper +end diff --git a/app/models/dining_extension.rb b/app/models/dining_extension.rb new file mode 100644 index 0000000..cd84cf6 --- /dev/null +++ b/app/models/dining_extension.rb @@ -0,0 +1,15 @@ +class DiningExtension < ActiveRecord::Base + belongs_to :place + + def to_xml(options = {}) + options[:indent] ||= 2 + xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) + xml.instruct! unless options[:skip_instruct] + xml.dining_extension do |xml| + xml.logo_url(logo_url) + xml.more_info_url(more_info_url) + xml.owner_operator(owner_operator) + xml.payment_methods(payment_methods) + end + end +end diff --git a/app/models/place.rb b/app/models/place.rb index 2f87c94..52113cc 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,197 +1,200 @@ class Place < ActiveRecord::Base DEBUG = false has_many :operating_times + has_one :dining_extension acts_as_taggable_on :tags validates_presence_of :name def special_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 1}, :order => "startDate ASC, opensAt ASC" ) end def regular_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 0}, :order => "startDate ASC, opensAt ASC" ) end # Returns an array of Times representing the opening and closing times # of this Place between +startAt+ and +endAt+ def schedule(startAt,endAt) ## Caching ## @schedules ||= {} if @schedules[startAt.xmlschema] and @schedules[startAt.xmlschema][endAt.xmlschema] return @schedules[startAt.xmlschema][endAt.xmlschema] end ## End Caching ## # TODO Handle events starting within the range but ending outside of it? # TODO Offload this selection to the database; okay for testing though # Select all relevant times (1 day buffer on each end) # NOTE Make sure to use generous date comparisons to allow for midnight rollovers all_regular_operating_times = regular_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} all_special_operating_times = special_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} puts "\nRegular OperatingTimes: #{all_regular_operating_times.inspect}" if DEBUG puts "\nSpecial OperatingTimes: #{all_special_operating_times.inspect}" if DEBUG regular_times = [] special_times = [] special_ranges = [] all_special_operating_times.each do |ot| puts "\nSpecial Scheduling for: #{ot.inspect}" if DEBUG # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do if DEBUG puts "Open: #{open}" puts "Close: #{close}" puts "Start Date: #{ot.startDate} (#{ot.startDate.class})" puts "End Date: #{ot.endDate} (#{ot.endDate.class})" end if close < startAt # Skip forward to the first occurrance in our time range open,close = ot.next_times(close) next end special_times << [open,close] special_ranges << Range.new(ot.startDate,ot.endDate) open,close = ot.next_times(close) end end puts "\nSpecial Times: #{special_times.inspect}" if DEBUG puts "\nSpecial Ranges: #{special_ranges.inspect}" if DEBUG all_regular_operating_times.each do |ot| puts "\nRegular Scheduling for: #{ot.inspect}" if DEBUG # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do puts "Open: #{open}" if DEBUG puts "Close: #{close}" if DEBUG if close < startAt # Skip forward to the first occurrance in our time range open,close = ot.next_times(close) next end special_ranges.each do |sr| next if sr.member?(open) end # FIXME Causing an infinite loop; would be nice if this worked #open = startAt if open < startAt #close = endAt if close > endAt regular_times << [open,close] open,close = ot.next_times(close) end end puts "\nRegular Times: #{regular_times.inspect}" if DEBUG # TODO Handle schedule overrides # TODO Handle combinations (i.e. part special, part regular) final_schedule = (regular_times+special_times).sort{|a,b|a[0] <=> b[0]} ## Caching ## @schedules ||= {} @schedules[startAt.xmlschema] ||= {} @schedules[startAt.xmlschema][endAt.xmlschema] = final_schedule ## End Caching ## final_schedule end def daySchedule(at = Date.today) at = at.to_date if at.class == Time or at.class == DateTime day_schedule = schedule(at.midnight,(at+1).midnight) #schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } #schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end =end day_schedule.sort{|a,b|a[0] <=> b[0]} end def currentSchedule(at = Time.now) puts "At(cS): #{at}" if DEBUG daySchedule(at).select { |open,close| puts "Open(cS): #{open}" if DEBUG puts "Close(cS): #{close}" if DEBUG open <= at and at <= close }[0] end def open?(at = Time.now) a = currentSchedule(at) return a ? true : false end alias :open :open? def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end def to_xml(options = {}) #super(options.merge({:only => [:id, :name, :location, :phone], :methods => [ :open, :daySchedule ] })) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] xml.place do xml.id(self.id) xml.name(self.name) xml.location(self.location) xml.building_id(self.building_id) xml.phone(self.phone) xml.tags do |xml| self.tag_list.each do |tag| xml.tag(tag) end end + self.dining_extension.to_xml(options) unless self.dining_extension.nil? + xml.open(self.open?) if daySchedule.nil? or daySchedule.empty? xml.daySchedule else xml.daySchedule(:for => Date.today) do |xml|; daySchedule.each do |open,close| xml.open(open.xmlschema) xml.close(close.xmlschema) end; end end end end end diff --git a/app/views/dining_extensions/edit.html.erb b/app/views/dining_extensions/edit.html.erb new file mode 100644 index 0000000..f3eaa1b --- /dev/null +++ b/app/views/dining_extensions/edit.html.erb @@ -0,0 +1,12 @@ +<h1>Editing dining_extension</h1> + +<% form_for(@dining_extension) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.submit "Update" %> + </p> +<% end %> + +<%= link_to 'Show', @dining_extension %> | +<%= link_to 'Back', dining_extensions_path %> diff --git a/app/views/dining_extensions/index.html.erb b/app/views/dining_extensions/index.html.erb new file mode 100644 index 0000000..f0c10e4 --- /dev/null +++ b/app/views/dining_extensions/index.html.erb @@ -0,0 +1,18 @@ +<h1>Listing dining_extensions</h1> + +<table> + <tr> + </tr> + +<% for dining_extension in @dining_extensions %> + <tr> + <td><%= link_to 'Show', dining_extension %></td> + <td><%= link_to 'Edit', edit_dining_extension_path(dining_extension) %></td> + <td><%= link_to 'Destroy', dining_extension, :confirm => 'Are you sure?', :method => :delete %></td> + </tr> +<% end %> +</table> + +<br /> + +<%= link_to 'New dining_extension', new_dining_extension_path %> diff --git a/app/views/dining_extensions/new.html.erb b/app/views/dining_extensions/new.html.erb new file mode 100644 index 0000000..6387ef4 --- /dev/null +++ b/app/views/dining_extensions/new.html.erb @@ -0,0 +1,11 @@ +<h1>New dining_extension</h1> + +<% form_for(@dining_extension) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.submit "Create" %> + </p> +<% end %> + +<%= link_to 'Back', dining_extensions_path %> diff --git a/app/views/dining_extensions/show.html.erb b/app/views/dining_extensions/show.html.erb new file mode 100644 index 0000000..48a0581 --- /dev/null +++ b/app/views/dining_extensions/show.html.erb @@ -0,0 +1,3 @@ + +<%= link_to 'Edit', edit_dining_extension_path(@dining_extension) %> | +<%= link_to 'Back', dining_extensions_path %> diff --git a/app/views/layouts/dining_extensions.html.erb b/app/views/layouts/dining_extensions.html.erb new file mode 100644 index 0000000..bf26c09 --- /dev/null +++ b/app/views/layouts/dining_extensions.html.erb @@ -0,0 +1,17 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> + +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> + <title>DiningExtensions: <%= controller.action_name %></title> + <%= stylesheet_link_tag 'scaffold' %> +</head> +<body> + +<p style="color: green"><%= flash[:notice] %></p> + +<%= yield %> + +</body> +</html> diff --git a/config/routes.rb b/config/routes.rb index 471e0bf..cb864f0 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,49 +1,51 @@ ActionController::Routing::Routes.draw do |map| + map.resources :dining_extensions + map.resources :places map.resources :operating_times map.connect 'operating_times/place/:place_id', :controller => 'operating_times', :action => 'index' map.root :controller => "places" # The priority is based upon order of creation: first created -> highest priority. # Sample of regular route: # map.connect 'products/:id', :controller => 'catalog', :action => 'view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase' # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # map.resources :products # Sample resource route with options: # map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get } # Sample resource route with sub-resources: # map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller # Sample resource route with more complex sub-resources # map.resources :products do |products| # products.resources :comments # products.resources :sales, :collection => { :recent => :get } # end # Sample resource route within a namespace: # map.namespace :admin do |admin| # # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb) # admin.resources :products # end # You can have the root of your site routed with map.root -- just remember to delete public/index.html. # map.root :controller => "welcome" # See how all your routes lay out with "rake routes" # Install the default routes as the lowest priority. # Note: These default routes make all actions in every controller accessible via GET requests. You should # consider removing the them or commenting them out if you're using named routes and resources. map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end diff --git a/db/migrate/20090706185105_create_dining_extensions.rb b/db/migrate/20090706185105_create_dining_extensions.rb new file mode 100644 index 0000000..906e5cb --- /dev/null +++ b/db/migrate/20090706185105_create_dining_extensions.rb @@ -0,0 +1,17 @@ +class CreateDiningExtensions < ActiveRecord::Migration + def self.up + create_table :dining_extensions do |t| + t.integer "place_id" + t.string "logo_url" + t.string "more_info_url" + t.string "owner_operator" + t.string "payment_methods" + + t.timestamps + end + end + + def self.down + drop_table :dining_extensions + end +end diff --git a/spec/controllers/dining_extensions_controller_spec.rb b/spec/controllers/dining_extensions_controller_spec.rb new file mode 100644 index 0000000..932aafc --- /dev/null +++ b/spec/controllers/dining_extensions_controller_spec.rb @@ -0,0 +1,131 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') + +describe DiningExtensionsController do + + def mock_dining_extension(stubs={}) + @mock_dining_extension ||= mock_model(DiningExtension, stubs) + end + + describe "GET index" do + it "assigns all dining_extensions as @dining_extensions" do + DiningExtension.stub!(:find).with(:all).and_return([mock_dining_extension]) + get :index + assigns[:dining_extensions].should == [mock_dining_extension] + end + end + + describe "GET show" do + it "assigns the requested dining_extension as @dining_extension" do + DiningExtension.stub!(:find).with("37").and_return(mock_dining_extension) + get :show, :id => "37" + assigns[:dining_extension].should equal(mock_dining_extension) + end + end + + describe "GET new" do + it "assigns a new dining_extension as @dining_extension" do + DiningExtension.stub!(:new).and_return(mock_dining_extension) + get :new + assigns[:dining_extension].should equal(mock_dining_extension) + end + end + + describe "GET edit" do + it "assigns the requested dining_extension as @dining_extension" do + DiningExtension.stub!(:find).with("37").and_return(mock_dining_extension) + get :edit, :id => "37" + assigns[:dining_extension].should equal(mock_dining_extension) + end + end + + describe "POST create" do + + describe "with valid params" do + it "assigns a newly created dining_extension as @dining_extension" do + DiningExtension.stub!(:new).with({'these' => 'params'}).and_return(mock_dining_extension(:save => true)) + post :create, :dining_extension => {:these => 'params'} + assigns[:dining_extension].should equal(mock_dining_extension) + end + + it "redirects to the created dining_extension" do + DiningExtension.stub!(:new).and_return(mock_dining_extension(:save => true)) + post :create, :dining_extension => {} + response.should redirect_to(dining_extension_url(mock_dining_extension)) + end + end + + describe "with invalid params" do + it "assigns a newly created but unsaved dining_extension as @dining_extension" do + DiningExtension.stub!(:new).with({'these' => 'params'}).and_return(mock_dining_extension(:save => false)) + post :create, :dining_extension => {:these => 'params'} + assigns[:dining_extension].should equal(mock_dining_extension) + end + + it "re-renders the 'new' template" do + DiningExtension.stub!(:new).and_return(mock_dining_extension(:save => false)) + post :create, :dining_extension => {} + response.should render_template('new') + end + end + + end + + describe "PUT update" do + + describe "with valid params" do + it "updates the requested dining_extension" do + DiningExtension.should_receive(:find).with("37").and_return(mock_dining_extension) + mock_dining_extension.should_receive(:update_attributes).with({'these' => 'params'}) + put :update, :id => "37", :dining_extension => {:these => 'params'} + end + + it "assigns the requested dining_extension as @dining_extension" do + DiningExtension.stub!(:find).and_return(mock_dining_extension(:update_attributes => true)) + put :update, :id => "1" + assigns[:dining_extension].should equal(mock_dining_extension) + end + + it "redirects to the dining_extension" do + DiningExtension.stub!(:find).and_return(mock_dining_extension(:update_attributes => true)) + put :update, :id => "1" + response.should redirect_to(dining_extension_url(mock_dining_extension)) + end + end + + describe "with invalid params" do + it "updates the requested dining_extension" do + DiningExtension.should_receive(:find).with("37").and_return(mock_dining_extension) + mock_dining_extension.should_receive(:update_attributes).with({'these' => 'params'}) + put :update, :id => "37", :dining_extension => {:these => 'params'} + end + + it "assigns the dining_extension as @dining_extension" do + DiningExtension.stub!(:find).and_return(mock_dining_extension(:update_attributes => false)) + put :update, :id => "1" + assigns[:dining_extension].should equal(mock_dining_extension) + end + + it "re-renders the 'edit' template" do + DiningExtension.stub!(:find).and_return(mock_dining_extension(:update_attributes => false)) + put :update, :id => "1" + response.should render_template('edit') + end + end + + end + + describe "DELETE destroy" do + it "destroys the requested dining_extension" do + DiningExtension.should_receive(:find).with("37").and_return(mock_dining_extension) + mock_dining_extension.should_receive(:destroy) + delete :destroy, :id => "37" + end + + it "redirects to the dining_extensions list" do + DiningExtension.stub!(:find).and_return(mock_dining_extension(:destroy => true)) + delete :destroy, :id => "1" + response.should redirect_to(dining_extensions_url) + end + end + +end diff --git a/spec/fixtures/dining_extensions.yml b/spec/fixtures/dining_extensions.yml new file mode 100644 index 0000000..5bf0293 --- /dev/null +++ b/spec/fixtures/dining_extensions.yml @@ -0,0 +1,7 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +# one: +# column: value +# +# two: +# column: value diff --git a/spec/helpers/dining_extensions_helper_spec.rb b/spec/helpers/dining_extensions_helper_spec.rb new file mode 100644 index 0000000..019f3be --- /dev/null +++ b/spec/helpers/dining_extensions_helper_spec.rb @@ -0,0 +1,11 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') + +describe DiningExtensionsHelper do + + #Delete this example and add some real ones or delete this file + it "is included in the helper object" do + included_modules = (class << helper; self; end).send :included_modules + included_modules.should include(DiningExtensionsHelper) + end + +end diff --git a/spec/integration/dining_extensions_spec.rb b/spec/integration/dining_extensions_spec.rb new file mode 100644 index 0000000..0bb4727 --- /dev/null +++ b/spec/integration/dining_extensions_spec.rb @@ -0,0 +1,4 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') + +describe "DiningExtensions" do +end diff --git a/spec/models/dining_extension_spec.rb b/spec/models/dining_extension_spec.rb new file mode 100644 index 0000000..81ec7a8 --- /dev/null +++ b/spec/models/dining_extension_spec.rb @@ -0,0 +1,13 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') + +describe DiningExtension do + before(:each) do + @valid_attributes = { + + } + end + + it "should create a new instance given valid attributes" do + DiningExtension.create!(@valid_attributes) + end +end diff --git a/spec/routing/dining_extensions_routing_spec.rb b/spec/routing/dining_extensions_routing_spec.rb new file mode 100644 index 0000000..d12b2c4 --- /dev/null +++ b/spec/routing/dining_extensions_routing_spec.rb @@ -0,0 +1,63 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') + +describe DiningExtensionsController do + describe "route generation" do + it "maps #index" do + route_for(:controller => "dining_extensions", :action => "index").should == "/dining_extensions" + end + + it "maps #new" do + route_for(:controller => "dining_extensions", :action => "new").should == "/dining_extensions/new" + end + + it "maps #show" do + route_for(:controller => "dining_extensions", :action => "show", :id => "1").should == "/dining_extensions/1" + end + + it "maps #edit" do + route_for(:controller => "dining_extensions", :action => "edit", :id => "1").should == "/dining_extensions/1/edit" + end + + it "maps #create" do + route_for(:controller => "dining_extensions", :action => "create").should == {:path => "/dining_extensions", :method => :post} + end + + it "maps #update" do + route_for(:controller => "dining_extensions", :action => "update", :id => "1").should == {:path =>"/dining_extensions/1", :method => :put} + end + + it "maps #destroy" do + route_for(:controller => "dining_extensions", :action => "destroy", :id => "1").should == {:path =>"/dining_extensions/1", :method => :delete} + end + end + + describe "route recognition" do + it "generates params for #index" do + params_from(:get, "/dining_extensions").should == {:controller => "dining_extensions", :action => "index"} + end + + it "generates params for #new" do + params_from(:get, "/dining_extensions/new").should == {:controller => "dining_extensions", :action => "new"} + end + + it "generates params for #create" do + params_from(:post, "/dining_extensions").should == {:controller => "dining_extensions", :action => "create"} + end + + it "generates params for #show" do + params_from(:get, "/dining_extensions/1").should == {:controller => "dining_extensions", :action => "show", :id => "1"} + end + + it "generates params for #edit" do + params_from(:get, "/dining_extensions/1/edit").should == {:controller => "dining_extensions", :action => "edit", :id => "1"} + end + + it "generates params for #update" do + params_from(:put, "/dining_extensions/1").should == {:controller => "dining_extensions", :action => "update", :id => "1"} + end + + it "generates params for #destroy" do + params_from(:delete, "/dining_extensions/1").should == {:controller => "dining_extensions", :action => "destroy", :id => "1"} + end + end +end diff --git a/spec/views/dining_extensions/edit.html.erb_spec.rb b/spec/views/dining_extensions/edit.html.erb_spec.rb new file mode 100644 index 0000000..495082f --- /dev/null +++ b/spec/views/dining_extensions/edit.html.erb_spec.rb @@ -0,0 +1,18 @@ +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') + +describe "/dining_extensions/edit.html.erb" do + include DiningExtensionsHelper + + before(:each) do + assigns[:dining_extension] = @dining_extension = stub_model(DiningExtension, + :new_record? => false + ) + end + + it "renders the edit dining_extension form" do + render + + response.should have_tag("form[action=#{dining_extension_path(@dining_extension)}][method=post]") do + end + end +end diff --git a/spec/views/dining_extensions/index.html.erb_spec.rb b/spec/views/dining_extensions/index.html.erb_spec.rb new file mode 100644 index 0000000..dce82a6 --- /dev/null +++ b/spec/views/dining_extensions/index.html.erb_spec.rb @@ -0,0 +1,16 @@ +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') + +describe "/dining_extensions/index.html.erb" do + include DiningExtensionsHelper + + before(:each) do + assigns[:dining_extensions] = [ + stub_model(DiningExtension), + stub_model(DiningExtension) + ] + end + + it "renders a list of dining_extensions" do + render + end +end diff --git a/spec/views/dining_extensions/new.html.erb_spec.rb b/spec/views/dining_extensions/new.html.erb_spec.rb new file mode 100644 index 0000000..edd0d62 --- /dev/null +++ b/spec/views/dining_extensions/new.html.erb_spec.rb @@ -0,0 +1,18 @@ +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') + +describe "/dining_extensions/new.html.erb" do + include DiningExtensionsHelper + + before(:each) do + assigns[:dining_extension] = stub_model(DiningExtension, + :new_record? => true + ) + end + + it "renders new dining_extension form" do + render + + response.should have_tag("form[action=?][method=post]", dining_extensions_path) do + end + end +end diff --git a/spec/views/dining_extensions/show.html.erb_spec.rb b/spec/views/dining_extensions/show.html.erb_spec.rb new file mode 100644 index 0000000..9b8a53e --- /dev/null +++ b/spec/views/dining_extensions/show.html.erb_spec.rb @@ -0,0 +1,12 @@ +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') + +describe "/dining_extensions/show.html.erb" do + include DiningExtensionsHelper + before(:each) do + assigns[:dining_extension] = @dining_extension = stub_model(DiningExtension) + end + + it "renders attributes in <p>" do + render + end +end
michaelansel/dukenow
75f086f24dede310ce229dcde8f38248ca351bdc
Add building_id field to Place model
diff --git a/app/models/place.rb b/app/models/place.rb index b7cab2a..2f87c94 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,192 +1,197 @@ class Place < ActiveRecord::Base DEBUG = false has_many :operating_times acts_as_taggable_on :tags validates_presence_of :name def special_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 1}, :order => "startDate ASC, opensAt ASC" ) end def regular_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 0}, :order => "startDate ASC, opensAt ASC" ) end # Returns an array of Times representing the opening and closing times # of this Place between +startAt+ and +endAt+ def schedule(startAt,endAt) ## Caching ## @schedules ||= {} if @schedules[startAt.xmlschema] and @schedules[startAt.xmlschema][endAt.xmlschema] return @schedules[startAt.xmlschema][endAt.xmlschema] end ## End Caching ## # TODO Handle events starting within the range but ending outside of it? # TODO Offload this selection to the database; okay for testing though # Select all relevant times (1 day buffer on each end) # NOTE Make sure to use generous date comparisons to allow for midnight rollovers all_regular_operating_times = regular_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} all_special_operating_times = special_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} puts "\nRegular OperatingTimes: #{all_regular_operating_times.inspect}" if DEBUG puts "\nSpecial OperatingTimes: #{all_special_operating_times.inspect}" if DEBUG regular_times = [] special_times = [] special_ranges = [] all_special_operating_times.each do |ot| puts "\nSpecial Scheduling for: #{ot.inspect}" if DEBUG # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do if DEBUG puts "Open: #{open}" puts "Close: #{close}" puts "Start Date: #{ot.startDate} (#{ot.startDate.class})" puts "End Date: #{ot.endDate} (#{ot.endDate.class})" end if close < startAt # Skip forward to the first occurrance in our time range open,close = ot.next_times(close) next end special_times << [open,close] special_ranges << Range.new(ot.startDate,ot.endDate) open,close = ot.next_times(close) end end puts "\nSpecial Times: #{special_times.inspect}" if DEBUG puts "\nSpecial Ranges: #{special_ranges.inspect}" if DEBUG all_regular_operating_times.each do |ot| puts "\nRegular Scheduling for: #{ot.inspect}" if DEBUG # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do puts "Open: #{open}" if DEBUG puts "Close: #{close}" if DEBUG if close < startAt # Skip forward to the first occurrance in our time range open,close = ot.next_times(close) next end special_ranges.each do |sr| next if sr.member?(open) end + # FIXME Causing an infinite loop; would be nice if this worked + #open = startAt if open < startAt + #close = endAt if close > endAt + regular_times << [open,close] open,close = ot.next_times(close) end end puts "\nRegular Times: #{regular_times.inspect}" if DEBUG # TODO Handle schedule overrides # TODO Handle combinations (i.e. part special, part regular) final_schedule = (regular_times+special_times).sort{|a,b|a[0] <=> b[0]} ## Caching ## @schedules ||= {} @schedules[startAt.xmlschema] ||= {} @schedules[startAt.xmlschema][endAt.xmlschema] = final_schedule ## End Caching ## final_schedule end def daySchedule(at = Date.today) at = at.to_date if at.class == Time or at.class == DateTime day_schedule = schedule(at.midnight,(at+1).midnight) #schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } #schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end =end day_schedule.sort{|a,b|a[0] <=> b[0]} end def currentSchedule(at = Time.now) puts "At(cS): #{at}" if DEBUG daySchedule(at).select { |open,close| puts "Open(cS): #{open}" if DEBUG puts "Close(cS): #{close}" if DEBUG open <= at and at <= close }[0] end def open?(at = Time.now) a = currentSchedule(at) return a ? true : false end alias :open :open? def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end def to_xml(options = {}) #super(options.merge({:only => [:id, :name, :location, :phone], :methods => [ :open, :daySchedule ] })) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] xml.place do xml.id(self.id) xml.name(self.name) xml.location(self.location) + xml.building_id(self.building_id) xml.phone(self.phone) xml.tags do |xml| self.tag_list.each do |tag| xml.tag(tag) end end xml.open(self.open?) if daySchedule.nil? or daySchedule.empty? xml.daySchedule else xml.daySchedule(:for => Date.today) do |xml|; daySchedule.each do |open,close| xml.open(open.xmlschema) xml.close(close.xmlschema) end; end end end end end diff --git a/db/migrate/20090706175956_add_building_id.rb b/db/migrate/20090706175956_add_building_id.rb new file mode 100644 index 0000000..811d19d --- /dev/null +++ b/db/migrate/20090706175956_add_building_id.rb @@ -0,0 +1,9 @@ +class AddBuildingId < ActiveRecord::Migration + def self.up + add_column("places", "building_id", :integer) + end + + def self.down + remove_column("places", "building_id") + end +end diff --git a/db/schema.rb b/db/schema.rb index 99c2c03..586332b 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,97 +1,98 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20090706033509) do +ActiveRecord::Schema.define(:version => 20090706175956) do create_table "eateries", :force => true do |t| t.string "name" t.string "location" t.string "phone" t.datetime "created_at" t.datetime "updated_at" end create_table "operating_time_taggings", :force => true do |t| t.integer "tag_id" t.integer "taggable_id" t.integer "tagger_id" t.string "tagger_type" t.string "taggable_type" t.string "context" t.datetime "created_at" end add_index "operating_time_taggings", ["tag_id"], :name => "index_operating_time_taggings_on_tag_id" add_index "operating_time_taggings", ["taggable_id", "taggable_type", "context"], :name => "index_operating_time_taggings_on_taggable_id_and_taggable_type_and_context" create_table "operating_time_tags", :force => true do |t| t.string "name" end create_table "operating_times", :force => true do |t| t.integer "place_id" t.integer "opensAt" t.integer "length" t.text "details" t.date "startDate" t.date "endDate" t.datetime "created_at" t.datetime "updated_at" t.integer "override", :default => 0, :null => false t.integer "daysOfWeek", :default => 0, :null => false end create_table "places", :force => true do |t| t.string "name" t.string "location" t.string "phone" t.datetime "created_at" t.datetime "updated_at" + t.integer "building_id" end create_table "regular_operating_times", :force => true do |t| t.integer "eatery_id" t.integer "opensAt" t.integer "closesAt" t.integer "daysOfWeek" t.datetime "created_at" t.datetime "updated_at" end create_table "special_operating_times", :force => true do |t| t.integer "eatery_id" t.integer "opensAt" t.integer "closesAt" t.integer "daysOfWeek" t.date "start" t.date "end" t.datetime "created_at" t.datetime "updated_at" end create_table "taggings", :force => true do |t| t.integer "tag_id" t.integer "taggable_id" t.integer "tagger_id" t.string "tagger_type" t.string "taggable_type" t.string "context" t.datetime "created_at" end add_index "taggings", ["tag_id"], :name => "index_taggings_on_tag_id" add_index "taggings", ["taggable_id", "taggable_type", "context"], :name => "index_taggings_on_taggable_id_and_taggable_type_and_context" create_table "tags", :force => true do |t| t.string "name" end end
michaelansel/dukenow
4098a9fdcb10d0f3165cbd92ce01de8eaf2aa64b
Add tags to XML for Place and OperatingTime
diff --git a/app/models/operating_time.rb b/app/models/operating_time.rb index 8d22e93..e45e977 100644 --- a/app/models/operating_time.rb +++ b/app/models/operating_time.rb @@ -1,284 +1,277 @@ class OperatingTime < ActiveRecord::Base belongs_to :place acts_as_taggable_on :operating_time_tags validates_presence_of :place_id, :endDate, :startDate validates_associated :place validate :end_after_start, :daysOfWeek_valid validate {|ot| 0 <= ot.length and ot.length <= 1.days } ## DaysOfWeek Constants ## SUNDAY = 0b00000001 MONDAY = 0b00000010 TUESDAY = 0b00000100 WEDNESDAY = 0b00001000 THURSDAY = 0b00010000 FRIDAY = 0b00100000 SATURDAY = 0b01000000 ALL_DAYS = (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) ## Validations ## def end_after_start if endDate < startDate errors.add_to_base("End date cannot preceed start date") end end def daysOfWeek_valid daysOfWeek == daysOfWeek & (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) end ## End Validations ## # TODO Is this OperatingTime applicable at +time+ def valid_at(time=Time.now) raise NotImplementedError end # Tag Helpers %w{tag_list tags tag_counts tag_ids tag_tagging_ids tag_taggings}.each do |m| [m,m+"="].each do |m| if self.instance_methods.include?("operating_time_"+m) - definition = "" - definition += "def #{m}(" - definition += "arg" if self.instance_method("operating_time_"+m).arity == 1 - definition += "*args" if self.instance_method("operating_time_"+m).arity > 1 - definition += ")\n" - definition += "operating_time_#{m}(" - definition += "arg" if self.instance_method("operating_time_"+m).arity == 1 - definition += "*args" if self.instance_method("operating_time_"+m).arity > 1 - definition += ")\n" - definition += "end" - - self.class_eval(definition) + self.class_eval "alias #{m.to_sym} #{"operating_time_#{m}".to_sym}" end end ; end def tags_from ; operating_time_tags_from ; end def override read_attribute(:override) == 1 end def override=(mode) if mode == true or mode == "true" or mode == 1 write_attribute(:override, true) elsif mode == false or mode == "false" or mode == 0 write_attribute(:override, false) else raise ArgumentError, "Invalid override value (#{mode.inspect}); Accepts true/false, 1/0" end end def daysOfWeek=(newDow) if not ( newDow & ALL_DAYS == newDow ) # Invalid input raise ArgumentError, "Not a valid value for daysOfWeek (#{newDow.inspect})" end write_attribute(:daysOfWeek, newDow & ALL_DAYS) @daysOfWeekHash = nil @daysOfWeekArray = nil @daysOfWeekString = nil end ## daysOfWeek Helper/Accessors ## # Hash mapping day of week (Symbol) to valid(true)/invalid(false) def daysOfWeekHash @daysOfWeekHash ||= { :sunday => (daysOfWeek & SUNDAY ) > 0, :monday => (daysOfWeek & MONDAY ) > 0, :tuesday => (daysOfWeek & TUESDAY ) > 0, :wednesday => (daysOfWeek & WEDNESDAY ) > 0, :thursday => (daysOfWeek & THURSDAY ) > 0, :friday => (daysOfWeek & FRIDAY ) > 0, :saturday => (daysOfWeek & SATURDAY ) > 0 } end # Array beginning with Sunday of valid(true)/inactive(false) values def daysOfWeekArray dow = daysOfWeekHash @daysOfWeekArray ||= [ dow[:sunday], dow[:monday], dow[:tuesday], dow[:wednesday], dow[:thursday], dow[:friday], dow[:saturday] ] end # Human-readable string of applicable days of week def daysOfWeekString dow = daysOfWeekHash @daysOfWeekString ||= (dow[:sunday] ? "Su" : "") + (dow[:monday] ? "M" : "") + (dow[:tuesday] ? "Tu" : "") + (dow[:wednesday] ? "W" : "") + (dow[:thursday] ? "Th" : "") + (dow[:friday] ? "F" : "") + (dow[:saturday] ? "Sa" : "") end ## End daysOfWeek Helper/Accessors ## # Returns the next full occurrence of these operating time rule. # If we are currently within a valid time range, it will look forward for the # <em>next</em> opening time def next_times(at = Time.now) at = at.midnight unless at.respond_to? :offset return nil if length == 0 return nil if at.to_date > endDate # Schedules end at 23:59 of the stored endDate at = startDate.midnight if at < startDate # This schedule hasn't started yet, skip to startDate # Next occurrence is later today # This is the only time the "time" actually matters; # after today, all we care about is the date if daysOfWeekArray[at.wday] and start >= at.offset open = at.midnight + start close = open + length return [open,close] end # We don't care about the time offset anymore, jump to the next midnight at = at.midnight + 1.day # NOTE This also has the added benefit of preventing an infinite loop # from occurring if +at+ gets shifted by 0.days further down. # Shift daysOfWeekArray so that +at+ is first element dow = daysOfWeekArray[at.wday..-1] + daysOfWeekArray[0..(at.wday-1)] # NOTE The above call does something a little quirky: # In the event that at.wday = 0, it concatenates the array with itself. # Since we are only interested in the first true value, this does not # cause a problem, but could probably be cleaned up if done so carefully. # Next day of the week this schedule is valid for (relative to current day) shift = dow.index(true) if shift # Skip forward at = at + shift.days else # Give up, there are no more occurrences # TODO Test edge case: valid for 1 day/week return nil end # Recurse to rerun the validation routines return next_times(at) end alias :to_times :next_times def to_xml(options) #super(params.merge({:only => [:id, :place_id], :methods => [ {:times => :next_times}, :start, :length, :startDate, :endDate ]})) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] - xml.place do + xml.tag!("operating-time".to_sym) do xml.id(self.id) xml.place_id(self.place_id) #xml.place_name(self.place.name) #xml.place_location(self.place.location) #xml.place_phone(self.place.phone) xml.details(self.details) - xml.tags(self.tag_list) + xml.tags do |xml| + self.tag_list.each do |tag| + xml.tag(tag) + end + end xml.start(self.start) xml.length(self.length) xml.daysOfWeek(self.daysOfWeek) xml.startDate(self.startDate) xml.endDate(self.endDate) xml.override(self.override) open,close = self.next_times(Date.today) if open.nil? or close.nil? xml.next_times(:for => Date.today) else xml.next_times(:for => Date.today) do |xml| xml.open(open.xmlschema) xml.close(close.xmlschema) end end end end ##### TODO DEPRECATED METHODS ##### def at @at end def at=(time) @opensAt = nil @closesAt = nil @at = time end # Returns a Time object representing the beginning of this OperatingTime def opensAt @opensAt ||= relativeTime.openTime(at) end def closesAt @closesAt ||= relativeTime.closeTime(at) end # Sets the beginning of this OperatingTime # Input: params = { :hour => 12, :minute => 45 } def opensAt=(time) if time.class == Time @opensAt = relativeTime.openTime = time else super end end # Sets the end of this OperatingTime def closesAt=(time) @closesAt = relativeTime.closeTime = time end def start read_attribute(:opensAt) end def start=(offset) write_attribute(:opensAt,offset) end # Returns a RelativeTime object representing this OperatingTime def relativeTime @relativeTime ||= RelativeTime.new(self, :opensAt, :length) end; protected :relativeTime # Backwards compatibility with old database schema # TODO GET RID OF THIS!!! def flags ( (override ? 1 : 0) << 7) | read_attribute(:daysOfWeek) end # FIXME Deprecated, use +override+ instead def special override end # Input: isSpecial = true/false # FIXME Deprecated, use +override=+ instead def special=(isSpecial) if isSpecial == true or isSpecial == "true" or isSpecial == 1 self.override = true elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 self.override = false end end end diff --git a/app/models/place.rb b/app/models/place.rb index d7373cb..b7cab2a 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,187 +1,192 @@ class Place < ActiveRecord::Base DEBUG = false has_many :operating_times acts_as_taggable_on :tags validates_presence_of :name def special_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 1}, :order => "startDate ASC, opensAt ASC" ) end def regular_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 0}, :order => "startDate ASC, opensAt ASC" ) end # Returns an array of Times representing the opening and closing times # of this Place between +startAt+ and +endAt+ def schedule(startAt,endAt) ## Caching ## @schedules ||= {} if @schedules[startAt.xmlschema] and @schedules[startAt.xmlschema][endAt.xmlschema] return @schedules[startAt.xmlschema][endAt.xmlschema] end ## End Caching ## # TODO Handle events starting within the range but ending outside of it? # TODO Offload this selection to the database; okay for testing though # Select all relevant times (1 day buffer on each end) # NOTE Make sure to use generous date comparisons to allow for midnight rollovers all_regular_operating_times = regular_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} all_special_operating_times = special_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} puts "\nRegular OperatingTimes: #{all_regular_operating_times.inspect}" if DEBUG puts "\nSpecial OperatingTimes: #{all_special_operating_times.inspect}" if DEBUG regular_times = [] special_times = [] special_ranges = [] all_special_operating_times.each do |ot| puts "\nSpecial Scheduling for: #{ot.inspect}" if DEBUG # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do if DEBUG puts "Open: #{open}" puts "Close: #{close}" puts "Start Date: #{ot.startDate} (#{ot.startDate.class})" puts "End Date: #{ot.endDate} (#{ot.endDate.class})" end if close < startAt # Skip forward to the first occurrance in our time range open,close = ot.next_times(close) next end special_times << [open,close] special_ranges << Range.new(ot.startDate,ot.endDate) open,close = ot.next_times(close) end end puts "\nSpecial Times: #{special_times.inspect}" if DEBUG puts "\nSpecial Ranges: #{special_ranges.inspect}" if DEBUG all_regular_operating_times.each do |ot| puts "\nRegular Scheduling for: #{ot.inspect}" if DEBUG # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do puts "Open: #{open}" if DEBUG puts "Close: #{close}" if DEBUG if close < startAt # Skip forward to the first occurrance in our time range open,close = ot.next_times(close) next end special_ranges.each do |sr| next if sr.member?(open) end regular_times << [open,close] open,close = ot.next_times(close) end end puts "\nRegular Times: #{regular_times.inspect}" if DEBUG # TODO Handle schedule overrides # TODO Handle combinations (i.e. part special, part regular) final_schedule = (regular_times+special_times).sort{|a,b|a[0] <=> b[0]} ## Caching ## @schedules ||= {} @schedules[startAt.xmlschema] ||= {} @schedules[startAt.xmlschema][endAt.xmlschema] = final_schedule ## End Caching ## final_schedule end def daySchedule(at = Date.today) at = at.to_date if at.class == Time or at.class == DateTime day_schedule = schedule(at.midnight,(at+1).midnight) #schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } #schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end =end day_schedule.sort{|a,b|a[0] <=> b[0]} end def currentSchedule(at = Time.now) puts "At(cS): #{at}" if DEBUG daySchedule(at).select { |open,close| puts "Open(cS): #{open}" if DEBUG puts "Close(cS): #{close}" if DEBUG open <= at and at <= close }[0] end def open?(at = Time.now) a = currentSchedule(at) return a ? true : false end alias :open :open? def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end - def to_xml(options) + def to_xml(options = {}) #super(options.merge({:only => [:id, :name, :location, :phone], :methods => [ :open, :daySchedule ] })) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] xml.place do xml.id(self.id) xml.name(self.name) xml.location(self.location) xml.phone(self.phone) + xml.tags do |xml| + self.tag_list.each do |tag| + xml.tag(tag) + end + end xml.open(self.open?) if daySchedule.nil? or daySchedule.empty? xml.daySchedule else xml.daySchedule(:for => Date.today) do |xml|; daySchedule.each do |open,close| xml.open(open.xmlschema) xml.close(close.xmlschema) end; end end end end end
michaelansel/dukenow
7e7e7232da93f0f5c1a871c0ecda41d1a5d46482
Add tagging capabilities to OperatingTime model (no specs)
diff --git a/app/models/operating_time.rb b/app/models/operating_time.rb index f45e00f..8d22e93 100644 --- a/app/models/operating_time.rb +++ b/app/models/operating_time.rb @@ -1,260 +1,284 @@ class OperatingTime < ActiveRecord::Base belongs_to :place + acts_as_taggable_on :operating_time_tags validates_presence_of :place_id, :endDate, :startDate validates_associated :place validate :end_after_start, :daysOfWeek_valid validate {|ot| 0 <= ot.length and ot.length <= 1.days } ## DaysOfWeek Constants ## SUNDAY = 0b00000001 MONDAY = 0b00000010 TUESDAY = 0b00000100 WEDNESDAY = 0b00001000 THURSDAY = 0b00010000 FRIDAY = 0b00100000 SATURDAY = 0b01000000 ALL_DAYS = (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) ## Validations ## def end_after_start if endDate < startDate errors.add_to_base("End date cannot preceed start date") end end def daysOfWeek_valid daysOfWeek == daysOfWeek & (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) end ## End Validations ## # TODO Is this OperatingTime applicable at +time+ def valid_at(time=Time.now) raise NotImplementedError end + # Tag Helpers + %w{tag_list tags tag_counts tag_ids tag_tagging_ids tag_taggings}.each do |m| [m,m+"="].each do |m| + if self.instance_methods.include?("operating_time_"+m) + definition = "" + definition += "def #{m}(" + definition += "arg" if self.instance_method("operating_time_"+m).arity == 1 + definition += "*args" if self.instance_method("operating_time_"+m).arity > 1 + definition += ")\n" + definition += "operating_time_#{m}(" + definition += "arg" if self.instance_method("operating_time_"+m).arity == 1 + definition += "*args" if self.instance_method("operating_time_"+m).arity > 1 + definition += ")\n" + definition += "end" + + self.class_eval(definition) + end + end ; end + def tags_from ; operating_time_tags_from ; end + def override read_attribute(:override) == 1 end def override=(mode) if mode == true or mode == "true" or mode == 1 write_attribute(:override, true) elsif mode == false or mode == "false" or mode == 0 write_attribute(:override, false) else raise ArgumentError, "Invalid override value (#{mode.inspect}); Accepts true/false, 1/0" end end def daysOfWeek=(newDow) if not ( newDow & ALL_DAYS == newDow ) # Invalid input raise ArgumentError, "Not a valid value for daysOfWeek (#{newDow.inspect})" end write_attribute(:daysOfWeek, newDow & ALL_DAYS) @daysOfWeekHash = nil @daysOfWeekArray = nil @daysOfWeekString = nil end ## daysOfWeek Helper/Accessors ## # Hash mapping day of week (Symbol) to valid(true)/invalid(false) def daysOfWeekHash @daysOfWeekHash ||= { :sunday => (daysOfWeek & SUNDAY ) > 0, :monday => (daysOfWeek & MONDAY ) > 0, :tuesday => (daysOfWeek & TUESDAY ) > 0, :wednesday => (daysOfWeek & WEDNESDAY ) > 0, :thursday => (daysOfWeek & THURSDAY ) > 0, :friday => (daysOfWeek & FRIDAY ) > 0, :saturday => (daysOfWeek & SATURDAY ) > 0 } end # Array beginning with Sunday of valid(true)/inactive(false) values def daysOfWeekArray dow = daysOfWeekHash @daysOfWeekArray ||= [ dow[:sunday], dow[:monday], dow[:tuesday], dow[:wednesday], dow[:thursday], dow[:friday], dow[:saturday] ] end # Human-readable string of applicable days of week def daysOfWeekString dow = daysOfWeekHash @daysOfWeekString ||= (dow[:sunday] ? "Su" : "") + (dow[:monday] ? "M" : "") + (dow[:tuesday] ? "Tu" : "") + (dow[:wednesday] ? "W" : "") + (dow[:thursday] ? "Th" : "") + (dow[:friday] ? "F" : "") + (dow[:saturday] ? "Sa" : "") end ## End daysOfWeek Helper/Accessors ## # Returns the next full occurrence of these operating time rule. # If we are currently within a valid time range, it will look forward for the # <em>next</em> opening time def next_times(at = Time.now) at = at.midnight unless at.respond_to? :offset return nil if length == 0 return nil if at.to_date > endDate # Schedules end at 23:59 of the stored endDate at = startDate.midnight if at < startDate # This schedule hasn't started yet, skip to startDate # Next occurrence is later today # This is the only time the "time" actually matters; # after today, all we care about is the date if daysOfWeekArray[at.wday] and start >= at.offset open = at.midnight + start close = open + length return [open,close] end # We don't care about the time offset anymore, jump to the next midnight at = at.midnight + 1.day # NOTE This also has the added benefit of preventing an infinite loop # from occurring if +at+ gets shifted by 0.days further down. # Shift daysOfWeekArray so that +at+ is first element dow = daysOfWeekArray[at.wday..-1] + daysOfWeekArray[0..(at.wday-1)] # NOTE The above call does something a little quirky: # In the event that at.wday = 0, it concatenates the array with itself. # Since we are only interested in the first true value, this does not # cause a problem, but could probably be cleaned up if done so carefully. # Next day of the week this schedule is valid for (relative to current day) shift = dow.index(true) if shift # Skip forward at = at + shift.days else # Give up, there are no more occurrences # TODO Test edge case: valid for 1 day/week return nil end # Recurse to rerun the validation routines return next_times(at) end alias :to_times :next_times def to_xml(options) #super(params.merge({:only => [:id, :place_id], :methods => [ {:times => :next_times}, :start, :length, :startDate, :endDate ]})) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] xml.place do xml.id(self.id) xml.place_id(self.place_id) #xml.place_name(self.place.name) #xml.place_location(self.place.location) #xml.place_phone(self.place.phone) + xml.details(self.details) + xml.tags(self.tag_list) xml.start(self.start) xml.length(self.length) + xml.daysOfWeek(self.daysOfWeek) xml.startDate(self.startDate) xml.endDate(self.endDate) + xml.override(self.override) open,close = self.next_times(Date.today) if open.nil? or close.nil? xml.next_times(:for => Date.today) else xml.next_times(:for => Date.today) do |xml| xml.open(open.xmlschema) xml.close(close.xmlschema) end end end end ##### TODO DEPRECATED METHODS ##### def at @at end def at=(time) @opensAt = nil @closesAt = nil @at = time end # Returns a Time object representing the beginning of this OperatingTime def opensAt @opensAt ||= relativeTime.openTime(at) end def closesAt @closesAt ||= relativeTime.closeTime(at) end # Sets the beginning of this OperatingTime # Input: params = { :hour => 12, :minute => 45 } def opensAt=(time) if time.class == Time @opensAt = relativeTime.openTime = time else super end end # Sets the end of this OperatingTime def closesAt=(time) @closesAt = relativeTime.closeTime = time end def start read_attribute(:opensAt) end def start=(offset) write_attribute(:opensAt,offset) end # Returns a RelativeTime object representing this OperatingTime def relativeTime @relativeTime ||= RelativeTime.new(self, :opensAt, :length) end; protected :relativeTime # Backwards compatibility with old database schema # TODO GET RID OF THIS!!! def flags ( (override ? 1 : 0) << 7) | read_attribute(:daysOfWeek) end # FIXME Deprecated, use +override+ instead def special override end # Input: isSpecial = true/false # FIXME Deprecated, use +override=+ instead def special=(isSpecial) if isSpecial == true or isSpecial == "true" or isSpecial == 1 self.override = true elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 self.override = false end end end diff --git a/db/migrate/20090706033509_operating_time_tags.rb b/db/migrate/20090706033509_operating_time_tags.rb new file mode 100644 index 0000000..771c860 --- /dev/null +++ b/db/migrate/20090706033509_operating_time_tags.rb @@ -0,0 +1,29 @@ +class OperatingTimeTags < ActiveRecord::Migration + def self.up + create_table :operating_time_tags do |t| + t.column :name, :string + end + + create_table :operating_time_taggings do |t| + t.column :tag_id, :integer + t.column :taggable_id, :integer + t.column :tagger_id, :integer + t.column :tagger_type, :string + + # You should make sure that the column created is + # long enough to store the required class names. + t.column :taggable_type, :string + t.column :context, :string + + t.column :created_at, :datetime + end + + add_index :operating_time_taggings, :tag_id + add_index :operating_time_taggings, [:taggable_id, :taggable_type, :context] + end + + def self.down + drop_table :operating_time_taggings + drop_table :operating_time_tags + end +end diff --git a/db/schema.rb b/db/schema.rb index 3967d72..99c2c03 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,80 +1,97 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20090629201611) do +ActiveRecord::Schema.define(:version => 20090706033509) do create_table "eateries", :force => true do |t| t.string "name" t.string "location" t.string "phone" t.datetime "created_at" t.datetime "updated_at" end + create_table "operating_time_taggings", :force => true do |t| + t.integer "tag_id" + t.integer "taggable_id" + t.integer "tagger_id" + t.string "tagger_type" + t.string "taggable_type" + t.string "context" + t.datetime "created_at" + end + + add_index "operating_time_taggings", ["tag_id"], :name => "index_operating_time_taggings_on_tag_id" + add_index "operating_time_taggings", ["taggable_id", "taggable_type", "context"], :name => "index_operating_time_taggings_on_taggable_id_and_taggable_type_and_context" + + create_table "operating_time_tags", :force => true do |t| + t.string "name" + end + create_table "operating_times", :force => true do |t| t.integer "place_id" t.integer "opensAt" t.integer "length" t.text "details" t.date "startDate" t.date "endDate" t.datetime "created_at" t.datetime "updated_at" t.integer "override", :default => 0, :null => false t.integer "daysOfWeek", :default => 0, :null => false end create_table "places", :force => true do |t| t.string "name" t.string "location" t.string "phone" t.datetime "created_at" t.datetime "updated_at" end create_table "regular_operating_times", :force => true do |t| t.integer "eatery_id" t.integer "opensAt" t.integer "closesAt" t.integer "daysOfWeek" t.datetime "created_at" t.datetime "updated_at" end create_table "special_operating_times", :force => true do |t| t.integer "eatery_id" t.integer "opensAt" t.integer "closesAt" t.integer "daysOfWeek" t.date "start" t.date "end" t.datetime "created_at" t.datetime "updated_at" end create_table "taggings", :force => true do |t| t.integer "tag_id" t.integer "taggable_id" t.integer "tagger_id" t.string "tagger_type" t.string "taggable_type" t.string "context" t.datetime "created_at" end add_index "taggings", ["tag_id"], :name => "index_taggings_on_tag_id" add_index "taggings", ["taggable_id", "taggable_type", "context"], :name => "index_taggings_on_taggable_id_and_taggable_type_and_context" create_table "tags", :force => true do |t| t.string "name" end end diff --git a/spec/models/operating_time_spec.rb b/spec/models/operating_time_spec.rb index 3e7c4da..6ce4834 100644 --- a/spec/models/operating_time_spec.rb +++ b/spec/models/operating_time_spec.rb @@ -1,208 +1,209 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe OperatingTime do before(:each) do @place = mock_model(Place) @valid_attributes = { :place_id => @place.id, :start => (Time.now - 1.hours).to_i, :length => 2.hours, :daysOfWeek => OperatingTime::ALL_DAYS, :startDate => Date.yesterday, :endDate => Date.tomorrow, :override => false } @operating_time = OperatingTime.create!(@valid_attributes) end it "should create a new instance given all valid attributes" do OperatingTime.create!(@valid_attributes) end describe "missing required attributes" do it "should not create a new instance without a valid start time" it "should not create a new instance without a valid length" it "should not create a new instance without a valid Place reference" it "should not create a new instance without a valid start date" it "should not create a new instance without a valid end date" end describe "missing default-able attributes" do it "should default daysOfWeek to 0" do @valid_attributes.delete(:daysOfWeek) if @valid_attributes[:daysOfWeek] OperatingTime.create!(@valid_attributes).daysOfWeek.should == 0 end it "should default override to false" do @valid_attributes.delete(:override) if @valid_attributes[:override] OperatingTime.create!(@valid_attributes).override.should == false end end describe "given invalid attributes" do def create @operating_time = OperatingTime.create!(@valid_attributes) end =begin it "should create a new instance, but ignore an invalid override value" do @valid_attributes[:override] = "invalid" create @operating_time.override.should == false # where false is the default value @valid_attributes[:override] = 10 create @operating_time.override.should == false # where false is the default value end it "should create a new instance, but ignore an invalid daysOfWeek value" do @valid_attributes[:daysOfWeek] = 1000 create @operating_time.daysOfWeek.should == 0 # where 0 is the default value end =end it "should not create a new instance with an invalid start time" it "should not create a new instance with an invalid length" it "should not create a new instance with an invalid Place reference" it "should not create a new instance with an invalid start date" it "should not create a new instance with an invalid end date" end it "should enable override mode" do @operating_time.should_receive(:write_attribute).with(:override, true).exactly(3).times @operating_time.override = true @operating_time.override = "true" @operating_time.override = 1 end it "should disable override mode" do @operating_time.should_receive(:write_attribute).with(:override, false).exactly(3).times @operating_time.override = false @operating_time.override = "false" @operating_time.override = 0 end it "should complain about invalid override values, but not change the value" do @operating_time.override = true @operating_time.override.should == true #TODO Should nil be ignored or errored? lambda { @operating_time.override = nil }.should raise_error(ArgumentError) @operating_time.override.should == true lambda { @operating_time.override = "invalid" }.should raise_error(ArgumentError) @operating_time.override.should == true lambda { @operating_time.override = false }.should_not raise_error @operating_time.override.should == false end it "should complain about invalid daysOfWeek values, but not change the value" do @operating_time.daysOfWeek = OperatingTime::SUNDAY @operating_time.daysOfWeek.should == OperatingTime::SUNDAY #TODO Should nil be ignored or errored? lambda { @operating_time.daysOfWeek = nil }.should raise_error(ArgumentError) @operating_time.daysOfWeek.should == OperatingTime::SUNDAY lambda { @operating_time.daysOfWeek = 200 }.should raise_error(ArgumentError) @operating_time.daysOfWeek.should == OperatingTime::SUNDAY lambda { @operating_time.daysOfWeek= OperatingTime::MONDAY }.should_not raise_error @operating_time.daysOfWeek.should == OperatingTime::MONDAY end describe "with open and close times" do before(:each) do @now = Time.now.midnight + 15.minutes @open = @now.midnight + 23.hours + 30.minutes @close = @open + 1.hour start = @open - @open.midnight length = @close - @open @valid_attributes.update({ :start => start, :length => length }) @operating_time = OperatingTime.create!(@valid_attributes) end it "should return valid open and close times for 'now'" do + Time.stub(:now).and_return(@now) open,close = @operating_time.next_times() open.to_s.should == @open.to_s close.to_s.should == @close.to_s end it "should return valid open and close times for a given time" do @open, @close, @now = [@open,@close,@now].collect{|t| t + 5.days} @operating_time.endDate += 5 open,close = @operating_time.next_times( @now ) open.to_s.should == @open.to_s close.to_s.should == @close.to_s end it "should return valid open/close times if open past midnight, but ending today" do @operating_time.endDate = @now.to_date open = @now.midnight + @operating_time.start close = open + @operating_time.length - open,close = @operating_time.next_times() + open,close = @operating_time.next_times(@now) close.should > (@now.to_date + 1).midnight open.to_s.should == @open.to_s close.to_s.should == @close.to_s end it "should return valid open/close times if open one day per week" do @operating_time.endDate = @now.to_date + 21 open = @now.midnight pending("Look at next_times daysOfWeek array shifting") end end end ### Midnight Module Specs ### describe Date do before(:each) do @date = Date.today end it "should have a valid midnight" do @date.should respond_to(:midnight) @date.midnight.should == Time.mktime(@date.year, @date.month, @date.day, 0, 0, 0) end end describe Time do before(:each) do @time = Time.now end it "should have a valid midnight" do @time.should respond_to(:midnight) @time.midnight.should == Time.mktime(@time.year, @time.month, @time.day, 0, 0, 0) end it "should have a valid midnight offset" do @time.should respond_to(:offset) @time.offset.should == @time.hour.hours + @time.min.minutes + @time.sec end end describe DateTime do before(:each) do @dt = DateTime.now end it "should have a valid midnight" do @dt.should respond_to(:midnight) @dt.midnight.should == Time.mktime(@dt.year, @dt.month, @dt.day, 0, 0, 0) end end ### End Midnight Module Specs ### diff --git a/spec/models/schedules.rb b/spec/models/schedules.rb index fa2cf70..dfed43d 100644 --- a/spec/models/schedules.rb +++ b/spec/models/schedules.rb @@ -1,381 +1,380 @@ ###################### ##### Scheduling ##### ###################### describe "a Place with scheduling capabilities", :shared => true do before(:each) do add_scheduling_spec_helpers(@place) end validate_setup do before(:each) do @place.build end end it "should be clean" do @place.regular_operating_times.should == [] @place.special_operating_times.should == [] @place.constraints.should == [] @place.times.should == [] end in_order_to "be open now" do before(:each) do @place.add_times([ {:start => 6.hours, :length => 2.hours, :override => false}, {:start => 6.hours, :length => 2.hours, :override => true} ]) @at = (@at || Time.now).midnight + 7.hours end it "should have operating times" do @place.build(@at) @place.operating_times.should_not be_empty end it "should have a schedule" do @place.build(@at) @place.schedule(@at.midnight, @at.midnight + 1.day).should_not be_empty end it "should have a daySchedule" do @place.build(@at) @place.daySchedule(@at).should_not be_empty end it "should have a currentSchedule" do @place.build(@at) @place.currentSchedule(@at).should_not be_nil end it "should be open on Sunday" do @at = @at - @at.wday.days # Set to previous Sunday @place.rebuild @place.open(@at).should == true end it "should be open on Wednesday" do @at = @at - @at.wday.days + 3.days # Set to Wednesday after last Sunday @place.rebuild(@at) begin @place.open(@at).should == true rescue Exception => e puts "" puts "At: #{@at}" puts "Times: #{@place.times.inspect}" puts "OperatingTimes: #{@place.operating_times.inspect}" puts "daySchedule: #{@place.daySchedule(@at)}" raise e end end it "should be open on Saturday" do @at = @at - @at.wday.days + 6.days# Set to Saturday after last Sunday @place.rebuild(@at) @place.open(@at).should == true end it "should be open on only one day every week" do @at = @at - @at.wday.days + 6.days# Set to Saturday after last Sunday @place.times.each do |t| t[:daysOfWeek] = OperatingTime::SATURDAY t[:startDate] = @at.to_date - 2.days t[:endDate] = @at.to_date + 3.weeks end @place.rebuild(@at) - puts @place.schedule(@at-1.day, @at+15.days).inspect @place.schedule(@at-1.day, @at+15.days).should have(3).times @place.schedule(@at-1.day, @at+15.days).collect{|a,b|[a.xmlschema,b.xmlschema]}.uniq.should have(3).unique_times end end in_order_to "be open 24 hours" do before(:each) do @place.add_times([ {:start => 0, :length => 24.hours, :override => false}, {:start => 0, :length => 24.hours, :override => true} ]) @at = (@at || Time.now).midnight + 12.hours @place.build(@at) end it "should be open during the day" do @place.open(@at).should == true end it "should be open at midnight" do @place.open(@at.midnight).should == true end end in_order_to "be open later in the day" do before(:each) do @place.add_times([ {:start => 16.hours, :length => 2.hours, :override => false}, {:start => 16.hours, :length => 2.hours, :override => true} ]) @at = (@at || Time.now).midnight + 12.hours @place.build(@at) end it "should be closed now" do @place.open(@at).should == false end it "should have a schedule later in the day" do @place.schedule(@at,@at.midnight + 24.hours).should_not be_empty end it "should not have a schedule earlier in the day" do @place.schedule(@at.midnight,@at).should be_empty end end in_order_to "be closed for the day" do before(:each) do @place.add_times([ {:start => 4.hours, :length => 2.hours, :override => false}, {:start => 4.hours, :length => 2.hours, :override => true} ]) @at = (@at || Time.now).midnight + 12.hours @place.build(@at) end it "should be closed now" do @place.open(@at).should == false end it "should have a schedule earlier in the day" do @place.schedule(@at.midnight,@at).should_not be_empty end it "should not have a schedule later in the day" do @place.schedule(@at, @at.midnight + 24.hours).should be_empty end end in_order_to "be open past midnight" do before(:each) do @at = (@at || Time.now).midnight + 12.hours @place.add_times([ {:start => 23.hours, :length => 4.hours, :override => true}, {:start => 23.hours, :length => 4.hours, :override => false} ]) @place.times.each do |t| t[:startDate] = @at.to_date t[:endDate] = @at.to_date end @place.build(@at) end it "should be open early the next morning" do @place.open(@at.midnight + 1.days + 2.hours).should == true end it "should not be open early that morning" do @place.open(@at.midnight + 2.hours).should == false end it "should not be open late the next night" do @place.open(@at.midnight + 2.days + 2.hours).should == false end end in_order_to "be closed now" do before(:each) do @place.add_constraint {|t| ( t[:start] > @at.offset ) or ( (t[:start] + t[:length]) < @at.offset ) } @place.add_times([ {:start => 6.hours, :length => 2.hours, :override => false}, {:start => 6.hours, :length => 2.hours, :override => true} ]) @at = Time.now.midnight + 12.hours @place.build end it "should be closed" do @place.open(@at).should == false end end in_order_to "be closed all day" do before(:each) do @at ||= Time.now @place.add_times([ {:start => 0, :length => 0, :startDate => @at.to_date, :endDate => @at.to_date, :override => false}, {:start => 0, :length => 0, :startDate => @at.to_date, :endDate => @at.to_date, :override => true} ]) @place.build(@at) end it "should be closed now" do @place.open(@at).should == false end it "should not have a schedule earlier in the day" do @place.schedule(@at.midnight,@at).should be_empty end it "should not have a schedule later in the day" do @place.schedule(@at, @at.midnight + 24.hours).should be_empty end it "should not have a schedule at all for the day" do @place.daySchedule(@at).should be_empty end end in_order_to "have a valid schedule" do it "should not have any overlapping times" it "should have all times within the specified time range" end end describe "a Place with valid times", :shared => true do describe "with only regular times" do before(:each) do @place.add_constraint {|t| t[:override] == false } @place.build end validate_setup do it "should have regular times" do #puts "Regular Times: #{@place.regular_operating_times.inspect}" @place.regular_operating_times.should_not be_empty end it "should not have any special times" do #puts "Special Times: #{@place.special_operating_times.inspect}" @place.special_operating_times.should be_empty end end it_can "be open now" it_can "be open 24 hours" it_can "be open past midnight" it_can "be open later in the day" it_can "be closed for the day" it_can "be closed now" it_can "be closed all day" end describe "with only special times" do before(:each) do @place.add_constraint {|t| t[:override] == true } @place.build end validate_setup do it "should not have regular times" do @place.regular_operating_times.should be_empty end it "should have special times" do @place.special_operating_times.should_not be_empty end end it_can "be open now" it_can "be open 24 hours" it_can "be open past midnight" it_can "be open later in the day" it_can "be closed for the day" it_can "be closed now" it_can "be closed all day" end describe "with regular and special times" do validate_setup do it "should have regular times" do @place.regular_operating_times.should_not be_empty end it "should have special times" do @place.special_operating_times.should_not be_empty end end describe "where the special times are overriding the regular times" do #it_can "be open now" #it_can "be open 24 hours" #it_can "be open past midnight" #it_can "be open later in the day" #it_can "be closed for the day" #it_can "be closed now" #it_can "be closed all day" end describe "where the special times are not overriding the regular times" do #it_can "be open now" #it_can "be open 24 hours" #it_can "be open past midnight" #it_can "be open later in the day" #it_can "be closed for the day" #it_can "be closed now" #it_can "be closed all day" end end describe "with special times" do describe "extending normal hours" do #it_can "be open now" #it_can "be open 24 hours" #it_can "be open past midnight" #it_can "be open later in the day" #it_can "be closed for the day" #it_can "be closed now" #it_can "be closed all day" end describe "reducing normal hours" do #it_can "be open now" #it_can "be open 24 hours" #it_can "be open past midnight" #it_can "be open later in the day" #it_can "be closed for the day" #it_can "be closed now" #it_can "be closed all day" end describe "removing all hours" do #it_can "be open now" #it_can "be open 24 hours" #it_can "be open past midnight" #it_can "be open later in the day" #it_can "be closed for the day" #it_can "be closed now" #it_can "be closed all day" end describe "moving normal hours (extending and reducing)" do #it_can "be open now" #it_can "be open 24 hours" #it_can "be open past midnight" #it_can "be open later in the day" #it_can "be closed for the day" #it_can "be closed now" #it_can "be closed all day" end end end
michaelansel/dukenow
961067d11b860b90d61f87c251dafdce06a3da94
Bugfix that was causing an infinite loop in OperatingTime.next_times
diff --git a/app/models/operating_time.rb b/app/models/operating_time.rb index 18af8a4..f45e00f 100644 --- a/app/models/operating_time.rb +++ b/app/models/operating_time.rb @@ -1,260 +1,260 @@ class OperatingTime < ActiveRecord::Base belongs_to :place validates_presence_of :place_id, :endDate, :startDate validates_associated :place validate :end_after_start, :daysOfWeek_valid validate {|ot| 0 <= ot.length and ot.length <= 1.days } ## DaysOfWeek Constants ## SUNDAY = 0b00000001 MONDAY = 0b00000010 TUESDAY = 0b00000100 WEDNESDAY = 0b00001000 THURSDAY = 0b00010000 FRIDAY = 0b00100000 SATURDAY = 0b01000000 ALL_DAYS = (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) ## Validations ## def end_after_start if endDate < startDate errors.add_to_base("End date cannot preceed start date") end end def daysOfWeek_valid daysOfWeek == daysOfWeek & (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) end ## End Validations ## # TODO Is this OperatingTime applicable at +time+ def valid_at(time=Time.now) raise NotImplementedError end def override read_attribute(:override) == 1 end def override=(mode) if mode == true or mode == "true" or mode == 1 write_attribute(:override, true) elsif mode == false or mode == "false" or mode == 0 write_attribute(:override, false) else raise ArgumentError, "Invalid override value (#{mode.inspect}); Accepts true/false, 1/0" end end def daysOfWeek=(newDow) if not ( newDow & ALL_DAYS == newDow ) # Invalid input raise ArgumentError, "Not a valid value for daysOfWeek (#{newDow.inspect})" end write_attribute(:daysOfWeek, newDow & ALL_DAYS) @daysOfWeekHash = nil @daysOfWeekArray = nil @daysOfWeekString = nil end ## daysOfWeek Helper/Accessors ## # Hash mapping day of week (Symbol) to valid(true)/invalid(false) def daysOfWeekHash @daysOfWeekHash ||= { :sunday => (daysOfWeek & SUNDAY ) > 0, :monday => (daysOfWeek & MONDAY ) > 0, :tuesday => (daysOfWeek & TUESDAY ) > 0, :wednesday => (daysOfWeek & WEDNESDAY ) > 0, :thursday => (daysOfWeek & THURSDAY ) > 0, :friday => (daysOfWeek & FRIDAY ) > 0, :saturday => (daysOfWeek & SATURDAY ) > 0 } end # Array beginning with Sunday of valid(true)/inactive(false) values def daysOfWeekArray dow = daysOfWeekHash @daysOfWeekArray ||= [ dow[:sunday], dow[:monday], dow[:tuesday], dow[:wednesday], dow[:thursday], dow[:friday], dow[:saturday] ] end # Human-readable string of applicable days of week def daysOfWeekString dow = daysOfWeekHash @daysOfWeekString ||= (dow[:sunday] ? "Su" : "") + (dow[:monday] ? "M" : "") + (dow[:tuesday] ? "Tu" : "") + (dow[:wednesday] ? "W" : "") + (dow[:thursday] ? "Th" : "") + (dow[:friday] ? "F" : "") + (dow[:saturday] ? "Sa" : "") end ## End daysOfWeek Helper/Accessors ## # Returns the next full occurrence of these operating time rule. # If we are currently within a valid time range, it will look forward for the # <em>next</em> opening time def next_times(at = Time.now) - at = at.midnight unless respond_to? :offset + at = at.midnight unless at.respond_to? :offset return nil if length == 0 return nil if at.to_date > endDate # Schedules end at 23:59 of the stored endDate at = startDate.midnight if at < startDate # This schedule hasn't started yet, skip to startDate # Next occurrence is later today # This is the only time the "time" actually matters; # after today, all we care about is the date if daysOfWeekArray[at.wday] and start >= at.offset open = at.midnight + start close = open + length return [open,close] end # We don't care about the time offset anymore, jump to the next midnight at = at.midnight + 1.day # NOTE This also has the added benefit of preventing an infinite loop # from occurring if +at+ gets shifted by 0.days further down. # Shift daysOfWeekArray so that +at+ is first element dow = daysOfWeekArray[at.wday..-1] + daysOfWeekArray[0..(at.wday-1)] # NOTE The above call does something a little quirky: # In the event that at.wday = 0, it concatenates the array with itself. # Since we are only interested in the first true value, this does not # cause a problem, but could probably be cleaned up if done so carefully. # Next day of the week this schedule is valid for (relative to current day) shift = dow.index(true) if shift # Skip forward at = at + shift.days else # Give up, there are no more occurrences # TODO Test edge case: valid for 1 day/week return nil end # Recurse to rerun the validation routines return next_times(at) end alias :to_times :next_times def to_xml(options) #super(params.merge({:only => [:id, :place_id], :methods => [ {:times => :next_times}, :start, :length, :startDate, :endDate ]})) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] xml.place do xml.id(self.id) xml.place_id(self.place_id) #xml.place_name(self.place.name) #xml.place_location(self.place.location) #xml.place_phone(self.place.phone) xml.start(self.start) xml.length(self.length) xml.startDate(self.startDate) xml.endDate(self.endDate) open,close = self.next_times(Date.today) if open.nil? or close.nil? xml.next_times(:for => Date.today) else xml.next_times(:for => Date.today) do |xml| xml.open(open.xmlschema) xml.close(close.xmlschema) end end end end ##### TODO DEPRECATED METHODS ##### def at @at end def at=(time) @opensAt = nil @closesAt = nil @at = time end # Returns a Time object representing the beginning of this OperatingTime def opensAt @opensAt ||= relativeTime.openTime(at) end def closesAt @closesAt ||= relativeTime.closeTime(at) end # Sets the beginning of this OperatingTime # Input: params = { :hour => 12, :minute => 45 } def opensAt=(time) if time.class == Time @opensAt = relativeTime.openTime = time else super end end # Sets the end of this OperatingTime def closesAt=(time) @closesAt = relativeTime.closeTime = time end def start read_attribute(:opensAt) end def start=(offset) write_attribute(:opensAt,offset) end # Returns a RelativeTime object representing this OperatingTime def relativeTime @relativeTime ||= RelativeTime.new(self, :opensAt, :length) end; protected :relativeTime # Backwards compatibility with old database schema # TODO GET RID OF THIS!!! def flags ( (override ? 1 : 0) << 7) | read_attribute(:daysOfWeek) end # FIXME Deprecated, use +override+ instead def special override end # Input: isSpecial = true/false # FIXME Deprecated, use +override=+ instead def special=(isSpecial) if isSpecial == true or isSpecial == "true" or isSpecial == 1 self.override = true elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 self.override = false end end end
michaelansel/dukenow
401a0688d40e5dda5234821ba7738a7ea37c813d
Customize XML builders; Add schedule caching
diff --git a/app/models/operating_time.rb b/app/models/operating_time.rb index 55232c3..18af8a4 100644 --- a/app/models/operating_time.rb +++ b/app/models/operating_time.rb @@ -1,226 +1,260 @@ class OperatingTime < ActiveRecord::Base belongs_to :place validates_presence_of :place_id, :endDate, :startDate validates_associated :place validate :end_after_start, :daysOfWeek_valid validate {|ot| 0 <= ot.length and ot.length <= 1.days } ## DaysOfWeek Constants ## SUNDAY = 0b00000001 MONDAY = 0b00000010 TUESDAY = 0b00000100 WEDNESDAY = 0b00001000 THURSDAY = 0b00010000 FRIDAY = 0b00100000 SATURDAY = 0b01000000 ALL_DAYS = (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) ## Validations ## def end_after_start if endDate < startDate errors.add_to_base("End date cannot preceed start date") end end def daysOfWeek_valid daysOfWeek == daysOfWeek & (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) end ## End Validations ## # TODO Is this OperatingTime applicable at +time+ def valid_at(time=Time.now) raise NotImplementedError end def override read_attribute(:override) == 1 end def override=(mode) if mode == true or mode == "true" or mode == 1 write_attribute(:override, true) elsif mode == false or mode == "false" or mode == 0 write_attribute(:override, false) else raise ArgumentError, "Invalid override value (#{mode.inspect}); Accepts true/false, 1/0" end end def daysOfWeek=(newDow) if not ( newDow & ALL_DAYS == newDow ) # Invalid input raise ArgumentError, "Not a valid value for daysOfWeek (#{newDow.inspect})" end write_attribute(:daysOfWeek, newDow & ALL_DAYS) @daysOfWeekHash = nil @daysOfWeekArray = nil @daysOfWeekString = nil end ## daysOfWeek Helper/Accessors ## # Hash mapping day of week (Symbol) to valid(true)/invalid(false) def daysOfWeekHash @daysOfWeekHash ||= { :sunday => (daysOfWeek & SUNDAY ) > 0, :monday => (daysOfWeek & MONDAY ) > 0, :tuesday => (daysOfWeek & TUESDAY ) > 0, :wednesday => (daysOfWeek & WEDNESDAY ) > 0, :thursday => (daysOfWeek & THURSDAY ) > 0, :friday => (daysOfWeek & FRIDAY ) > 0, :saturday => (daysOfWeek & SATURDAY ) > 0 } end # Array beginning with Sunday of valid(true)/inactive(false) values def daysOfWeekArray dow = daysOfWeekHash @daysOfWeekArray ||= [ dow[:sunday], dow[:monday], dow[:tuesday], dow[:wednesday], dow[:thursday], dow[:friday], dow[:saturday] ] end # Human-readable string of applicable days of week def daysOfWeekString dow = daysOfWeekHash @daysOfWeekString ||= (dow[:sunday] ? "Su" : "") + (dow[:monday] ? "M" : "") + (dow[:tuesday] ? "Tu" : "") + (dow[:wednesday] ? "W" : "") + (dow[:thursday] ? "Th" : "") + (dow[:friday] ? "F" : "") + (dow[:saturday] ? "Sa" : "") end ## End daysOfWeek Helper/Accessors ## - def to_xml(params) - super(params.merge({:only => [:id, :place_id, :flags], :methods => [ :opensAt, :closesAt, :startDate, :endDate ]})) - end - - # Returns the next full occurrence of these operating time rule. # If we are currently within a valid time range, it will look forward for the # <em>next</em> opening time def next_times(at = Time.now) + at = at.midnight unless respond_to? :offset return nil if length == 0 return nil if at.to_date > endDate # Schedules end at 23:59 of the stored endDate at = startDate.midnight if at < startDate # This schedule hasn't started yet, skip to startDate # Next occurrence is later today # This is the only time the "time" actually matters; # after today, all we care about is the date if daysOfWeekArray[at.wday] and start >= at.offset open = at.midnight + start close = open + length return [open,close] end # We don't care about the time offset anymore, jump to the next midnight at = at.midnight + 1.day + # NOTE This also has the added benefit of preventing an infinite loop + # from occurring if +at+ gets shifted by 0.days further down. - # TODO Test for Sun, Sat, and one of M-F - dow = daysOfWeekArray[at.wday..-1] + daysOfWeekArray[0..at.wday] + # Shift daysOfWeekArray so that +at+ is first element + dow = daysOfWeekArray[at.wday..-1] + daysOfWeekArray[0..(at.wday-1)] + # NOTE The above call does something a little quirky: + # In the event that at.wday = 0, it concatenates the array with itself. + # Since we are only interested in the first true value, this does not + # cause a problem, but could probably be cleaned up if done so carefully. - # Next day of the week this schedule is valid for + # Next day of the week this schedule is valid for (relative to current day) shift = dow.index(true) if shift # Skip forward at = at + shift.days else # Give up, there are no more occurrences # TODO Test edge case: valid for 1 day/week return nil end # Recurse to rerun the validation routines return next_times(at) end alias :to_times :next_times + def to_xml(options) + #super(params.merge({:only => [:id, :place_id], :methods => [ {:times => :next_times}, :start, :length, :startDate, :endDate ]})) + options[:indent] ||= 2 + xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) + xml.instruct! unless options[:skip_instruct] + xml.place do + + xml.id(self.id) + xml.place_id(self.place_id) + #xml.place_name(self.place.name) + #xml.place_location(self.place.location) + #xml.place_phone(self.place.phone) + + xml.start(self.start) + xml.length(self.length) + xml.startDate(self.startDate) + xml.endDate(self.endDate) + + open,close = self.next_times(Date.today) + if open.nil? or close.nil? + xml.next_times(:for => Date.today) + else + xml.next_times(:for => Date.today) do |xml| + xml.open(open.xmlschema) + xml.close(close.xmlschema) + end + end + + end + end + + ##### TODO DEPRECATED METHODS ##### def at @at end def at=(time) @opensAt = nil @closesAt = nil @at = time end # Returns a Time object representing the beginning of this OperatingTime def opensAt @opensAt ||= relativeTime.openTime(at) end def closesAt @closesAt ||= relativeTime.closeTime(at) end # Sets the beginning of this OperatingTime # Input: params = { :hour => 12, :minute => 45 } def opensAt=(time) if time.class == Time @opensAt = relativeTime.openTime = time else super end end # Sets the end of this OperatingTime def closesAt=(time) @closesAt = relativeTime.closeTime = time end def start read_attribute(:opensAt) end def start=(offset) write_attribute(:opensAt,offset) end # Returns a RelativeTime object representing this OperatingTime def relativeTime @relativeTime ||= RelativeTime.new(self, :opensAt, :length) end; protected :relativeTime # Backwards compatibility with old database schema # TODO GET RID OF THIS!!! def flags ( (override ? 1 : 0) << 7) | read_attribute(:daysOfWeek) end # FIXME Deprecated, use +override+ instead def special override end # Input: isSpecial = true/false # FIXME Deprecated, use +override=+ instead def special=(isSpecial) if isSpecial == true or isSpecial == "true" or isSpecial == 1 self.override = true elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 self.override = false end end end diff --git a/app/models/place.rb b/app/models/place.rb index 1cb793a..d7373cb 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,151 +1,187 @@ class Place < ActiveRecord::Base DEBUG = false has_many :operating_times acts_as_taggable_on :tags validates_presence_of :name def special_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 1}, :order => "startDate ASC, opensAt ASC" ) end def regular_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 0}, :order => "startDate ASC, opensAt ASC" ) end - # Returns an array of OperatingTimes + # Returns an array of Times representing the opening and closing times + # of this Place between +startAt+ and +endAt+ def schedule(startAt,endAt) - # TODO Returns the schedule for a specified time window + ## Caching ## + @schedules ||= {} + if @schedules[startAt.xmlschema] and + @schedules[startAt.xmlschema][endAt.xmlschema] + return @schedules[startAt.xmlschema][endAt.xmlschema] + end + ## End Caching ## + # TODO Handle events starting within the range but ending outside of it? - # TODO Offload this selection to the database; okay for testing + # TODO Offload this selection to the database; okay for testing though # Select all relevant times (1 day buffer on each end) # NOTE Make sure to use generous date comparisons to allow for midnight rollovers - regular_operating_times = regular_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} - special_operating_times = special_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} + all_regular_operating_times = regular_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} + all_special_operating_times = special_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} - puts "\nRegular OperatingTimes: #{regular_operating_times.inspect}" if DEBUG - puts "\nSpecial OperatingTimes: #{special_operating_times.inspect}" if DEBUG + puts "\nRegular OperatingTimes: #{all_regular_operating_times.inspect}" if DEBUG + puts "\nSpecial OperatingTimes: #{all_special_operating_times.inspect}" if DEBUG regular_times = [] special_times = [] special_ranges = [] - special_operating_times.each do |ot| + all_special_operating_times.each do |ot| puts "\nSpecial Scheduling for: #{ot.inspect}" if DEBUG # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do if DEBUG puts "Open: #{open}" puts "Close: #{close}" puts "Start Date: #{ot.startDate} (#{ot.startDate.class})" puts "End Date: #{ot.endDate} (#{ot.endDate.class})" end if close < startAt # Skip forward to the first occurrance in our time range open,close = ot.next_times(close) next end special_times << [open,close] special_ranges << Range.new(ot.startDate,ot.endDate) open,close = ot.next_times(close) end end puts "\nSpecial Times: #{special_times.inspect}" if DEBUG puts "\nSpecial Ranges: #{special_ranges.inspect}" if DEBUG - regular_operating_times.each do |ot| + all_regular_operating_times.each do |ot| puts "\nRegular Scheduling for: #{ot.inspect}" if DEBUG # Start a day early if possible earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day # Calculate the next set up open/close times open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do puts "Open: #{open}" if DEBUG puts "Close: #{close}" if DEBUG if close < startAt # Skip forward to the first occurrance in our time range open,close = ot.next_times(close) next end special_ranges.each do |sr| next if sr.member?(open) end regular_times << [open,close] open,close = ot.next_times(close) end end puts "\nRegular Times: #{regular_times.inspect}" if DEBUG # TODO Handle schedule overrides # TODO Handle combinations (i.e. part special, part regular) - (regular_times+special_times).sort{|a,b|a[0] <=> b[0]} + final_schedule = (regular_times+special_times).sort{|a,b|a[0] <=> b[0]} + + ## Caching ## + @schedules ||= {} + @schedules[startAt.xmlschema] ||= {} + @schedules[startAt.xmlschema][endAt.xmlschema] = final_schedule + ## End Caching ## + + final_schedule end def daySchedule(at = Date.today) at = at.to_date if at.class == Time or at.class == DateTime - schedule = schedule(at.midnight,(at+1).midnight) + day_schedule = schedule(at.midnight,(at+1).midnight) #schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } #schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end =end - schedule.sort{|a,b|a[0] <=> b[0]} + day_schedule.sort{|a,b|a[0] <=> b[0]} end def currentSchedule(at = Time.now) puts "At(cS): #{at}" if DEBUG daySchedule(at).select { |open,close| puts "Open(cS): #{open}" if DEBUG puts "Close(cS): #{close}" if DEBUG open <= at and at <= close }[0] end def open?(at = Time.now) a = currentSchedule(at) return a ? true : false end - - # Alias for <tt>open?</tt> - def open(at = Time.now); open? at ; end + alias :open :open? def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end - def to_xml(params) - super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) + def to_xml(options) + #super(options.merge({:only => [:id, :name, :location, :phone], :methods => [ :open, :daySchedule ] })) + options[:indent] ||= 2 + xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) + xml.instruct! unless options[:skip_instruct] + xml.place do + + xml.id(self.id) + xml.name(self.name) + xml.location(self.location) + xml.phone(self.phone) + + xml.open(self.open?) + + if daySchedule.nil? or daySchedule.empty? + xml.daySchedule + else + xml.daySchedule(:for => Date.today) do |xml|; daySchedule.each do |open,close| + xml.open(open.xmlschema) + xml.close(close.xmlschema) + end; end + end + + end end end diff --git a/spec/models/operating_time_spec.rb b/spec/models/operating_time_spec.rb index 4cededb..3e7c4da 100644 --- a/spec/models/operating_time_spec.rb +++ b/spec/models/operating_time_spec.rb @@ -1,202 +1,208 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe OperatingTime do before(:each) do @place = mock_model(Place) @valid_attributes = { :place_id => @place.id, :start => (Time.now - 1.hours).to_i, :length => 2.hours, :daysOfWeek => OperatingTime::ALL_DAYS, :startDate => Date.yesterday, :endDate => Date.tomorrow, :override => false } @operating_time = OperatingTime.create!(@valid_attributes) end it "should create a new instance given all valid attributes" do OperatingTime.create!(@valid_attributes) end describe "missing required attributes" do it "should not create a new instance without a valid start time" it "should not create a new instance without a valid length" it "should not create a new instance without a valid Place reference" it "should not create a new instance without a valid start date" it "should not create a new instance without a valid end date" end describe "missing default-able attributes" do it "should default daysOfWeek to 0" do @valid_attributes.delete(:daysOfWeek) if @valid_attributes[:daysOfWeek] OperatingTime.create!(@valid_attributes).daysOfWeek.should == 0 end it "should default override to false" do @valid_attributes.delete(:override) if @valid_attributes[:override] OperatingTime.create!(@valid_attributes).override.should == false end end describe "given invalid attributes" do def create @operating_time = OperatingTime.create!(@valid_attributes) end =begin it "should create a new instance, but ignore an invalid override value" do @valid_attributes[:override] = "invalid" create @operating_time.override.should == false # where false is the default value @valid_attributes[:override] = 10 create @operating_time.override.should == false # where false is the default value end it "should create a new instance, but ignore an invalid daysOfWeek value" do @valid_attributes[:daysOfWeek] = 1000 create @operating_time.daysOfWeek.should == 0 # where 0 is the default value end =end it "should not create a new instance with an invalid start time" it "should not create a new instance with an invalid length" it "should not create a new instance with an invalid Place reference" it "should not create a new instance with an invalid start date" it "should not create a new instance with an invalid end date" end it "should enable override mode" do @operating_time.should_receive(:write_attribute).with(:override, true).exactly(3).times @operating_time.override = true @operating_time.override = "true" @operating_time.override = 1 end it "should disable override mode" do @operating_time.should_receive(:write_attribute).with(:override, false).exactly(3).times @operating_time.override = false @operating_time.override = "false" @operating_time.override = 0 end it "should complain about invalid override values, but not change the value" do @operating_time.override = true @operating_time.override.should == true #TODO Should nil be ignored or errored? lambda { @operating_time.override = nil }.should raise_error(ArgumentError) @operating_time.override.should == true lambda { @operating_time.override = "invalid" }.should raise_error(ArgumentError) @operating_time.override.should == true lambda { @operating_time.override = false }.should_not raise_error @operating_time.override.should == false end it "should complain about invalid daysOfWeek values, but not change the value" do @operating_time.daysOfWeek = OperatingTime::SUNDAY @operating_time.daysOfWeek.should == OperatingTime::SUNDAY #TODO Should nil be ignored or errored? lambda { @operating_time.daysOfWeek = nil }.should raise_error(ArgumentError) @operating_time.daysOfWeek.should == OperatingTime::SUNDAY lambda { @operating_time.daysOfWeek = 200 }.should raise_error(ArgumentError) @operating_time.daysOfWeek.should == OperatingTime::SUNDAY lambda { @operating_time.daysOfWeek= OperatingTime::MONDAY }.should_not raise_error @operating_time.daysOfWeek.should == OperatingTime::MONDAY end describe "with open and close times" do before(:each) do @now = Time.now.midnight + 15.minutes @open = @now.midnight + 23.hours + 30.minutes @close = @open + 1.hour start = @open - @open.midnight length = @close - @open @valid_attributes.update({ :start => start, :length => length }) @operating_time = OperatingTime.create!(@valid_attributes) end it "should return valid open and close times for 'now'" do open,close = @operating_time.next_times() open.to_s.should == @open.to_s close.to_s.should == @close.to_s end it "should return valid open and close times for a given time" do @open, @close, @now = [@open,@close,@now].collect{|t| t + 5.days} @operating_time.endDate += 5 open,close = @operating_time.next_times( @now ) open.to_s.should == @open.to_s close.to_s.should == @close.to_s end it "should return valid open/close times if open past midnight, but ending today" do @operating_time.endDate = @now.to_date open = @now.midnight + @operating_time.start close = open + @operating_time.length open,close = @operating_time.next_times() close.should > (@now.to_date + 1).midnight open.to_s.should == @open.to_s close.to_s.should == @close.to_s end + + it "should return valid open/close times if open one day per week" do + @operating_time.endDate = @now.to_date + 21 + open = @now.midnight + pending("Look at next_times daysOfWeek array shifting") + end end end ### Midnight Module Specs ### describe Date do before(:each) do @date = Date.today end it "should have a valid midnight" do @date.should respond_to(:midnight) @date.midnight.should == Time.mktime(@date.year, @date.month, @date.day, 0, 0, 0) end end describe Time do before(:each) do @time = Time.now end it "should have a valid midnight" do @time.should respond_to(:midnight) @time.midnight.should == Time.mktime(@time.year, @time.month, @time.day, 0, 0, 0) end it "should have a valid midnight offset" do @time.should respond_to(:offset) @time.offset.should == @time.hour.hours + @time.min.minutes + @time.sec end end describe DateTime do before(:each) do @dt = DateTime.now end it "should have a valid midnight" do @dt.should respond_to(:midnight) @dt.midnight.should == Time.mktime(@dt.year, @dt.month, @dt.day, 0, 0, 0) end end ### End Midnight Module Specs ### diff --git a/spec/models/schedules.rb b/spec/models/schedules.rb index 7547b9c..fa2cf70 100644 --- a/spec/models/schedules.rb +++ b/spec/models/schedules.rb @@ -1,334 +1,381 @@ ###################### ##### Scheduling ##### ###################### describe "a Place with scheduling capabilities", :shared => true do before(:each) do add_scheduling_spec_helpers(@place) end validate_setup do before(:each) do @place.build end end it "should be clean" do @place.regular_operating_times.should == [] @place.special_operating_times.should == [] @place.constraints.should == [] @place.times.should == [] end in_order_to "be open now" do before(:each) do @place.add_times([ {:start => 6.hours, :length => 2.hours, :override => false}, {:start => 6.hours, :length => 2.hours, :override => true} ]) @at = (@at || Time.now).midnight + 7.hours end it "should have operating times" do @place.build(@at) @place.operating_times.should_not be_empty end it "should have a schedule" do @place.build(@at) @place.schedule(@at.midnight, @at.midnight + 1.day).should_not be_empty end it "should have a daySchedule" do @place.build(@at) @place.daySchedule(@at).should_not be_empty end it "should have a currentSchedule" do @place.build(@at) @place.currentSchedule(@at).should_not be_nil end it "should be open on Sunday" do @at = @at - @at.wday.days # Set to previous Sunday @place.rebuild @place.open(@at).should == true end it "should be open on Wednesday" do @at = @at - @at.wday.days + 3.days # Set to Wednesday after last Sunday @place.rebuild(@at) begin @place.open(@at).should == true rescue Exception => e puts "" puts "At: #{@at}" puts "Times: #{@place.times.inspect}" puts "OperatingTimes: #{@place.operating_times.inspect}" puts "daySchedule: #{@place.daySchedule(@at)}" raise e end end it "should be open on Saturday" do @at = @at - @at.wday.days + 6.days# Set to Saturday after last Sunday @place.rebuild(@at) @place.open(@at).should == true end + + it "should be open on only one day every week" do + @at = @at - @at.wday.days + 6.days# Set to Saturday after last Sunday + @place.times.each do |t| + t[:daysOfWeek] = OperatingTime::SATURDAY + t[:startDate] = @at.to_date - 2.days + t[:endDate] = @at.to_date + 3.weeks + end + @place.rebuild(@at) + + puts @place.schedule(@at-1.day, @at+15.days).inspect + @place.schedule(@at-1.day, @at+15.days).should have(3).times + @place.schedule(@at-1.day, @at+15.days).collect{|a,b|[a.xmlschema,b.xmlschema]}.uniq.should have(3).unique_times + end end in_order_to "be open 24 hours" do before(:each) do @place.add_times([ {:start => 0, :length => 24.hours, :override => false}, {:start => 0, :length => 24.hours, :override => true} ]) @at = (@at || Time.now).midnight + 12.hours @place.build(@at) end it "should be open during the day" do @place.open(@at).should == true end it "should be open at midnight" do @place.open(@at.midnight).should == true end end in_order_to "be open later in the day" do before(:each) do @place.add_times([ {:start => 16.hours, :length => 2.hours, :override => false}, {:start => 16.hours, :length => 2.hours, :override => true} ]) @at = (@at || Time.now).midnight + 12.hours @place.build(@at) end it "should be closed now" do @place.open(@at).should == false end it "should have a schedule later in the day" do @place.schedule(@at,@at.midnight + 24.hours).should_not be_empty end it "should not have a schedule earlier in the day" do @place.schedule(@at.midnight,@at).should be_empty end end in_order_to "be closed for the day" do before(:each) do @place.add_times([ {:start => 4.hours, :length => 2.hours, :override => false}, - {:start => 4.hours, :length => 2.hours, :override => false} + {:start => 4.hours, :length => 2.hours, :override => true} ]) @at = (@at || Time.now).midnight + 12.hours @place.build(@at) end it "should be closed now" do @place.open(@at).should == false end it "should have a schedule earlier in the day" do @place.schedule(@at.midnight,@at).should_not be_empty end it "should not have a schedule later in the day" do @place.schedule(@at, @at.midnight + 24.hours).should be_empty end end in_order_to "be open past midnight" do before(:each) do @at = (@at || Time.now).midnight + 12.hours @place.add_times([ {:start => 23.hours, :length => 4.hours, :override => true}, {:start => 23.hours, :length => 4.hours, :override => false} ]) @place.times.each do |t| t[:startDate] = @at.to_date t[:endDate] = @at.to_date end @place.build(@at) end it "should be open early the next morning" do @place.open(@at.midnight + 1.days + 2.hours).should == true end it "should not be open early that morning" do @place.open(@at.midnight + 2.hours).should == false end it "should not be open late the next night" do @place.open(@at.midnight + 2.days + 2.hours).should == false end end in_order_to "be closed now" do before(:each) do @place.add_constraint {|t| ( t[:start] > @at.offset ) or ( (t[:start] + t[:length]) < @at.offset ) } @place.add_times([ {:start => 6.hours, :length => 2.hours, :override => false}, {:start => 6.hours, :length => 2.hours, :override => true} ]) @at = Time.now.midnight + 12.hours @place.build end it "should be closed" do @place.open(@at).should == false end end in_order_to "be closed all day" do before(:each) do @at ||= Time.now @place.add_times([ {:start => 0, :length => 0, :startDate => @at.to_date, :endDate => @at.to_date, :override => false}, - {:start => 0, :length => 0, :startDate => @at.to_date, :endDate => @at.to_date, :override => false} + {:start => 0, :length => 0, :startDate => @at.to_date, :endDate => @at.to_date, :override => true} ]) @place.build(@at) end it "should be closed now" do @place.open(@at).should == false end it "should not have a schedule earlier in the day" do @place.schedule(@at.midnight,@at).should be_empty end it "should not have a schedule later in the day" do @place.schedule(@at, @at.midnight + 24.hours).should be_empty end it "should not have a schedule at all for the day" do @place.daySchedule(@at).should be_empty end end in_order_to "have a valid schedule" do it "should not have any overlapping times" it "should have all times within the specified time range" end end describe "a Place with valid times", :shared => true do describe "with only regular times" do before(:each) do @place.add_constraint {|t| t[:override] == false } @place.build end validate_setup do it "should have regular times" do #puts "Regular Times: #{@place.regular_operating_times.inspect}" @place.regular_operating_times.should_not be_empty end it "should not have any special times" do #puts "Special Times: #{@place.special_operating_times.inspect}" @place.special_operating_times.should be_empty end end it_can "be open now" it_can "be open 24 hours" it_can "be open past midnight" it_can "be open later in the day" it_can "be closed for the day" it_can "be closed now" it_can "be closed all day" end -=begin describe "with only special times" do before(:each) do @place.add_constraint {|t| t[:override] == true } @place.build end - validate_setup do it "should not have regular times" do @place.regular_operating_times.should be_empty end it "should have special times" do @place.special_operating_times.should_not be_empty end end it_can "be open now" it_can "be open 24 hours" it_can "be open past midnight" it_can "be open later in the day" it_can "be closed for the day" it_can "be closed now" it_can "be closed all day" end describe "with regular and special times" do validate_setup do it "should have regular times" do @place.regular_operating_times.should_not be_empty end it "should have special times" do @place.special_operating_times.should_not be_empty end end describe "where the special times are overriding the regular times" do - #it_should_behave_like "a Place with all scheduling capabilities" + #it_can "be open now" + #it_can "be open 24 hours" + #it_can "be open past midnight" + #it_can "be open later in the day" + #it_can "be closed for the day" + #it_can "be closed now" + #it_can "be closed all day" end describe "where the special times are not overriding the regular times" do - #it_should_behave_like "a Place with all scheduling capabilities" + #it_can "be open now" + #it_can "be open 24 hours" + #it_can "be open past midnight" + #it_can "be open later in the day" + #it_can "be closed for the day" + #it_can "be closed now" + #it_can "be closed all day" end end describe "with special times" do describe "extending normal hours" do - #it_should_behave_like "a Place with all scheduling capabilities" + #it_can "be open now" + #it_can "be open 24 hours" + #it_can "be open past midnight" + #it_can "be open later in the day" + #it_can "be closed for the day" + #it_can "be closed now" + #it_can "be closed all day" end describe "reducing normal hours" do - #it_should_behave_like "a Place with all scheduling capabilities" + #it_can "be open now" + #it_can "be open 24 hours" + #it_can "be open past midnight" + #it_can "be open later in the day" + #it_can "be closed for the day" + #it_can "be closed now" + #it_can "be closed all day" end describe "removing all hours" do - #it_should_behave_like "a Place with all scheduling capabilities" + #it_can "be open now" + #it_can "be open 24 hours" + #it_can "be open past midnight" + #it_can "be open later in the day" + #it_can "be closed for the day" + #it_can "be closed now" + #it_can "be closed all day" end describe "moving normal hours (extending and reducing)" do - #it_should_behave_like "a Place with all scheduling capabilities" + #it_can "be open now" + #it_can "be open 24 hours" + #it_can "be open past midnight" + #it_can "be open later in the day" + #it_can "be closed for the day" + #it_can "be closed now" + #it_can "be closed all day" end end -=end end
michaelansel/dukenow
08ef7773e09ccdcb1553f531b4352e3f841ccbc7
Add backwards compatibility fixes to migrations for existing data (does not affect a fresh database)
diff --git a/app/models/operating_time.rb b/app/models/operating_time.rb index 71fff80..55232c3 100644 --- a/app/models/operating_time.rb +++ b/app/models/operating_time.rb @@ -1,226 +1,226 @@ class OperatingTime < ActiveRecord::Base belongs_to :place - validates_presence_of :place_id + validates_presence_of :place_id, :endDate, :startDate validates_associated :place validate :end_after_start, :daysOfWeek_valid validate {|ot| 0 <= ot.length and ot.length <= 1.days } ## DaysOfWeek Constants ## SUNDAY = 0b00000001 MONDAY = 0b00000010 TUESDAY = 0b00000100 WEDNESDAY = 0b00001000 THURSDAY = 0b00010000 FRIDAY = 0b00100000 SATURDAY = 0b01000000 ALL_DAYS = (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) ## Validations ## def end_after_start if endDate < startDate errors.add_to_base("End date cannot preceed start date") end end def daysOfWeek_valid daysOfWeek == daysOfWeek & (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) end ## End Validations ## # TODO Is this OperatingTime applicable at +time+ def valid_at(time=Time.now) raise NotImplementedError end def override read_attribute(:override) == 1 end def override=(mode) if mode == true or mode == "true" or mode == 1 write_attribute(:override, true) elsif mode == false or mode == "false" or mode == 0 write_attribute(:override, false) else raise ArgumentError, "Invalid override value (#{mode.inspect}); Accepts true/false, 1/0" end end def daysOfWeek=(newDow) if not ( newDow & ALL_DAYS == newDow ) # Invalid input raise ArgumentError, "Not a valid value for daysOfWeek (#{newDow.inspect})" end write_attribute(:daysOfWeek, newDow & ALL_DAYS) @daysOfWeekHash = nil @daysOfWeekArray = nil @daysOfWeekString = nil end ## daysOfWeek Helper/Accessors ## # Hash mapping day of week (Symbol) to valid(true)/invalid(false) def daysOfWeekHash @daysOfWeekHash ||= { :sunday => (daysOfWeek & SUNDAY ) > 0, :monday => (daysOfWeek & MONDAY ) > 0, :tuesday => (daysOfWeek & TUESDAY ) > 0, :wednesday => (daysOfWeek & WEDNESDAY ) > 0, :thursday => (daysOfWeek & THURSDAY ) > 0, :friday => (daysOfWeek & FRIDAY ) > 0, :saturday => (daysOfWeek & SATURDAY ) > 0 } end # Array beginning with Sunday of valid(true)/inactive(false) values def daysOfWeekArray dow = daysOfWeekHash @daysOfWeekArray ||= [ dow[:sunday], dow[:monday], dow[:tuesday], dow[:wednesday], dow[:thursday], dow[:friday], dow[:saturday] ] end # Human-readable string of applicable days of week def daysOfWeekString dow = daysOfWeekHash @daysOfWeekString ||= (dow[:sunday] ? "Su" : "") + (dow[:monday] ? "M" : "") + (dow[:tuesday] ? "Tu" : "") + (dow[:wednesday] ? "W" : "") + (dow[:thursday] ? "Th" : "") + (dow[:friday] ? "F" : "") + (dow[:saturday] ? "Sa" : "") end ## End daysOfWeek Helper/Accessors ## def to_xml(params) super(params.merge({:only => [:id, :place_id, :flags], :methods => [ :opensAt, :closesAt, :startDate, :endDate ]})) end # Returns the next full occurrence of these operating time rule. # If we are currently within a valid time range, it will look forward for the # <em>next</em> opening time def next_times(at = Time.now) return nil if length == 0 return nil if at.to_date > endDate # Schedules end at 23:59 of the stored endDate at = startDate.midnight if at < startDate # This schedule hasn't started yet, skip to startDate # Next occurrence is later today # This is the only time the "time" actually matters; # after today, all we care about is the date if daysOfWeekArray[at.wday] and start >= at.offset open = at.midnight + start close = open + length return [open,close] end # We don't care about the time offset anymore, jump to the next midnight at = at.midnight + 1.day # TODO Test for Sun, Sat, and one of M-F dow = daysOfWeekArray[at.wday..-1] + daysOfWeekArray[0..at.wday] # Next day of the week this schedule is valid for shift = dow.index(true) if shift # Skip forward at = at + shift.days else # Give up, there are no more occurrences # TODO Test edge case: valid for 1 day/week return nil end # Recurse to rerun the validation routines return next_times(at) end alias :to_times :next_times ##### TODO DEPRECATED METHODS ##### def at @at end def at=(time) @opensAt = nil @closesAt = nil @at = time end # Returns a Time object representing the beginning of this OperatingTime def opensAt @opensAt ||= relativeTime.openTime(at) end def closesAt @closesAt ||= relativeTime.closeTime(at) end # Sets the beginning of this OperatingTime # Input: params = { :hour => 12, :minute => 45 } def opensAt=(time) if time.class == Time @opensAt = relativeTime.openTime = time else super end end # Sets the end of this OperatingTime def closesAt=(time) @closesAt = relativeTime.closeTime = time end def start read_attribute(:opensAt) end def start=(offset) write_attribute(:opensAt,offset) end # Returns a RelativeTime object representing this OperatingTime def relativeTime @relativeTime ||= RelativeTime.new(self, :opensAt, :length) end; protected :relativeTime # Backwards compatibility with old database schema # TODO GET RID OF THIS!!! def flags ( (override ? 1 : 0) << 7) | read_attribute(:daysOfWeek) end # FIXME Deprecated, use +override+ instead def special override end # Input: isSpecial = true/false # FIXME Deprecated, use +override=+ instead def special=(isSpecial) if isSpecial == true or isSpecial == "true" or isSpecial == 1 self.override = true elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 self.override = false end end end diff --git a/db/migrate/20090616040958_start_length_schema.rb b/db/migrate/20090616040958_start_length_schema.rb index 7dfc5de..0b73dff 100644 --- a/db/migrate/20090616040958_start_length_schema.rb +++ b/db/migrate/20090616040958_start_length_schema.rb @@ -1,11 +1,16 @@ class StartLengthSchema < ActiveRecord::Migration def self.up - OperatingTime.find(:all).each{|ot| ot.write_attribute(:closesAt, ot.read_attribute(:closesAt) - ot.read_attribute(:opensAt)) ; ot.save } + OperatingTime.find(:all).each do |ot| + ot.write_attribute(:closesAt, ot.read_attribute(:closesAt) - ot.read_attribute(:opensAt)) + ot.write_attribute(:startDate, ot.read_attribute(:startDate) || Date.new(Date.today.year,1,1)) + ot.write_attribute(:endDate, ot.read_attribute(:endDate) || Date.new(Date.today.year,12,31)) + ot.save_without_validation + end rename_column('operating_times', 'closesAt', 'length') end def self.down - OperatingTime.find(:all).each{|ot| ot.length = ot.length + ot.read_attribute(:opensAt) ; ot.save } + OperatingTime.find(:all).each{|ot| ot.length = ot.length + ot.read_attribute(:opensAt) ; ot.save_without_validation } rename_column('operating_times', 'length', 'closesAt') end end diff --git a/db/migrate/20090626212057_override_and_days_of_week_flags.rb b/db/migrate/20090626212057_override_and_days_of_week_flags.rb index 5e40402..8507df7 100644 --- a/db/migrate/20090626212057_override_and_days_of_week_flags.rb +++ b/db/migrate/20090626212057_override_and_days_of_week_flags.rb @@ -1,28 +1,28 @@ class OverrideAndDaysOfWeekFlags < ActiveRecord::Migration def self.up add_column "operating_times", "override", :integer, :null => false, :default => 0 add_column "operating_times", "days_of_week", :integer, :null => false, :default => 0 OperatingTime.reset_column_information OperatingTime.find(:all).each do |ot| ot.write_attribute(:override, ot.read_attribute(:flags) & 128) # 128 == Special Flag ot.write_attribute(:days_of_week, ot.read_attribute(:flags) & (1+2+4+8+16+32+64) ) # Sum == Flag for each day of the week - ot.save + ot.save_without_validation end remove_column("operating_times", "flags") end def self.down add_column("operating_times","flags",:integer, :null => false, :default => 0) OperatingTime.reset_column_information OperatingTime.find(:all).each do |ot| ot.write_attribute(:flags, (ot.read_attribute(:override) << 7) | ot.read_attribute(:days_of_week) ) - ot.save + ot.save_without_validation end remove_column("operating_times", "override") remove_column("operating_times", "days_of_week") end end
michaelansel/dukenow
17b1ce2e2888e4544c8737c840dd58e4ff760f31
Finish out scheduling specs and fix Places model
diff --git a/app/models/operating_time.rb b/app/models/operating_time.rb index 6f5eac9..71fff80 100644 --- a/app/models/operating_time.rb +++ b/app/models/operating_time.rb @@ -1,224 +1,226 @@ class OperatingTime < ActiveRecord::Base belongs_to :place validates_presence_of :place_id validates_associated :place validate :end_after_start, :daysOfWeek_valid + validate {|ot| 0 <= ot.length and ot.length <= 1.days } ## DaysOfWeek Constants ## SUNDAY = 0b00000001 MONDAY = 0b00000010 TUESDAY = 0b00000100 WEDNESDAY = 0b00001000 THURSDAY = 0b00010000 FRIDAY = 0b00100000 SATURDAY = 0b01000000 ALL_DAYS = (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) ## Validations ## def end_after_start if endDate < startDate errors.add_to_base("End date cannot preceed start date") end end def daysOfWeek_valid daysOfWeek == daysOfWeek & (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) end ## End Validations ## # TODO Is this OperatingTime applicable at +time+ def valid_at(time=Time.now) raise NotImplementedError end def override read_attribute(:override) == 1 end def override=(mode) if mode == true or mode == "true" or mode == 1 write_attribute(:override, true) elsif mode == false or mode == "false" or mode == 0 write_attribute(:override, false) else raise ArgumentError, "Invalid override value (#{mode.inspect}); Accepts true/false, 1/0" end end def daysOfWeek=(newDow) if not ( newDow & ALL_DAYS == newDow ) # Invalid input raise ArgumentError, "Not a valid value for daysOfWeek (#{newDow.inspect})" end write_attribute(:daysOfWeek, newDow & ALL_DAYS) @daysOfWeekHash = nil @daysOfWeekArray = nil @daysOfWeekString = nil end ## daysOfWeek Helper/Accessors ## # Hash mapping day of week (Symbol) to valid(true)/invalid(false) def daysOfWeekHash @daysOfWeekHash ||= { :sunday => (daysOfWeek & SUNDAY ) > 0, :monday => (daysOfWeek & MONDAY ) > 0, :tuesday => (daysOfWeek & TUESDAY ) > 0, :wednesday => (daysOfWeek & WEDNESDAY ) > 0, :thursday => (daysOfWeek & THURSDAY ) > 0, :friday => (daysOfWeek & FRIDAY ) > 0, :saturday => (daysOfWeek & SATURDAY ) > 0 } end # Array beginning with Sunday of valid(true)/inactive(false) values def daysOfWeekArray dow = daysOfWeekHash @daysOfWeekArray ||= [ dow[:sunday], dow[:monday], dow[:tuesday], dow[:wednesday], dow[:thursday], dow[:friday], dow[:saturday] ] end # Human-readable string of applicable days of week def daysOfWeekString dow = daysOfWeekHash @daysOfWeekString ||= (dow[:sunday] ? "Su" : "") + (dow[:monday] ? "M" : "") + (dow[:tuesday] ? "Tu" : "") + (dow[:wednesday] ? "W" : "") + (dow[:thursday] ? "Th" : "") + (dow[:friday] ? "F" : "") + (dow[:saturday] ? "Sa" : "") end ## End daysOfWeek Helper/Accessors ## def to_xml(params) super(params.merge({:only => [:id, :place_id, :flags], :methods => [ :opensAt, :closesAt, :startDate, :endDate ]})) end # Returns the next full occurrence of these operating time rule. # If we are currently within a valid time range, it will look forward for the # <em>next</em> opening time def next_times(at = Time.now) - return nil if at > endDate # This schedule has ended + return nil if length == 0 + return nil if at.to_date > endDate # Schedules end at 23:59 of the stored endDate at = startDate.midnight if at < startDate # This schedule hasn't started yet, skip to startDate # Next occurrence is later today # This is the only time the "time" actually matters; # after today, all we care about is the date if daysOfWeekArray[at.wday] and - start >= (at - at.midnight) + start >= at.offset open = at.midnight + start close = open + length return [open,close] end # We don't care about the time offset anymore, jump to the next midnight at = at.midnight + 1.day # TODO Test for Sun, Sat, and one of M-F dow = daysOfWeekArray[at.wday..-1] + daysOfWeekArray[0..at.wday] # Next day of the week this schedule is valid for shift = dow.index(true) if shift # Skip forward at = at + shift.days else # Give up, there are no more occurrences # TODO Test edge case: valid for 1 day/week return nil end # Recurse to rerun the validation routines return next_times(at) end alias :to_times :next_times ##### TODO DEPRECATED METHODS ##### def at @at end def at=(time) @opensAt = nil @closesAt = nil @at = time end # Returns a Time object representing the beginning of this OperatingTime def opensAt @opensAt ||= relativeTime.openTime(at) end def closesAt @closesAt ||= relativeTime.closeTime(at) end # Sets the beginning of this OperatingTime # Input: params = { :hour => 12, :minute => 45 } def opensAt=(time) if time.class == Time @opensAt = relativeTime.openTime = time else super end end # Sets the end of this OperatingTime def closesAt=(time) @closesAt = relativeTime.closeTime = time end def start read_attribute(:opensAt) end def start=(offset) write_attribute(:opensAt,offset) end # Returns a RelativeTime object representing this OperatingTime def relativeTime @relativeTime ||= RelativeTime.new(self, :opensAt, :length) end; protected :relativeTime # Backwards compatibility with old database schema # TODO GET RID OF THIS!!! def flags ( (override ? 1 : 0) << 7) | read_attribute(:daysOfWeek) end # FIXME Deprecated, use +override+ instead def special override end # Input: isSpecial = true/false # FIXME Deprecated, use +override=+ instead def special=(isSpecial) if isSpecial == true or isSpecial == "true" or isSpecial == 1 self.override = true elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 self.override = false end end end diff --git a/app/models/place.rb b/app/models/place.rb index f92404e..1cb793a 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,140 +1,151 @@ class Place < ActiveRecord::Base - DEBUG = defined? DEBUG ? DEBUG : false + DEBUG = false has_many :operating_times acts_as_taggable_on :tags validates_presence_of :name def special_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 1}, :order => "startDate ASC, opensAt ASC" ) end def regular_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 0}, :order => "startDate ASC, opensAt ASC" ) end # Returns an array of OperatingTimes def schedule(startAt,endAt) # TODO Returns the schedule for a specified time window # TODO Handle events starting within the range but ending outside of it? # TODO Offload this selection to the database; okay for testing - regular_operating_times = regular_operating_times().select{|t| t.startDate <= endAt.to_date and t.endDate >= startAt.to_date} - special_operating_times = special_operating_times().select{|t| t.startDate <= endAt.to_date and t.endDate >= startAt.to_date} + # Select all relevant times (1 day buffer on each end) + # NOTE Make sure to use generous date comparisons to allow for midnight rollovers + regular_operating_times = regular_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} + special_operating_times = special_operating_times().select{|t| (t.startDate - 1) <= endAt.to_date and startAt.to_date <= (t.endDate + 1)} + + puts "\nRegular OperatingTimes: #{regular_operating_times.inspect}" if DEBUG + puts "\nSpecial OperatingTimes: #{special_operating_times.inspect}" if DEBUG regular_times = [] special_times = [] special_ranges = [] special_operating_times.each do |ot| - puts "\nSpecial Scheduling: #{ot.inspect}" if DEBUG + puts "\nSpecial Scheduling for: #{ot.inspect}" if DEBUG - open,close = ot.next_times(startAt-1.day) + # Start a day early if possible + earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day + # Calculate the next set up open/close times + open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do if DEBUG puts "Open: #{open}" puts "Close: #{close}" puts "Start Date: #{ot.startDate} (#{ot.startDate.class})" puts "End Date: #{ot.endDate} (#{ot.endDate.class})" end if close < startAt # Skip forward to the first occurrance in our time range open,close = ot.next_times(close) next end special_times << [open,close] special_ranges << Range.new(ot.startDate,ot.endDate) open,close = ot.next_times(close) end end puts "\nSpecial Times: #{special_times.inspect}" if DEBUG puts "\nSpecial Ranges: #{special_ranges.inspect}" if DEBUG regular_operating_times.each do |ot| - puts "\nRegular Scheduling: #{ot.inspect}" if DEBUG + puts "\nRegular Scheduling for: #{ot.inspect}" if DEBUG - open,close = ot.next_times(startAt-1.day) + # Start a day early if possible + earlyStart = startAt-1.day < ot.startDate.midnight ? startAt : startAt - 1.day + # Calculate the next set up open/close times + open,close = ot.next_times(earlyStart) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do puts "Open: #{open}" if DEBUG puts "Close: #{close}" if DEBUG if close < startAt # Skip forward to the first occurrance in our time range open,close = ot.next_times(close) next end special_ranges.each do |sr| next if sr.member?(open) end regular_times << [open,close] open,close = ot.next_times(close) end end puts "\nRegular Times: #{regular_times.inspect}" if DEBUG # TODO Handle schedule overrides # TODO Handle combinations (i.e. part special, part regular) (regular_times+special_times).sort{|a,b|a[0] <=> b[0]} end def daySchedule(at = Date.today) at = at.to_date if at.class == Time or at.class == DateTime schedule = schedule(at.midnight,(at+1).midnight) #schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } #schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end =end schedule.sort{|a,b|a[0] <=> b[0]} end def currentSchedule(at = Time.now) puts "At(cS): #{at}" if DEBUG daySchedule(at).select { |open,close| puts "Open(cS): #{open}" if DEBUG puts "Close(cS): #{close}" if DEBUG open <= at and at <= close }[0] end def open?(at = Time.now) a = currentSchedule(at) return a ? true : false end # Alias for <tt>open?</tt> def open(at = Time.now); open? at ; end def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end def to_xml(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end end diff --git a/spec/capabilities.rb b/spec/capabilities.rb index 145fb19..3eb0e4a 100644 --- a/spec/capabilities.rb +++ b/spec/capabilities.rb @@ -1,77 +1,71 @@ require 'rubygems' require 'spec' module Spec module Example class ExampleGroupHierarchy def validation_blocks @validation_blocks ||= collect {|klass| klass.validation_blocks}.flatten end end module ExampleGroupMethods def it_can(*capabilities) capabilities.each do |c| include_capability(c) end end def it_can_be(*capabilities) capabilities.each do |c| it_can("be #{c}") end end def in_order_to(*args, &block) raise Spec::Example::NoDescriptionError.new("example group", caller(0)[1]) if args.empty? options = add_options(args) set_location(options, caller(0)[1]) Spec::Example::CapabilityFactory.create_capability(*args, &block) end def in_order_to_be(*args, &block) in_order_to("be", *args, &block) end def include_capability(capability) - case capability - when Capability - include capability - else - unless example_group = Capability.find(capability) - raise RuntimeError.new("Capability '#{capability}' can not be found") - end - include(example_group) + + unless example_group = Capability.find(capability) + raise RuntimeError.new("Capability '#{capability}' can not be found") end - ExampleGroupHierarchy.new(self).validation_blocks.each do |validation_block| - describe("set up properly", &validation_block) + subclass("can",capability,"therefore") do + include example_group + + describe("when set up properly") do + ExampleGroupHierarchy.new(self).validation_blocks.each do |validation_block| + self.module_eval(&validation_block) + end + end end end def validation_blocks @validation_blocks ||= [] end def validate_setup(&block) validation_blocks << block end end class Capability < SharedExampleGroup end class CapabilityFactory < ExampleGroupFactory def self.create_capability(*args, &capability_block) # :nodoc: -=begin - ::Spec::Example::Capability.register(*args) do - describe("that can",*args) do - ::Spec::Example::Capability.register(*args,&capability_block) - end - end -=end - ::Spec::Example::Capability.register(*args,&capability_block) + ::Spec::Example::Capability.register(*args,&capability_block) end end end end diff --git a/spec/models/operating_time_spec.rb b/spec/models/operating_time_spec.rb index af0bea2..4cededb 100644 --- a/spec/models/operating_time_spec.rb +++ b/spec/models/operating_time_spec.rb @@ -1,191 +1,202 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe OperatingTime do before(:each) do @place = mock_model(Place) @valid_attributes = { :place_id => @place.id, :start => (Time.now - 1.hours).to_i, :length => 2.hours, :daysOfWeek => OperatingTime::ALL_DAYS, :startDate => Date.yesterday, :endDate => Date.tomorrow, :override => false } @operating_time = OperatingTime.create!(@valid_attributes) end it "should create a new instance given all valid attributes" do OperatingTime.create!(@valid_attributes) end describe "missing required attributes" do it "should not create a new instance without a valid start time" it "should not create a new instance without a valid length" it "should not create a new instance without a valid Place reference" it "should not create a new instance without a valid start date" it "should not create a new instance without a valid end date" end describe "missing default-able attributes" do it "should default daysOfWeek to 0" do @valid_attributes.delete(:daysOfWeek) if @valid_attributes[:daysOfWeek] OperatingTime.create!(@valid_attributes).daysOfWeek.should == 0 end it "should default override to false" do @valid_attributes.delete(:override) if @valid_attributes[:override] OperatingTime.create!(@valid_attributes).override.should == false end end describe "given invalid attributes" do def create @operating_time = OperatingTime.create!(@valid_attributes) end =begin it "should create a new instance, but ignore an invalid override value" do @valid_attributes[:override] = "invalid" create @operating_time.override.should == false # where false is the default value @valid_attributes[:override] = 10 create @operating_time.override.should == false # where false is the default value end it "should create a new instance, but ignore an invalid daysOfWeek value" do @valid_attributes[:daysOfWeek] = 1000 create @operating_time.daysOfWeek.should == 0 # where 0 is the default value end =end it "should not create a new instance with an invalid start time" it "should not create a new instance with an invalid length" it "should not create a new instance with an invalid Place reference" it "should not create a new instance with an invalid start date" it "should not create a new instance with an invalid end date" end it "should enable override mode" do @operating_time.should_receive(:write_attribute).with(:override, true).exactly(3).times @operating_time.override = true @operating_time.override = "true" @operating_time.override = 1 end it "should disable override mode" do @operating_time.should_receive(:write_attribute).with(:override, false).exactly(3).times @operating_time.override = false @operating_time.override = "false" @operating_time.override = 0 end it "should complain about invalid override values, but not change the value" do @operating_time.override = true @operating_time.override.should == true #TODO Should nil be ignored or errored? lambda { @operating_time.override = nil }.should raise_error(ArgumentError) @operating_time.override.should == true lambda { @operating_time.override = "invalid" }.should raise_error(ArgumentError) @operating_time.override.should == true lambda { @operating_time.override = false }.should_not raise_error @operating_time.override.should == false end it "should complain about invalid daysOfWeek values, but not change the value" do @operating_time.daysOfWeek = OperatingTime::SUNDAY @operating_time.daysOfWeek.should == OperatingTime::SUNDAY #TODO Should nil be ignored or errored? lambda { @operating_time.daysOfWeek = nil }.should raise_error(ArgumentError) @operating_time.daysOfWeek.should == OperatingTime::SUNDAY lambda { @operating_time.daysOfWeek = 200 }.should raise_error(ArgumentError) @operating_time.daysOfWeek.should == OperatingTime::SUNDAY lambda { @operating_time.daysOfWeek= OperatingTime::MONDAY }.should_not raise_error @operating_time.daysOfWeek.should == OperatingTime::MONDAY end describe "with open and close times" do before(:each) do @now = Time.now.midnight + 15.minutes @open = @now.midnight + 23.hours + 30.minutes @close = @open + 1.hour start = @open - @open.midnight length = @close - @open @valid_attributes.update({ :start => start, :length => length }) @operating_time = OperatingTime.create!(@valid_attributes) end it "should return valid open and close times for 'now'" do open,close = @operating_time.next_times() open.to_s.should == @open.to_s close.to_s.should == @close.to_s end it "should return valid open and close times for a given time" do @open, @close, @now = [@open,@close,@now].collect{|t| t + 5.days} @operating_time.endDate += 5 open,close = @operating_time.next_times( @now ) open.to_s.should == @open.to_s close.to_s.should == @close.to_s end + + it "should return valid open/close times if open past midnight, but ending today" do + @operating_time.endDate = @now.to_date + open = @now.midnight + @operating_time.start + close = open + @operating_time.length + + open,close = @operating_time.next_times() + close.should > (@now.to_date + 1).midnight + open.to_s.should == @open.to_s + close.to_s.should == @close.to_s + end end end ### Midnight Module Specs ### describe Date do before(:each) do @date = Date.today end it "should have a valid midnight" do @date.should respond_to(:midnight) @date.midnight.should == Time.mktime(@date.year, @date.month, @date.day, 0, 0, 0) end end describe Time do before(:each) do @time = Time.now end it "should have a valid midnight" do @time.should respond_to(:midnight) @time.midnight.should == Time.mktime(@time.year, @time.month, @time.day, 0, 0, 0) end it "should have a valid midnight offset" do @time.should respond_to(:offset) @time.offset.should == @time.hour.hours + @time.min.minutes + @time.sec end end describe DateTime do before(:each) do @dt = DateTime.now end it "should have a valid midnight" do @dt.should respond_to(:midnight) @dt.midnight.should == Time.mktime(@dt.year, @dt.month, @dt.day, 0, 0, 0) end end ### End Midnight Module Specs ### diff --git a/spec/models/place_spec.rb b/spec/models/place_spec.rb index fdb44d0..781b16f 100644 --- a/spec/models/place_spec.rb +++ b/spec/models/place_spec.rb @@ -1,99 +1,99 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') require File.expand_path(File.dirname(__FILE__) + '/schedules') describe Place do before(:each) do @valid_attributes = { :name => 'Test Place', :location => 'Somewhere', :phone => '(919) 555-1212' } @place = Place.create!(@valid_attributes) end it "should create a new, valid instance given valid attributes" do Place.create!(@valid_attributes).should be_valid end it "should not create a new instance without a name" do @valid_attributes.delete(:name) lambda { Place.create!(@valid_attributes) }.should raise_error end it "should produce valid XML" it "should produce valid JSON" ############################## ### ### ### Scheduling ### ### ### ############################## it_should_behave_like "a Place with scheduling capabilities" it_should_behave_like "a Place with valid times" - describe "a Place with no times" do + describe "with no times" do before(:each) do # Don't allow any times @place.add_constraint { false } @at = Time.now.midnight + 7.hours end - it_can "be closed now", "be closed all day", "be closed for the day" + it_can "be closed now", "be closed all day" end end =begin # TODO Create mocks for OperatingTime so we can test the scheduling methods describe "a Place with OperatingTimes", :shared => true do describe "that are valid now" do it "should have a valid schedule" do end it "should have a valid daily schedule" it "should have a valid current schedule" it "should have regular OperatingTimes" it "should have special OperatingTimes" end describe "that are not valid now" do end end describe Place do before(:each) do @valid_attributes = { :name => 'Test Place', :location => 'Somewhere', :phone => '(919) 555-1212' } end it "should build a valid dailySchedule" do #TODO Test against a valid schedule as well place = Place.create!(@valid_attributes) place.should_receive(:schedule).with(instance_of(Time), instance_of(Time)).and_return([]) place.daySchedule(Date.today).should == [] end ###### Special Schedules ###### describe "that is normally open, but closed all day today" do it_should_behave_like "a Place with OperatingTimes" end describe "that has special (extended) hours" do it_should_behave_like "a Place with OperatingTimes" end describe "that has special (shortened) hours" do it_should_behave_like "a Place with OperatingTimes" end end =end diff --git a/spec/models/schedules.rb b/spec/models/schedules.rb index 825796d..7547b9c 100644 --- a/spec/models/schedules.rb +++ b/spec/models/schedules.rb @@ -1,274 +1,334 @@ ###################### ##### Scheduling ##### ###################### describe "a Place with scheduling capabilities", :shared => true do before(:each) do add_scheduling_spec_helpers(@place) end + validate_setup do + before(:each) do + @place.build + end + end + it "should be clean" do @place.regular_operating_times.should == [] @place.special_operating_times.should == [] @place.constraints.should == [] @place.times.should == [] end in_order_to "be open now" do - describe "can be open now, so" do before(:each) do @place.add_times([ {:start => 6.hours, :length => 2.hours, :override => false}, {:start => 6.hours, :length => 2.hours, :override => true} ]) @at = (@at || Time.now).midnight + 7.hours - - @place.build end it "should have operating times" do + @place.build(@at) @place.operating_times.should_not be_empty end it "should have a schedule" do + @place.build(@at) @place.schedule(@at.midnight, @at.midnight + 1.day).should_not be_empty end it "should have a daySchedule" do + @place.build(@at) @place.daySchedule(@at).should_not be_empty end it "should have a currentSchedule" do - #puts "\n\n\n\n\n\nDay Schedule: \n#{@place.daySchedule(@at).collect{|a,b| a.inspect + " to " + b.inspect}.join("\n")}\n\n\n\n\n\n" + @place.build(@at) @place.currentSchedule(@at).should_not be_nil end - it "should be open today" do + it "should be open on Sunday" do + @at = @at - @at.wday.days # Set to previous Sunday + @place.rebuild + @place.open(@at).should == true end - it "should be open \"now\" in the past" do - @at -= 12.days - @place.operating_times.each do |t| - t.startDate -= 12 - end + it "should be open on Wednesday" do + @at = @at - @at.wday.days + 3.days # Set to Wednesday after last Sunday + @place.rebuild(@at) - @place.open(@at).should == true - end + begin + @place.open(@at).should == true + rescue Exception => e + puts "" + puts "At: #{@at}" + puts "Times: #{@place.times.inspect}" + puts "OperatingTimes: #{@place.operating_times.inspect}" + puts "daySchedule: #{@place.daySchedule(@at)}" - it "should be open \"now\" in the future" do - @at += 12.days - @place.operating_times.each do |t| - t.endDate += 12 + raise e end + end + + it "should be open on Saturday" do + @at = @at - @at.wday.days + 6.days# Set to Saturday after last Sunday + @place.rebuild(@at) @place.open(@at).should == true end - end end in_order_to "be open 24 hours" do before(:each) do @place.add_times([ {:start => 0, :length => 24.hours, :override => false}, {:start => 0, :length => 24.hours, :override => true} ]) - @at = Time.now.midnight + 12.hours + @at = (@at || Time.now).midnight + 12.hours - @place.build + @place.build(@at) end it "should be open during the day" do @place.open(@at).should == true end it "should be open at midnight" do @place.open(@at.midnight).should == true end end in_order_to "be open later in the day" do before(:each) do @place.add_times([ {:start => 16.hours, :length => 2.hours, :override => false}, {:start => 16.hours, :length => 2.hours, :override => true} ]) - @at = Time.now.midnight + 12.hours + @at = (@at || Time.now).midnight + 12.hours - @place.build + @place.build(@at) end - it "should have a schedule between now and midnight" do - @place.schedule(@at,@at.midnight + 24.hours).size.should > 0 + it "should be closed now" do + @place.open(@at).should == false end - end - in_order_to "be open earlier in the day" do + it "should have a schedule later in the day" do + @place.schedule(@at,@at.midnight + 24.hours).should_not be_empty + end + + it "should not have a schedule earlier in the day" do + @place.schedule(@at.midnight,@at).should be_empty + end end - in_order_to "be open past midnight (tonight)" do + in_order_to "be closed for the day" do before(:each) do - @at = Time.now.midnight + @place.add_times([ + {:start => 4.hours, :length => 2.hours, :override => false}, + {:start => 4.hours, :length => 2.hours, :override => false} + ]) + @at = (@at || Time.now).midnight + 12.hours + @place.build(@at) + end - @place.build + it "should be closed now" do + @place.open(@at).should == false + end + + it "should have a schedule earlier in the day" do + @place.schedule(@at.midnight,@at).should_not be_empty end - end - in_order_to "be open past midnight (last night)" do + it "should not have a schedule later in the day" do + @place.schedule(@at, @at.midnight + 24.hours).should be_empty + end end + in_order_to "be open past midnight" do + before(:each) do + @at = (@at || Time.now).midnight + 12.hours + + @place.add_times([ + {:start => 23.hours, :length => 4.hours, :override => true}, + {:start => 23.hours, :length => 4.hours, :override => false} + ]) + + @place.times.each do |t| + t[:startDate] = @at.to_date + t[:endDate] = @at.to_date + end + + @place.build(@at) + end + + it "should be open early the next morning" do + @place.open(@at.midnight + 1.days + 2.hours).should == true + end + + it "should not be open early that morning" do + @place.open(@at.midnight + 2.hours).should == false + end + + it "should not be open late the next night" do + @place.open(@at.midnight + 2.days + 2.hours).should == false + end + end in_order_to "be closed now" do before(:each) do @place.add_constraint {|t| ( t[:start] > @at.offset ) or ( (t[:start] + t[:length]) < @at.offset ) } @place.add_times([ {:start => 6.hours, :length => 2.hours, :override => false}, {:start => 6.hours, :length => 2.hours, :override => true} ]) @at = Time.now.midnight + 12.hours @place.build end it "should be closed" do @place.open(@at).should == false end end in_order_to "be closed all day" do - end + before(:each) do + @at ||= Time.now - in_order_to "be closed for the day" do - end + @place.add_times([ + {:start => 0, :length => 0, :startDate => @at.to_date, :endDate => @at.to_date, :override => false}, + {:start => 0, :length => 0, :startDate => @at.to_date, :endDate => @at.to_date, :override => false} + ]) - in_order_to "be closed until later in the day" do + @place.build(@at) + end + + it "should be closed now" do + @place.open(@at).should == false + end + + it "should not have a schedule earlier in the day" do + @place.schedule(@at.midnight,@at).should be_empty + end + + it "should not have a schedule later in the day" do + @place.schedule(@at, @at.midnight + 24.hours).should be_empty + end + + it "should not have a schedule at all for the day" do + @place.daySchedule(@at).should be_empty + end end in_order_to "have a valid schedule" do it "should not have any overlapping times" it "should have all times within the specified time range" end end -describe "a Place with all scheduling capabilities", :shared => true do - it_can "be open now" - it_can "be open 24 hours" - it_can "be open later in the day" - it_can "be open earlier in the day" - it_can "be open past midnight (tonight)" - it_can "be open past midnight (last night)" - - it_can "be closed now" - it_can "be closed all day" - it_can "be closed for the day" - it_can "be closed until later in the day" -end - describe "a Place with valid times", :shared => true do describe "with only regular times" do before(:each) do @place.add_constraint {|t| t[:override] == false } @place.build end validate_setup do it "should have regular times" do #puts "Regular Times: #{@place.regular_operating_times.inspect}" @place.regular_operating_times.should_not be_empty end it "should not have any special times" do #puts "Special Times: #{@place.special_operating_times.inspect}" @place.special_operating_times.should be_empty end end it_can "be open now" it_can "be open 24 hours" + it_can "be open past midnight" it_can "be open later in the day" - it_can "be open earlier in the day" - it_can "be open past midnight (tonight)" - it_can "be open past midnight (last night)" - + it_can "be closed for the day" it_can "be closed now" it_can "be closed all day" - it_can "be closed for the day" - it_can "be closed until later in the day" end +=begin describe "with only special times" do before(:each) do @place.add_constraint {|t| t[:override] == true } @place.build end validate_setup do it "should not have regular times" do @place.regular_operating_times.should be_empty end it "should have special times" do @place.special_operating_times.should_not be_empty end end it_can "be open now" it_can "be open 24 hours" + it_can "be open past midnight" it_can "be open later in the day" - it_can "be open earlier in the day" - it_can "be open past midnight (tonight)" - it_can "be open past midnight (last night)" - + it_can "be closed for the day" it_can "be closed now" it_can "be closed all day" - it_can "be closed for the day" - it_can "be closed until later in the day" end describe "with regular and special times" do validate_setup do it "should have regular times" do @place.regular_operating_times.should_not be_empty end it "should have special times" do @place.special_operating_times.should_not be_empty end end describe "where the special times are overriding the regular times" do #it_should_behave_like "a Place with all scheduling capabilities" end describe "where the special times are not overriding the regular times" do #it_should_behave_like "a Place with all scheduling capabilities" end end describe "with special times" do describe "extending normal hours" do #it_should_behave_like "a Place with all scheduling capabilities" end describe "reducing normal hours" do #it_should_behave_like "a Place with all scheduling capabilities" end describe "removing all hours" do #it_should_behave_like "a Place with all scheduling capabilities" end describe "moving normal hours (extending and reducing)" do #it_should_behave_like "a Place with all scheduling capabilities" end end +=end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 1837f3d..91a318e 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,172 +1,172 @@ # This file is copied to ~/spec when you run 'ruby script/generate rspec' # from the project root directory. ENV["RAILS_ENV"] ||= 'test' require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT) require 'spec/autorun' require 'spec/rails' require 'spec/capabilities' Spec::Runner.configure do |config| # If you're not using ActiveRecord you should remove these # lines, delete config/database.yml and disable :active_record # in your config/boot.rb config.use_transactional_fixtures = true config.use_instantiated_fixtures = false config.fixture_path = RAILS_ROOT + '/spec/fixtures/' # == Fixtures # # You can declare fixtures for each example_group like this: # describe "...." do # fixtures :table_a, :table_b # # Alternatively, if you prefer to declare them only once, you can # do so right here. Just uncomment the next line and replace the fixture # names with your fixtures. # # config.global_fixtures = :table_a, :table_b # # If you declare global fixtures, be aware that they will be declared # for all of your examples, even those that don't use them. # # You can also declare which fixtures to use (for example fixtures for test/fixtures): # # config.fixture_path = RAILS_ROOT + '/spec/fixtures/' # # == Mock Framework # # RSpec uses it's own mocking framework by default. If you prefer to # use mocha, flexmock or RR, uncomment the appropriate line: # # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr # # == Notes # # For more information take a look at Spec::Runner::Configuration and Spec::Runner end ConstraintDebugging = false def add_scheduling_spec_helpers(place) place.instance_eval do def operating_times regular_operating_times + special_operating_times end def regular_operating_times @regular_operating_times ||= [] end def special_operating_times @special_operating_times ||= [] end def constraints @constraints ||= [] end def times @times ||= [] end def add_constraint(&block) puts "Adding constraint: #{block.to_s.sub(/^[^\@]*\@/,'')[0..-2]}" if ConstraintDebugging self.constraints << block end # Test +time+ against all constraints for +place+ def acceptable_time(time) if ConstraintDebugging puts "Testing Time: #{time.inspect}" end matched_all = true self.constraints.each do |c| matched = c.call(time) if ConstraintDebugging if matched puts "++ Time accepted by constraint" else puts "-- Time rejected by constraint" end puts " Constraint: #{c.to_s.sub(/^[^\@]*\@/,'')[0..-2]}" end matched_all &= matched end if ConstraintDebugging if matched_all puts "++ Time Accepted" else puts "-- Time Rejected" end puts "" end matched_all end def add_times(new_times = []) new_times.each do |t| unless t[:start] and t[:length] raise ArgumentError, "Must specify a valid start offset and length" end end times.concat(new_times) end - def build + def build(at = Time.now) if ConstraintDebugging puts "Rebuilding #{self}" puts "Constraints:" constraints.each do |c| puts " #{c.to_s.sub(/^[^\@]*\@/,'')[0..-2]}" end puts "Times:" times.each do |t| puts " #{t.inspect}" end end regular_operating_times.clear special_operating_times.clear operating_times.clear self.times.each do |t| t=t.dup if acceptable_time(t) t[:override] ||= false - t[:startDate] ||= Date.yesterday - t[:endDate] ||= Date.tomorrow + t[:startDate] ||= at.to_date - 2 + t[:endDate] ||= at.to_date + 2 t[:daysOfWeek] ||= OperatingTime::ALL_DAYS t[:place_id] ||= self.id ot = OperatingTime.new t.each{|k,v| ot.send(k.to_s+'=',v)} puts "Added time: #{ot.inspect}" if ConstraintDebugging if t[:override] self.special_operating_times << ot else self.regular_operating_times << ot end end end if ConstraintDebugging puts "Regular Times: #{self.regular_operating_times.inspect}" puts "Special Times: #{self.special_operating_times.inspect}" end self end alias :build! :build alias :rebuild :build alias :rebuild! :build end end # add_scheduling_spec_helpers(place)
michaelansel/dukenow
3ee98b9ee1ea2b34965fcfbe7f88d255008161bd
Expand scheduling specs; Move Place extensions into spec_helper; Remove pre-Capabilities specs; Add "offset" method to Date,Time, and DateTime; Fix scheduling errors in Place model
diff --git a/app/models/place.rb b/app/models/place.rb index e225209..f92404e 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,129 +1,140 @@ class Place < ActiveRecord::Base DEBUG = defined? DEBUG ? DEBUG : false has_many :operating_times acts_as_taggable_on :tags validates_presence_of :name def special_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 1}, :order => "startDate ASC, opensAt ASC" ) end def regular_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 0}, :order => "startDate ASC, opensAt ASC" ) end # Returns an array of OperatingTimes def schedule(startAt,endAt) # TODO Returns the schedule for a specified time window # TODO Handle events starting within the range but ending outside of it? # TODO Offload this selection to the database; okay for testing regular_operating_times = regular_operating_times().select{|t| t.startDate <= endAt.to_date and t.endDate >= startAt.to_date} special_operating_times = special_operating_times().select{|t| t.startDate <= endAt.to_date and t.endDate >= startAt.to_date} regular_times = [] special_times = [] special_ranges = [] special_operating_times.each do |ot| puts "\nSpecial Scheduling: #{ot.inspect}" if DEBUG open,close = ot.next_times(startAt-1.day) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do if DEBUG puts "Open: #{open}" puts "Close: #{close}" puts "Start Date: #{ot.startDate} (#{ot.startDate.class})" puts "End Date: #{ot.endDate} (#{ot.endDate.class})" end + if close < startAt # Skip forward to the first occurrance in our time range + open,close = ot.next_times(close) + next + end + special_times << [open,close] special_ranges << Range.new(ot.startDate,ot.endDate) open,close = ot.next_times(close) end end puts "\nSpecial Times: #{special_times.inspect}" if DEBUG puts "\nSpecial Ranges: #{special_ranges.inspect}" if DEBUG regular_operating_times.each do |ot| puts "\nRegular Scheduling: #{ot.inspect}" if DEBUG open,close = ot.next_times(startAt-1.day) next if open.nil? # No valid occurrences in the future while not open.nil? and open <= endAt do puts "Open: #{open}" if DEBUG puts "Close: #{close}" if DEBUG + if close < startAt # Skip forward to the first occurrance in our time range + open,close = ot.next_times(close) + next + end + special_ranges.each do |sr| next if sr.member?(open) end regular_times << [open,close] open,close = ot.next_times(close) end end puts "\nRegular Times: #{regular_times.inspect}" if DEBUG # TODO Handle schedule overrides # TODO Handle combinations (i.e. part special, part regular) (regular_times+special_times).sort{|a,b|a[0] <=> b[0]} end def daySchedule(at = Date.today) at = at.to_date if at.class == Time or at.class == DateTime schedule = schedule(at.midnight,(at+1).midnight) #schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } #schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end =end schedule.sort{|a,b|a[0] <=> b[0]} end def currentSchedule(at = Time.now) + puts "At(cS): #{at}" if DEBUG daySchedule(at).select { |open,close| puts "Open(cS): #{open}" if DEBUG puts "Close(cS): #{close}" if DEBUG open <= at and at <= close }[0] end def open?(at = Time.now) a = currentSchedule(at) return a ? true : false end # Alias for <tt>open?</tt> def open(at = Time.now); open? at ; end def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end def to_xml(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end end diff --git a/config/environment.rb b/config/environment.rb index 7caf417..15305cd 100644 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,76 +1,78 @@ # Be sure to restart your server when you modify this file # Uncomment below to force Rails into production mode when # you don't control web/app server and can't set it the proper way # ENV['RAILS_ENV'] ||= 'production' # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.2.2' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # See Rails::Configuration for more options. # Skip frameworks you're not going to use. To use Rails without a database # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Specify gems that this application depends on. # They can then be installed with "rake gems:install" on new installations. # You have to specify the :lib option for libraries, where the Gem name (sqlite3-ruby) differs from the file itself (sqlite3) # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" config.gem "mbleigh-acts-as-taggable-on", :source => "http://gems.github.com", :lib => "acts-as-taggable-on" # Only load the plugins named here, in the order given. By default, all plugins # in vendor/plugins are loaded in alphabetical order. # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) + require 'date_time' + # Force all environments to use the same logger level # (by default production uses :info, the others :debug) # config.log_level = :debug # Make Time.zone default to the specified zone, and make Active Record store time values # in the database in UTC, and return them converted to the specified local zone. # Run "rake -D time" for a list of tasks for finding time zone names. Comment line to use default local time. #config.time_zone = 'UTC' # The internationalization framework can be changed to have another default locale (standard is :en) or more load paths. # All files from config/locales/*.rb,yml are added automatically. # config.i18n.load_path << Dir[File.join(RAILS_ROOT, 'my', 'locales', '*.{rb,yml}')] # config.i18n.default_locale = :de # Your secret key for verifying cookie session data integrity. # If you change this key, all old sessions will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. config.action_controller.session = { :session_key => '_DukeNow_session', :secret => '8e8355b37da6a989cc5989da3b5bcb79f4b30d3e4b02ecf47ba68d716292194eb939ea71e068c13f3676158f16dd74577017f3838505ef7ed8043f3a65e87741' } # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rake db:sessions:create") # config.action_controller.session_store = :active_record_store # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Activate observers that should always be running # Please note that observers generated using script/generate observer need to have an _observer suffix # config.active_record.observers = :cacher, :garbage_collector, :forum_observer end diff --git a/lib/date_time.rb b/lib/date_time.rb index cda7fd0..6e7004f 100644 --- a/lib/date_time.rb +++ b/lib/date_time.rb @@ -1,23 +1,27 @@ module Midnight def midnight Time.mktime(year, month, day, 0, 0, 0); end + + def offset + @midnight_offset || (@midnight_offset = (self - self.midnight).to_i) + end end require 'date' class Date include Midnight end require 'time' class Time include Midnight end class DateTime include Midnight end diff --git a/spec/models/operating_time_spec.rb b/spec/models/operating_time_spec.rb index 232da51..af0bea2 100644 --- a/spec/models/operating_time_spec.rb +++ b/spec/models/operating_time_spec.rb @@ -1,147 +1,191 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe OperatingTime do before(:each) do @place = mock_model(Place) @valid_attributes = { :place_id => @place.id, :start => (Time.now - 1.hours).to_i, :length => 2.hours, :daysOfWeek => OperatingTime::ALL_DAYS, :startDate => Date.yesterday, :endDate => Date.tomorrow, :override => false } @operating_time = OperatingTime.create!(@valid_attributes) end it "should create a new instance given all valid attributes" do OperatingTime.create!(@valid_attributes) end describe "missing required attributes" do it "should not create a new instance without a valid start time" it "should not create a new instance without a valid length" it "should not create a new instance without a valid Place reference" it "should not create a new instance without a valid start date" it "should not create a new instance without a valid end date" end describe "missing default-able attributes" do it "should default daysOfWeek to 0" do @valid_attributes.delete(:daysOfWeek) if @valid_attributes[:daysOfWeek] OperatingTime.create!(@valid_attributes).daysOfWeek.should == 0 end it "should default override to false" do @valid_attributes.delete(:override) if @valid_attributes[:override] OperatingTime.create!(@valid_attributes).override.should == false end end describe "given invalid attributes" do def create @operating_time = OperatingTime.create!(@valid_attributes) end =begin it "should create a new instance, but ignore an invalid override value" do @valid_attributes[:override] = "invalid" create @operating_time.override.should == false # where false is the default value @valid_attributes[:override] = 10 create @operating_time.override.should == false # where false is the default value end it "should create a new instance, but ignore an invalid daysOfWeek value" do @valid_attributes[:daysOfWeek] = 1000 create @operating_time.daysOfWeek.should == 0 # where 0 is the default value end =end it "should not create a new instance with an invalid start time" it "should not create a new instance with an invalid length" it "should not create a new instance with an invalid Place reference" it "should not create a new instance with an invalid start date" it "should not create a new instance with an invalid end date" end it "should enable override mode" do @operating_time.should_receive(:write_attribute).with(:override, true).exactly(3).times @operating_time.override = true @operating_time.override = "true" @operating_time.override = 1 end it "should disable override mode" do @operating_time.should_receive(:write_attribute).with(:override, false).exactly(3).times @operating_time.override = false @operating_time.override = "false" @operating_time.override = 0 end it "should complain about invalid override values, but not change the value" do @operating_time.override = true @operating_time.override.should == true #TODO Should nil be ignored or errored? lambda { @operating_time.override = nil }.should raise_error(ArgumentError) @operating_time.override.should == true lambda { @operating_time.override = "invalid" }.should raise_error(ArgumentError) @operating_time.override.should == true lambda { @operating_time.override = false }.should_not raise_error @operating_time.override.should == false end it "should complain about invalid daysOfWeek values, but not change the value" do @operating_time.daysOfWeek = OperatingTime::SUNDAY @operating_time.daysOfWeek.should == OperatingTime::SUNDAY #TODO Should nil be ignored or errored? lambda { @operating_time.daysOfWeek = nil }.should raise_error(ArgumentError) @operating_time.daysOfWeek.should == OperatingTime::SUNDAY lambda { @operating_time.daysOfWeek = 200 }.should raise_error(ArgumentError) @operating_time.daysOfWeek.should == OperatingTime::SUNDAY lambda { @operating_time.daysOfWeek= OperatingTime::MONDAY }.should_not raise_error @operating_time.daysOfWeek.should == OperatingTime::MONDAY end describe "with open and close times" do before(:each) do @now = Time.now.midnight + 15.minutes @open = @now.midnight + 23.hours + 30.minutes @close = @open + 1.hour start = @open - @open.midnight length = @close - @open @valid_attributes.update({ :start => start, :length => length }) @operating_time = OperatingTime.create!(@valid_attributes) end it "should return valid open and close times for 'now'" do open,close = @operating_time.next_times() open.to_s.should == @open.to_s close.to_s.should == @close.to_s end it "should return valid open and close times for a given time" do @open, @close, @now = [@open,@close,@now].collect{|t| t + 5.days} @operating_time.endDate += 5 open,close = @operating_time.next_times( @now ) open.to_s.should == @open.to_s close.to_s.should == @close.to_s end end end + + + +### Midnight Module Specs ### + +describe Date do + before(:each) do + @date = Date.today + end + + it "should have a valid midnight" do + @date.should respond_to(:midnight) + @date.midnight.should == Time.mktime(@date.year, @date.month, @date.day, 0, 0, 0) + end +end + +describe Time do + before(:each) do + @time = Time.now + end + + it "should have a valid midnight" do + @time.should respond_to(:midnight) + @time.midnight.should == Time.mktime(@time.year, @time.month, @time.day, 0, 0, 0) + end + + it "should have a valid midnight offset" do + @time.should respond_to(:offset) + @time.offset.should == @time.hour.hours + @time.min.minutes + @time.sec + end +end + +describe DateTime do + before(:each) do + @dt = DateTime.now + end + + it "should have a valid midnight" do + @dt.should respond_to(:midnight) + @dt.midnight.should == Time.mktime(@dt.year, @dt.month, @dt.day, 0, 0, 0) + end +end + +### End Midnight Module Specs ### diff --git a/spec/models/place_spec.rb b/spec/models/place_spec.rb index 839f14b..fdb44d0 100644 --- a/spec/models/place_spec.rb +++ b/spec/models/place_spec.rb @@ -1,265 +1,99 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') require File.expand_path(File.dirname(__FILE__) + '/schedules') describe Place do before(:each) do @valid_attributes = { :name => 'Test Place', :location => 'Somewhere', :phone => '(919) 555-1212' } @place = Place.create!(@valid_attributes) - - @place.class_eval <<EOM - attr_accessor :constraints - - def operating_times - regular_operating_times + special_operating_times - end - - def regular_operating_times - @regular_operating_times ||= [] - end - def special_operating_times - @special_operating_times ||= [] - end -EOM - @place.regular_operating_times.should == [] - @place.special_operating_times.should == [] end - it "should create a new instance given valid attributes" do - Place.create!(@valid_attributes) + it "should create a new, valid instance given valid attributes" do + Place.create!(@valid_attributes).should be_valid end it "should not create a new instance without a name" do @valid_attributes.delete(:name) lambda { Place.create!(@valid_attributes) }.should raise_error end it "should produce valid XML" it "should produce valid JSON" ############################## ### ### ### Scheduling ### ### ### ############################## it_should_behave_like "a Place with scheduling capabilities" it_should_behave_like "a Place with valid times" describe "a Place with no times" do before(:each) do # Don't allow any times - add_constraint(@place){ false } + @place.add_constraint { false } @at = Time.now.midnight + 7.hours end it_can "be closed now", "be closed all day", "be closed for the day" end end =begin # TODO Create mocks for OperatingTime so we can test the scheduling methods describe "a Place with OperatingTimes", :shared => true do describe "that are valid now" do it "should have a valid schedule" do end it "should have a valid daily schedule" it "should have a valid current schedule" it "should have regular OperatingTimes" it "should have special OperatingTimes" end describe "that are not valid now" do end end describe Place do before(:each) do @valid_attributes = { :name => 'Test Place', :location => 'Somewhere', :phone => '(919) 555-1212' } end - it "should create a new instance given valid attributes" do - Place.create!(@valid_attributes) - end - - it "should not create a new instance without a name" do - @valid_attributes.delete(:name) - lambda { Place.create!(@valid_attributes) }.should raise_error - end - it "should build a valid dailySchedule" do #TODO Test against a valid schedule as well place = Place.create!(@valid_attributes) place.should_receive(:schedule).with(instance_of(Time), instance_of(Time)).and_return([]) place.daySchedule(Date.today).should == [] end - describe "with only special OperatingTimes" do - end - describe "with only regular OperatingTimes" do - end - describe "with special OperatingTimes overriding regular OperatingTimes" do - end - - describe "that is currently open" do - it_should_behave_like "a Place with OperatingTimes" - - before(:each) do - @at = Time.now.midnight + 7.hours - @currentSchedule = stub_times([{:start => 6.hours, :length => 2.hours}]) - @daySchedule = [@currentSchedule] - - @place = Place.create!(@valid_attributes) - @place.stub(:operating_times).and_return(@currentSchedule) - @place.stub(:regular_operating_times).and_return(@currentSchedule) - @place.stub(:special_operating_times).and_return(@currentSchedule) - end - - it "should produce a valid daySchedule" do - end - - it "should produce a valid currentSchedule" do - end - - it "should be open" do - @place.should_receive(:currentSchedule). - with(duck_type(:midnight)). - and_return(@currentSchedule) - - @place.open?(@at).should == true - end - end - - describe "that is closed, but opens later today" do - it_should_behave_like "a Place with OperatingTimes" - - it "should be closed" - it "should have a schedule for later today" - end - - describe "that is closed for the day" do - it_should_behave_like "a Place with OperatingTimes" - - it "should be closed" - end - describe "that is not open at all today" do - it_should_behave_like "a Place with OperatingTimes" - - it "should be closed" - it "should not have a schedule for the remainder of today" - end - - describe "that is open past midnight today" do - it_should_behave_like "a Place with OperatingTimes" - end - describe "that was open past midnight yesterday" do - it_should_behave_like "a Place with OperatingTimes" - end ###### Special Schedules ###### describe "that is normally open, but closed all day today" do it_should_behave_like "a Place with OperatingTimes" end describe "that has special (extended) hours" do it_should_behave_like "a Place with OperatingTimes" end describe "that has special (shortened) hours" do it_should_behave_like "a Place with OperatingTimes" end end - - - - -describe "a capable Place", :shared => true do - it_can_be "closed all day", "closed for the day", "closed until later today" - #it_can_be "open past midnight tonight", "open past midnight last night" - #it_can_be "open now", "closed now" -end - -describe "a happy Place" do - in_order_to_be "closed all day" do - - it "should be closed right now" do - pending("There ain't no @place to test!") { @place.open?(@at) } - @place.open?(@at).should == false - end - - it "should have an empty schedule for the day" - it "should not have a current schedule" - end - - in_order_to_be "closed for the day" do - before(:each) do - end - - it "should be closed right now" - it "should not have a current schedule" - it_can "have no schedule elements later in the day" - it_can "have schedule elements earlier in the day", "have no schedule elements earlier in the day" - end - - in_order_to_be "closed until later today" do - before(:each) do - end - - end - - in_order_to "have schedule elements earlier in the day" do - end - - in_order_to "have no schedule elements earlier in the day" do - end - - in_order_to "have schedule elements later in the day" do - end - - in_order_to "have no schedule elements later in the day" do - end - - it_can_be "closed all day", "closed for the day", "closed until later today" - - describe "that has regular times" do - describe "without special times" do - it_should_behave_like "a capable Place" - end - - describe "with special times" do - describe "overriding the regular times" do - it_should_behave_like "a capable Place" - end - - describe "not overriding the regular times" do - it_should_behave_like "a capable Place" - end - end - end - - describe "that has no regular times" do - describe "and no special times" do - it_should_behave_like "a capable Place" - end - - describe "but has special times" do - it_should_behave_like "a capable Place" - end - end - -end =end diff --git a/spec/models/schedules.rb b/spec/models/schedules.rb index fb3ba34..825796d 100644 --- a/spec/models/schedules.rb +++ b/spec/models/schedules.rb @@ -1,295 +1,274 @@ ###################### ##### Scheduling ##### ###################### -ConstraintDebugging = false -def add_constraint(place, &block) - place.constraints ||= [] - place.constraints << block -end - -# Test +time+ against all constraints for +place+ -def acceptable_time(place, time) - if ConstraintDebugging - puts "Testing Time: #{time.inspect}" - end - - matched_all = true - place.constraints.each do |c| - matched = c.call(time) - - if ConstraintDebugging - if matched - puts "++ Time accepted by constraint" - else - puts "-- Time rejected by constraint" - end - puts " Constraint: #{c.to_s.sub(/^[^\@]*\@/,'')[0..-2]}" - end - - matched_all &= matched - end - - if ConstraintDebugging - if matched_all - puts "++ Time Accepted" - else - puts "-- Time Rejected" - end - puts "" - end - - matched_all -end - -def add_times(place, times = []) - times.each do |t| - unless t[:start] and t[:length] - raise ArgumentError, "Must specify a valid start offset and length" - end - - if acceptable_time(place, t) - t[:override] ||= false - t[:startDate] ||= Date.yesterday - t[:endDate] ||= Date.tomorrow - t[:daysOfWeek] ||= OperatingTime::ALL_DAYS - t[:place_id] ||= place.id - ot = OperatingTime.new - t.each{|k,v| ot.send(k.to_s+'=',v)} - - puts "Added time: #{ot.inspect}" if ConstraintDebugging - - if t[:override] - place.special_operating_times << ot - else - place.regular_operating_times << ot - end - end +describe "a Place with scheduling capabilities", :shared => true do + before(:each) do + add_scheduling_spec_helpers(@place) end - if ConstraintDebugging - puts "Regular Times: #{place.regular_operating_times.inspect}" - puts "Special Times: #{place.special_operating_times.inspect}" + it "should be clean" do + @place.regular_operating_times.should == [] + @place.special_operating_times.should == [] + @place.constraints.should == [] + @place.times.should == [] end - place -end - -def remove_times(place, times = []) -end - - -describe "a Place with scheduling capabilities", :shared => true do - in_order_to "be open now" do + describe "can be open now, so" do before(:each) do - add_times(@place,[ + @place.add_times([ {:start => 6.hours, :length => 2.hours, :override => false}, {:start => 6.hours, :length => 2.hours, :override => true} ]) - @at = Time.now.midnight + 7.hours + @at = (@at || Time.now).midnight + 7.hours + + @place.build end - it "should have a schedule" do + it "should have operating times" do @place.operating_times.should_not be_empty + end + + it "should have a schedule" do @place.schedule(@at.midnight, @at.midnight + 1.day).should_not be_empty + end + + it "should have a daySchedule" do @place.daySchedule(@at).should_not be_empty + end + + it "should have a currentSchedule" do + #puts "\n\n\n\n\n\nDay Schedule: \n#{@place.daySchedule(@at).collect{|a,b| a.inspect + " to " + b.inspect}.join("\n")}\n\n\n\n\n\n" @place.currentSchedule(@at).should_not be_nil end it "should be open today" do @place.open(@at).should == true end it "should be open \"now\" in the past" do - @at += 12.days + @at -= 12.days @place.operating_times.each do |t| - t.endDate += 12 + t.startDate -= 12 end @place.open(@at).should == true end it "should be open \"now\" in the future" do - @at -= 12.days + @at += 12.days @place.operating_times.each do |t| - t.startDate -= 12 + t.endDate += 12 end + + @place.open(@at).should == true + end end end in_order_to "be open 24 hours" do + before(:each) do + @place.add_times([ + {:start => 0, :length => 24.hours, :override => false}, + {:start => 0, :length => 24.hours, :override => true} + ]) + @at = Time.now.midnight + 12.hours + + @place.build + end + + it "should be open during the day" do + @place.open(@at).should == true + end + + it "should be open at midnight" do + @place.open(@at.midnight).should == true + end end in_order_to "be open later in the day" do before(:each) do - add_times(@place,[ + @place.add_times([ {:start => 16.hours, :length => 2.hours, :override => false}, {:start => 16.hours, :length => 2.hours, :override => true} ]) @at = Time.now.midnight + 12.hours + + @place.build end it "should have a schedule between now and midnight" do @place.schedule(@at,@at.midnight + 24.hours).size.should > 0 end end in_order_to "be open earlier in the day" do end in_order_to "be open past midnight (tonight)" do before(:each) do @at = Time.now.midnight + + @place.build end end in_order_to "be open past midnight (last night)" do end in_order_to "be closed now" do before(:each) do - #add_constraint(@place) {|t| ( t[:start] > (@at - @at.midnight) ) or - #( (t[:start] + t[:length]) < (@at - @at.midnight) ) } - add_times(@place,[ + @place.add_constraint {|t| ( t[:start] > @at.offset ) or + ( (t[:start] + t[:length]) < @at.offset ) } + @place.add_times([ {:start => 6.hours, :length => 2.hours, :override => false}, {:start => 6.hours, :length => 2.hours, :override => true} ]) - @at = Time.now.midnight + 9.hours + @at = Time.now.midnight + 12.hours + + @place.build end it "should be closed" do @place.open(@at).should == false end end in_order_to "be closed all day" do end in_order_to "be closed for the day" do end in_order_to "be closed until later in the day" do end in_order_to "have a valid schedule" do it "should not have any overlapping times" it "should have all times within the specified time range" end end describe "a Place with all scheduling capabilities", :shared => true do it_can "be open now" it_can "be open 24 hours" it_can "be open later in the day" it_can "be open earlier in the day" it_can "be open past midnight (tonight)" it_can "be open past midnight (last night)" it_can "be closed now" it_can "be closed all day" it_can "be closed for the day" it_can "be closed until later in the day" end describe "a Place with valid times", :shared => true do - before(:each) do - add_constraint(@place) { true } - end - describe "with only regular times" do before(:each) do - add_constraint(@place) {|t| t[:override] == false } + @place.add_constraint {|t| t[:override] == false } + + @place.build end validate_setup do it "should have regular times" do #puts "Regular Times: #{@place.regular_operating_times.inspect}" @place.regular_operating_times.should_not be_empty end it "should not have any special times" do #puts "Special Times: #{@place.special_operating_times.inspect}" @place.special_operating_times.should be_empty end end it_can "be open now" - #it_can "be open 24 hours" - #it_can "be open later in the day" - #it_can "be open earlier in the day" - #it_can "be open past midnight (tonight)" - #it_can "be open past midnight (last night)" + it_can "be open 24 hours" + it_can "be open later in the day" + it_can "be open earlier in the day" + it_can "be open past midnight (tonight)" + it_can "be open past midnight (last night)" - #it_can "be closed now" - #it_can "be closed all day" - #it_can "be closed for the day" - #it_can "be closed until later in the day" + it_can "be closed now" + it_can "be closed all day" + it_can "be closed for the day" + it_can "be closed until later in the day" end describe "with only special times" do before(:each) do - add_constraint(@place) {|t| t[:override] == true } + @place.add_constraint {|t| t[:override] == true } + + @place.build end validate_setup do it "should not have regular times" do @place.regular_operating_times.should be_empty end it "should have special times" do @place.special_operating_times.should_not be_empty end end it_can "be open now" - #it_can "be open 24 hours" - #it_can "be open later in the day" - #it_can "be open earlier in the day" - #it_can "be open past midnight (tonight)" - #it_can "be open past midnight (last night)" + it_can "be open 24 hours" + it_can "be open later in the day" + it_can "be open earlier in the day" + it_can "be open past midnight (tonight)" + it_can "be open past midnight (last night)" - #it_can "be closed now" - #it_can "be closed all day" - #it_can "be closed for the day" - #it_can "be closed until later in the day" + it_can "be closed now" + it_can "be closed all day" + it_can "be closed for the day" + it_can "be closed until later in the day" end describe "with regular and special times" do + validate_setup do + it "should have regular times" do + @place.regular_operating_times.should_not be_empty + end + + it "should have special times" do + @place.special_operating_times.should_not be_empty + end + end + describe "where the special times are overriding the regular times" do #it_should_behave_like "a Place with all scheduling capabilities" end describe "where the special times are not overriding the regular times" do #it_should_behave_like "a Place with all scheduling capabilities" end end describe "with special times" do describe "extending normal hours" do #it_should_behave_like "a Place with all scheduling capabilities" end describe "reducing normal hours" do #it_should_behave_like "a Place with all scheduling capabilities" end describe "removing all hours" do #it_should_behave_like "a Place with all scheduling capabilities" end describe "moving normal hours (extending and reducing)" do #it_should_behave_like "a Place with all scheduling capabilities" end end end - - - diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index fa95031..1837f3d 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,48 +1,172 @@ # This file is copied to ~/spec when you run 'ruby script/generate rspec' # from the project root directory. ENV["RAILS_ENV"] ||= 'test' require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT) require 'spec/autorun' require 'spec/rails' require 'spec/capabilities' Spec::Runner.configure do |config| # If you're not using ActiveRecord you should remove these # lines, delete config/database.yml and disable :active_record # in your config/boot.rb config.use_transactional_fixtures = true config.use_instantiated_fixtures = false config.fixture_path = RAILS_ROOT + '/spec/fixtures/' # == Fixtures # # You can declare fixtures for each example_group like this: # describe "...." do # fixtures :table_a, :table_b # # Alternatively, if you prefer to declare them only once, you can # do so right here. Just uncomment the next line and replace the fixture # names with your fixtures. # # config.global_fixtures = :table_a, :table_b # # If you declare global fixtures, be aware that they will be declared # for all of your examples, even those that don't use them. # # You can also declare which fixtures to use (for example fixtures for test/fixtures): # # config.fixture_path = RAILS_ROOT + '/spec/fixtures/' # # == Mock Framework # # RSpec uses it's own mocking framework by default. If you prefer to # use mocha, flexmock or RR, uncomment the appropriate line: # # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr # # == Notes # # For more information take a look at Spec::Runner::Configuration and Spec::Runner end + + +ConstraintDebugging = false +def add_scheduling_spec_helpers(place) + place.instance_eval do + + def operating_times + regular_operating_times + special_operating_times + end + + def regular_operating_times + @regular_operating_times ||= [] + end + def special_operating_times + @special_operating_times ||= [] + end + def constraints + @constraints ||= [] + end + def times + @times ||= [] + end + + + def add_constraint(&block) + puts "Adding constraint: #{block.to_s.sub(/^[^\@]*\@/,'')[0..-2]}" if ConstraintDebugging + self.constraints << block + end + + # Test +time+ against all constraints for +place+ + def acceptable_time(time) + if ConstraintDebugging + puts "Testing Time: #{time.inspect}" + end + + matched_all = true + self.constraints.each do |c| + matched = c.call(time) + + if ConstraintDebugging + if matched + puts "++ Time accepted by constraint" + else + puts "-- Time rejected by constraint" + end + puts " Constraint: #{c.to_s.sub(/^[^\@]*\@/,'')[0..-2]}" + end + + matched_all &= matched + end + + if ConstraintDebugging + if matched_all + puts "++ Time Accepted" + else + puts "-- Time Rejected" + end + puts "" + end + + matched_all + end + + def add_times(new_times = []) + new_times.each do |t| + unless t[:start] and t[:length] + raise ArgumentError, "Must specify a valid start offset and length" + end + end + times.concat(new_times) + end + + def build + if ConstraintDebugging + puts "Rebuilding #{self}" + puts "Constraints:" + constraints.each do |c| + puts " #{c.to_s.sub(/^[^\@]*\@/,'')[0..-2]}" + end + puts "Times:" + times.each do |t| + puts " #{t.inspect}" + end + end + + regular_operating_times.clear + special_operating_times.clear + operating_times.clear + + self.times.each do |t| + t=t.dup + if acceptable_time(t) + t[:override] ||= false + t[:startDate] ||= Date.yesterday + t[:endDate] ||= Date.tomorrow + t[:daysOfWeek] ||= OperatingTime::ALL_DAYS + t[:place_id] ||= self.id + ot = OperatingTime.new + t.each{|k,v| ot.send(k.to_s+'=',v)} + + puts "Added time: #{ot.inspect}" if ConstraintDebugging + + if t[:override] + self.special_operating_times << ot + else + self.regular_operating_times << ot + end + + end + end + + if ConstraintDebugging + puts "Regular Times: #{self.regular_operating_times.inspect}" + puts "Special Times: #{self.special_operating_times.inspect}" + end + + self + end + alias :build! :build + alias :rebuild :build + alias :rebuild! :build + + end +end # add_scheduling_spec_helpers(place)
michaelansel/dukenow
7eccd0ef99386cc703eca6c59d4a42d8498a2b17
Minor refactoring and spec fixes for OperatingTime and Place
diff --git a/app/models/operating_time.rb b/app/models/operating_time.rb index 35da623..6f5eac9 100644 --- a/app/models/operating_time.rb +++ b/app/models/operating_time.rb @@ -1,229 +1,224 @@ class OperatingTime < ActiveRecord::Base belongs_to :place validates_presence_of :place_id validates_associated :place validate :end_after_start, :daysOfWeek_valid ## DaysOfWeek Constants ## SUNDAY = 0b00000001 MONDAY = 0b00000010 TUESDAY = 0b00000100 WEDNESDAY = 0b00001000 THURSDAY = 0b00010000 FRIDAY = 0b00100000 SATURDAY = 0b01000000 ALL_DAYS = (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) ## Validations ## def end_after_start if endDate < startDate errors.add_to_base("End date cannot preceed start date") end end def daysOfWeek_valid daysOfWeek == daysOfWeek & (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) end ## End Validations ## # TODO Is this OperatingTime applicable at +time+ def valid_at(time=Time.now) raise NotImplementedError end def override read_attribute(:override) == 1 end def override=(mode) if mode == true or mode == "true" or mode == 1 write_attribute(:override, true) elsif mode == false or mode == "false" or mode == 0 write_attribute(:override, false) else raise ArgumentError, "Invalid override value (#{mode.inspect}); Accepts true/false, 1/0" end end def daysOfWeek=(newDow) if not ( newDow & ALL_DAYS == newDow ) # Invalid input raise ArgumentError, "Not a valid value for daysOfWeek (#{newDow.inspect})" end write_attribute(:daysOfWeek, newDow & ALL_DAYS) @daysOfWeekHash = nil @daysOfWeekArray = nil @daysOfWeekString = nil end ## daysOfWeek Helper/Accessors ## # Hash mapping day of week (Symbol) to valid(true)/invalid(false) def daysOfWeekHash @daysOfWeekHash ||= { :sunday => (daysOfWeek & SUNDAY ) > 0, :monday => (daysOfWeek & MONDAY ) > 0, :tuesday => (daysOfWeek & TUESDAY ) > 0, :wednesday => (daysOfWeek & WEDNESDAY ) > 0, :thursday => (daysOfWeek & THURSDAY ) > 0, :friday => (daysOfWeek & FRIDAY ) > 0, :saturday => (daysOfWeek & SATURDAY ) > 0 } end # Array beginning with Sunday of valid(true)/inactive(false) values def daysOfWeekArray dow = daysOfWeekHash @daysOfWeekArray ||= [ dow[:sunday], dow[:monday], dow[:tuesday], dow[:wednesday], dow[:thursday], dow[:friday], dow[:saturday] ] end # Human-readable string of applicable days of week def daysOfWeekString dow = daysOfWeekHash @daysOfWeekString ||= (dow[:sunday] ? "Su" : "") + (dow[:monday] ? "M" : "") + (dow[:tuesday] ? "Tu" : "") + (dow[:wednesday] ? "W" : "") + (dow[:thursday] ? "Th" : "") + (dow[:friday] ? "F" : "") + (dow[:saturday] ? "Sa" : "") end ## End daysOfWeek Helper/Accessors ## - # Return array of times representing the open and close times at a certain occurence - def to_times(at = Time.now) - # TODO Verify this is a valid occurrence - open = at.midnight + start - close = open + length - [open,close] - end - def to_xml(params) super(params.merge({:only => [:id, :place_id, :flags], :methods => [ :opensAt, :closesAt, :startDate, :endDate ]})) end # Returns the next full occurrence of these operating time rule. # If we are currently within a valid time range, it will look forward for the # <em>next</em> opening time def next_times(at = Time.now) return nil if at > endDate # This schedule has ended at = startDate.midnight if at < startDate # This schedule hasn't started yet, skip to startDate # Next occurrence is later today # This is the only time the "time" actually matters; # after today, all we care about is the date if daysOfWeekArray[at.wday] and start >= (at - at.midnight) - return to_times(at) + open = at.midnight + start + close = open + length + return [open,close] end # We don't care about the time offset anymore, jump to the next midnight at = at.midnight + 1.day # TODO Test for Sun, Sat, and one of M-F dow = daysOfWeekArray[at.wday..-1] + daysOfWeekArray[0..at.wday] # Next day of the week this schedule is valid for shift = dow.index(true) if shift # Skip forward at = at + shift.days else # Give up, there are no more occurrences # TODO Test edge case: valid for 1 day/week return nil end # Recurse to rerun the validation routines return next_times(at) end + alias :to_times :next_times ##### TODO DEPRECATED METHODS ##### def at @at end def at=(time) @opensAt = nil @closesAt = nil @at = time end # Returns a Time object representing the beginning of this OperatingTime def opensAt @opensAt ||= relativeTime.openTime(at) end def closesAt @closesAt ||= relativeTime.closeTime(at) end # Sets the beginning of this OperatingTime # Input: params = { :hour => 12, :minute => 45 } def opensAt=(time) if time.class == Time @opensAt = relativeTime.openTime = time else super end end # Sets the end of this OperatingTime def closesAt=(time) @closesAt = relativeTime.closeTime = time end def start read_attribute(:opensAt) end def start=(offset) write_attribute(:opensAt,offset) end # Returns a RelativeTime object representing this OperatingTime def relativeTime @relativeTime ||= RelativeTime.new(self, :opensAt, :length) end; protected :relativeTime # Backwards compatibility with old database schema # TODO GET RID OF THIS!!! def flags ( (override ? 1 : 0) << 7) | read_attribute(:daysOfWeek) end # FIXME Deprecated, use +override+ instead def special override end # Input: isSpecial = true/false # FIXME Deprecated, use +override=+ instead def special=(isSpecial) if isSpecial == true or isSpecial == "true" or isSpecial == 1 self.override = true elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 self.override = false end end end diff --git a/spec/models/operating_time_spec.rb b/spec/models/operating_time_spec.rb index 26b2e15..232da51 100644 --- a/spec/models/operating_time_spec.rb +++ b/spec/models/operating_time_spec.rb @@ -1,146 +1,147 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe OperatingTime do before(:each) do @place = mock_model(Place) @valid_attributes = { :place_id => @place.id, - :opensAt => (Time.now - 1.hours).to_i, + :start => (Time.now - 1.hours).to_i, :length => 2.hours, :daysOfWeek => OperatingTime::ALL_DAYS, :startDate => Date.yesterday, :endDate => Date.tomorrow, :override => false } @operating_time = OperatingTime.create!(@valid_attributes) end it "should create a new instance given all valid attributes" do OperatingTime.create!(@valid_attributes) end describe "missing required attributes" do it "should not create a new instance without a valid start time" it "should not create a new instance without a valid length" it "should not create a new instance without a valid Place reference" it "should not create a new instance without a valid start date" it "should not create a new instance without a valid end date" end describe "missing default-able attributes" do it "should default daysOfWeek to 0" do @valid_attributes.delete(:daysOfWeek) if @valid_attributes[:daysOfWeek] OperatingTime.create!(@valid_attributes).daysOfWeek.should == 0 end it "should default override to false" do @valid_attributes.delete(:override) if @valid_attributes[:override] OperatingTime.create!(@valid_attributes).override.should == false end end describe "given invalid attributes" do def create @operating_time = OperatingTime.create!(@valid_attributes) end =begin it "should create a new instance, but ignore an invalid override value" do @valid_attributes[:override] = "invalid" create @operating_time.override.should == false # where false is the default value @valid_attributes[:override] = 10 create @operating_time.override.should == false # where false is the default value end it "should create a new instance, but ignore an invalid daysOfWeek value" do @valid_attributes[:daysOfWeek] = 1000 create @operating_time.daysOfWeek.should == 0 # where 0 is the default value end =end it "should not create a new instance with an invalid start time" it "should not create a new instance with an invalid length" it "should not create a new instance with an invalid Place reference" it "should not create a new instance with an invalid start date" it "should not create a new instance with an invalid end date" end it "should enable override mode" do @operating_time.should_receive(:write_attribute).with(:override, true).exactly(3).times @operating_time.override = true @operating_time.override = "true" @operating_time.override = 1 end it "should disable override mode" do @operating_time.should_receive(:write_attribute).with(:override, false).exactly(3).times @operating_time.override = false @operating_time.override = "false" @operating_time.override = 0 end it "should complain about invalid override values, but not change the value" do @operating_time.override = true @operating_time.override.should == true #TODO Should nil be ignored or errored? lambda { @operating_time.override = nil }.should raise_error(ArgumentError) @operating_time.override.should == true lambda { @operating_time.override = "invalid" }.should raise_error(ArgumentError) @operating_time.override.should == true lambda { @operating_time.override = false }.should_not raise_error @operating_time.override.should == false end it "should complain about invalid daysOfWeek values, but not change the value" do @operating_time.daysOfWeek = OperatingTime::SUNDAY @operating_time.daysOfWeek.should == OperatingTime::SUNDAY #TODO Should nil be ignored or errored? lambda { @operating_time.daysOfWeek = nil }.should raise_error(ArgumentError) @operating_time.daysOfWeek.should == OperatingTime::SUNDAY lambda { @operating_time.daysOfWeek = 200 }.should raise_error(ArgumentError) @operating_time.daysOfWeek.should == OperatingTime::SUNDAY lambda { @operating_time.daysOfWeek= OperatingTime::MONDAY }.should_not raise_error @operating_time.daysOfWeek.should == OperatingTime::MONDAY end describe "with open and close times" do before(:each) do - @now = Time.now + @now = Time.now.midnight + 15.minutes - @open = @now - 1.hours - @close = @now + 1.hours + @open = @now.midnight + 23.hours + 30.minutes + @close = @open + 1.hour start = @open - @open.midnight length = @close - @open @valid_attributes.update({ - :opensAt => start, + :start => start, :length => length }) @operating_time = OperatingTime.create!(@valid_attributes) end it "should return valid open and close times for 'now'" do - open,close = @operating_time.to_times() - open.to_i.should == @open.to_i - close.to_i.should == @close.to_i + open,close = @operating_time.next_times() + open.to_s.should == @open.to_s + close.to_s.should == @close.to_s end it "should return valid open and close times for a given time" do @open, @close, @now = [@open,@close,@now].collect{|t| t + 5.days} + @operating_time.endDate += 5 - open,close = @operating_time.to_times( @now ) - open.to_i.should == @open.to_i - close.to_i.should == @close.to_i + open,close = @operating_time.next_times( @now ) + open.to_s.should == @open.to_s + close.to_s.should == @close.to_s end end end diff --git a/spec/models/place_spec.rb b/spec/models/place_spec.rb index 1377418..839f14b 100644 --- a/spec/models/place_spec.rb +++ b/spec/models/place_spec.rb @@ -1,256 +1,265 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') require File.expand_path(File.dirname(__FILE__) + '/schedules') describe Place do before(:each) do @valid_attributes = { :name => 'Test Place', :location => 'Somewhere', :phone => '(919) 555-1212' } @place = Place.create!(@valid_attributes) @place.class_eval <<EOM attr_accessor :constraints def operating_times regular_operating_times + special_operating_times end def regular_operating_times @regular_operating_times ||= [] end def special_operating_times @special_operating_times ||= [] end EOM @place.regular_operating_times.should == [] @place.special_operating_times.should == [] end - it_should_behave_like "a Place with scheduling capabilities" - it_should_behave_like "a Place with valid times" - it "should create a new instance given valid attributes" do Place.create!(@valid_attributes) end it "should not create a new instance without a name" do @valid_attributes.delete(:name) lambda { Place.create!(@valid_attributes) }.should raise_error end + it "should produce valid XML" + + it "should produce valid JSON" + + ############################## + ### ### + ### Scheduling ### + ### ### + ############################## + + it_should_behave_like "a Place with scheduling capabilities" + it_should_behave_like "a Place with valid times" + describe "a Place with no times" do before(:each) do + # Don't allow any times add_constraint(@place){ false } @at = Time.now.midnight + 7.hours - @open_at = @at.midnight + 7.hours - @closed_at = @at.midnight + 2.hours end it_can "be closed now", "be closed all day", "be closed for the day" end end =begin # TODO Create mocks for OperatingTime so we can test the scheduling methods describe "a Place with OperatingTimes", :shared => true do describe "that are valid now" do it "should have a valid schedule" do end it "should have a valid daily schedule" it "should have a valid current schedule" it "should have regular OperatingTimes" it "should have special OperatingTimes" end describe "that are not valid now" do end end describe Place do before(:each) do @valid_attributes = { :name => 'Test Place', :location => 'Somewhere', :phone => '(919) 555-1212' } end it "should create a new instance given valid attributes" do Place.create!(@valid_attributes) end it "should not create a new instance without a name" do @valid_attributes.delete(:name) lambda { Place.create!(@valid_attributes) }.should raise_error end it "should build a valid dailySchedule" do #TODO Test against a valid schedule as well place = Place.create!(@valid_attributes) place.should_receive(:schedule).with(instance_of(Time), instance_of(Time)).and_return([]) place.daySchedule(Date.today).should == [] end describe "with only special OperatingTimes" do end describe "with only regular OperatingTimes" do end describe "with special OperatingTimes overriding regular OperatingTimes" do end describe "that is currently open" do it_should_behave_like "a Place with OperatingTimes" before(:each) do @at = Time.now.midnight + 7.hours @currentSchedule = stub_times([{:start => 6.hours, :length => 2.hours}]) @daySchedule = [@currentSchedule] @place = Place.create!(@valid_attributes) @place.stub(:operating_times).and_return(@currentSchedule) @place.stub(:regular_operating_times).and_return(@currentSchedule) @place.stub(:special_operating_times).and_return(@currentSchedule) end it "should produce a valid daySchedule" do end it "should produce a valid currentSchedule" do end it "should be open" do @place.should_receive(:currentSchedule). with(duck_type(:midnight)). and_return(@currentSchedule) @place.open?(@at).should == true end end describe "that is closed, but opens later today" do it_should_behave_like "a Place with OperatingTimes" it "should be closed" it "should have a schedule for later today" end describe "that is closed for the day" do it_should_behave_like "a Place with OperatingTimes" it "should be closed" end describe "that is not open at all today" do it_should_behave_like "a Place with OperatingTimes" it "should be closed" it "should not have a schedule for the remainder of today" end describe "that is open past midnight today" do it_should_behave_like "a Place with OperatingTimes" end describe "that was open past midnight yesterday" do it_should_behave_like "a Place with OperatingTimes" end ###### Special Schedules ###### describe "that is normally open, but closed all day today" do it_should_behave_like "a Place with OperatingTimes" end describe "that has special (extended) hours" do it_should_behave_like "a Place with OperatingTimes" end describe "that has special (shortened) hours" do it_should_behave_like "a Place with OperatingTimes" end end describe "a capable Place", :shared => true do it_can_be "closed all day", "closed for the day", "closed until later today" #it_can_be "open past midnight tonight", "open past midnight last night" #it_can_be "open now", "closed now" end describe "a happy Place" do in_order_to_be "closed all day" do it "should be closed right now" do pending("There ain't no @place to test!") { @place.open?(@at) } @place.open?(@at).should == false end it "should have an empty schedule for the day" it "should not have a current schedule" end in_order_to_be "closed for the day" do before(:each) do end it "should be closed right now" it "should not have a current schedule" it_can "have no schedule elements later in the day" it_can "have schedule elements earlier in the day", "have no schedule elements earlier in the day" end in_order_to_be "closed until later today" do before(:each) do end end in_order_to "have schedule elements earlier in the day" do end in_order_to "have no schedule elements earlier in the day" do end in_order_to "have schedule elements later in the day" do end in_order_to "have no schedule elements later in the day" do end it_can_be "closed all day", "closed for the day", "closed until later today" describe "that has regular times" do describe "without special times" do it_should_behave_like "a capable Place" end describe "with special times" do describe "overriding the regular times" do it_should_behave_like "a capable Place" end describe "not overriding the regular times" do it_should_behave_like "a capable Place" end end end describe "that has no regular times" do describe "and no special times" do it_should_behave_like "a capable Place" end describe "but has special times" do it_should_behave_like "a capable Place" end end end =end diff --git a/spec/models/schedules.rb b/spec/models/schedules.rb index 46c28cf..fb3ba34 100644 --- a/spec/models/schedules.rb +++ b/spec/models/schedules.rb @@ -1,285 +1,295 @@ ###################### ##### Scheduling ##### ###################### ConstraintDebugging = false def add_constraint(place, &block) place.constraints ||= [] place.constraints << block end # Test +time+ against all constraints for +place+ def acceptable_time(place, time) if ConstraintDebugging puts "Testing Time: #{time.inspect}" end matched_all = true place.constraints.each do |c| matched = c.call(time) if ConstraintDebugging if matched puts "++ Time accepted by constraint" else puts "-- Time rejected by constraint" end puts " Constraint: #{c.to_s.sub(/^[^\@]*\@/,'')[0..-2]}" end matched_all &= matched end if ConstraintDebugging if matched_all puts "++ Time Accepted" else puts "-- Time Rejected" end puts "" end matched_all end def add_times(place, times = []) times.each do |t| unless t[:start] and t[:length] raise ArgumentError, "Must specify a valid start offset and length" end if acceptable_time(place, t) t[:override] ||= false t[:startDate] ||= Date.yesterday t[:endDate] ||= Date.tomorrow t[:daysOfWeek] ||= OperatingTime::ALL_DAYS t[:place_id] ||= place.id ot = OperatingTime.new t.each{|k,v| ot.send(k.to_s+'=',v)} puts "Added time: #{ot.inspect}" if ConstraintDebugging if t[:override] place.special_operating_times << ot else place.regular_operating_times << ot end end end if ConstraintDebugging puts "Regular Times: #{place.regular_operating_times.inspect}" puts "Special Times: #{place.special_operating_times.inspect}" end place end def remove_times(place, times = []) end describe "a Place with scheduling capabilities", :shared => true do in_order_to "be open now" do before(:each) do add_times(@place,[ {:start => 6.hours, :length => 2.hours, :override => false}, {:start => 6.hours, :length => 2.hours, :override => true} ]) @at = Time.now.midnight + 7.hours end it "should have a schedule" do @place.operating_times.should_not be_empty @place.schedule(@at.midnight, @at.midnight + 1.day).should_not be_empty @place.daySchedule(@at).should_not be_empty @place.currentSchedule(@at).should_not be_nil end it "should be open today" do @place.open(@at).should == true end - it "should be open in the past" do + it "should be open \"now\" in the past" do + @at += 12.days + @place.operating_times.each do |t| + t.endDate += 12 + end + + @place.open(@at).should == true end - it "should be open in the future" do + it "should be open \"now\" in the future" do + @at -= 12.days + @place.operating_times.each do |t| + t.startDate -= 12 + end end end in_order_to "be open 24 hours" do end in_order_to "be open later in the day" do before(:each) do add_times(@place,[ {:start => 16.hours, :length => 2.hours, :override => false}, {:start => 16.hours, :length => 2.hours, :override => true} ]) @at = Time.now.midnight + 12.hours end it "should have a schedule between now and midnight" do @place.schedule(@at,@at.midnight + 24.hours).size.should > 0 end end in_order_to "be open earlier in the day" do end in_order_to "be open past midnight (tonight)" do before(:each) do @at = Time.now.midnight end end in_order_to "be open past midnight (last night)" do end in_order_to "be closed now" do before(:each) do #add_constraint(@place) {|t| ( t[:start] > (@at - @at.midnight) ) or #( (t[:start] + t[:length]) < (@at - @at.midnight) ) } add_times(@place,[ {:start => 6.hours, :length => 2.hours, :override => false}, {:start => 6.hours, :length => 2.hours, :override => true} ]) @at = Time.now.midnight + 9.hours end it "should be closed" do @place.open(@at).should == false end end in_order_to "be closed all day" do end in_order_to "be closed for the day" do end in_order_to "be closed until later in the day" do end in_order_to "have a valid schedule" do it "should not have any overlapping times" it "should have all times within the specified time range" end end describe "a Place with all scheduling capabilities", :shared => true do it_can "be open now" it_can "be open 24 hours" it_can "be open later in the day" it_can "be open earlier in the day" it_can "be open past midnight (tonight)" it_can "be open past midnight (last night)" it_can "be closed now" it_can "be closed all day" it_can "be closed for the day" it_can "be closed until later in the day" end describe "a Place with valid times", :shared => true do before(:each) do add_constraint(@place) { true } end describe "with only regular times" do before(:each) do add_constraint(@place) {|t| t[:override] == false } end validate_setup do it "should have regular times" do #puts "Regular Times: #{@place.regular_operating_times.inspect}" @place.regular_operating_times.should_not be_empty end it "should not have any special times" do #puts "Special Times: #{@place.special_operating_times.inspect}" @place.special_operating_times.should be_empty end end it_can "be open now" #it_can "be open 24 hours" #it_can "be open later in the day" #it_can "be open earlier in the day" #it_can "be open past midnight (tonight)" #it_can "be open past midnight (last night)" #it_can "be closed now" #it_can "be closed all day" #it_can "be closed for the day" #it_can "be closed until later in the day" end describe "with only special times" do before(:each) do add_constraint(@place) {|t| t[:override] == true } end validate_setup do it "should not have regular times" do @place.regular_operating_times.should be_empty end it "should have special times" do @place.special_operating_times.should_not be_empty end end it_can "be open now" #it_can "be open 24 hours" #it_can "be open later in the day" #it_can "be open earlier in the day" #it_can "be open past midnight (tonight)" #it_can "be open past midnight (last night)" #it_can "be closed now" #it_can "be closed all day" #it_can "be closed for the day" #it_can "be closed until later in the day" end describe "with regular and special times" do describe "where the special times are overriding the regular times" do #it_should_behave_like "a Place with all scheduling capabilities" end describe "where the special times are not overriding the regular times" do #it_should_behave_like "a Place with all scheduling capabilities" end end describe "with special times" do describe "extending normal hours" do #it_should_behave_like "a Place with all scheduling capabilities" end describe "reducing normal hours" do #it_should_behave_like "a Place with all scheduling capabilities" end describe "removing all hours" do #it_should_behave_like "a Place with all scheduling capabilities" end describe "moving normal hours (extending and reducing)" do #it_should_behave_like "a Place with all scheduling capabilities" end end end
michaelansel/dukenow
e3b0b5f24f705e6f1ecc1e6322e7b003061962ba
Move all scheduling specs into a separate file from Place model specs
diff --git a/spec/models/place_spec.rb b/spec/models/place_spec.rb index 7ac59f9..1377418 100644 --- a/spec/models/place_spec.rb +++ b/spec/models/place_spec.rb @@ -1,537 +1,256 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') - -ConstraintDebugging = defined? ConstraintDebugging ? ConstraintDebugging : false - -def add_constraint(place, &block) - place.constraints ||= [] - place.constraints << block -end - -# Test +time+ against all constraints for +place+ -def acceptable_time(place, time) - if ConstraintDebugging - puts "Testing Time: #{time.inspect}" - end - - matched_all = true - place.constraints.each do |c| - matched = c.call(time) - - if ConstraintDebugging - if matched - puts "++ Time accepted by constraint" - else - puts "-- Time rejected by constraint" - end - puts " Constraint: #{c.to_s.sub(/^[^\@]*\@/,'')[0..-2]}" - end - - matched_all &= matched - end - - if ConstraintDebugging - if matched_all - puts "++ Time Accepted" - else - puts "-- Time Rejected" - end - puts "" - end - - matched_all -end - -def add_times(place, times = []) - times.each do |t| - unless t[:start] and t[:length] - raise ArgumentError, "Must specify a valid start offset and length" - end - - if acceptable_time(place, t) - t[:override] ||= false - t[:startDate] ||= Date.yesterday - t[:endDate] ||= Date.tomorrow - t[:daysOfWeek] ||= OperatingTime::ALL_DAYS - t[:place_id] ||= place.id - ot = OperatingTime.new - t.each{|k,v| ot.send(k.to_s+'=',v)} - - puts "Added time: #{ot.inspect}" if ConstraintDebugging - - if t[:override] - place.special_operating_times << ot - else - place.regular_operating_times << ot - end - - end - end - - if ConstraintDebugging - puts "Regular Times: #{place.regular_operating_times.inspect}" - puts "Special Times: #{place.special_operating_times.inspect}" - end - - place -end - -def remove_times(place, times = []) -end - - -describe "a Place with scheduling capabilities", :shared => true do - - in_order_to "be open now" do - before(:each) do - add_times(@place,[ - {:start => 6.hours, :length => 2.hours, :override => false}, - {:start => 6.hours, :length => 2.hours, :override => true} - ]) - @at = Time.now.midnight + 7.hours - end - - it "should have a schedule" do - @place.operating_times.should_not be_empty - @place.schedule(@at.midnight, @at.midnight + 1.day).should_not be_empty - @place.daySchedule(@at).should_not be_empty - @place.currentSchedule(@at).should_not be_nil - end - - it "should be open today" do - @place.open(@at).should == true - end - - it "should be open in the past" do - end - - it "should be open in the future" do - end - end - - in_order_to "be open 24 hours" do - end - - in_order_to "be open later in the day" do - before(:each) do - add_times(@place,[ - {:start => 16.hours, :length => 2.hours, :override => false}, - {:start => 16.hours, :length => 2.hours, :override => true} - ]) - @at = Time.now.midnight + 12.hours - end - - it "should have a schedule between now and midnight" do - @place.schedule(@at,@at.midnight + 24.hours).size.should > 0 - end - end - - in_order_to "be open earlier in the day" do - end - - in_order_to "be open past midnight (tonight)" do - before(:each) do - @at = Time.now.midnight - end - end - - in_order_to "be open past midnight (last night)" do - end - - - in_order_to "be closed now" do - before(:each) do - #add_constraint(@place) {|t| ( t[:start] > (@at - @at.midnight) ) or - #( (t[:start] + t[:length]) < (@at - @at.midnight) ) } - add_times(@place,[ - {:start => 6.hours, :length => 2.hours, :override => false}, - {:start => 6.hours, :length => 2.hours, :override => true} - ]) - @at = Time.now.midnight + 9.hours - end - - it "should be closed" do - @place.open(@at).should == false - end - end - - in_order_to "be closed all day" do - end - - in_order_to "be closed for the day" do - end - - in_order_to "be closed until later in the day" do - end - - in_order_to "have a valid schedule" do - it "should not have any overlapping times" - it "should have all times within the specified time range" - end -end - -describe "a Place with all scheduling capabilities", :shared => true do - it_can "be open now" - it_can "be open 24 hours" - it_can "be open later in the day" - it_can "be open earlier in the day" - it_can "be open past midnight (tonight)" - it_can "be open past midnight (last night)" - - it_can "be closed now" - it_can "be closed all day" - it_can "be closed for the day" - it_can "be closed until later in the day" -end - -describe "a Place with valid times", :shared => true do - before(:each) do - add_constraint(@place) { true } - end - - describe "with only regular times" do - before(:each) do - add_constraint(@place) {|t| t[:override] == false } - end - - validate_setup do - it "should have regular times" do - #puts "Regular Times: #{@place.regular_operating_times.inspect}" - @place.regular_operating_times.should_not be_empty - end - - it "should not have any special times" do - #puts "Special Times: #{@place.special_operating_times.inspect}" - @place.special_operating_times.should be_empty - end - end - - it_can "be open now" - #it_can "be open 24 hours" - #it_can "be open later in the day" - #it_can "be open earlier in the day" - #it_can "be open past midnight (tonight)" - #it_can "be open past midnight (last night)" - - #it_can "be closed now" - #it_can "be closed all day" - #it_can "be closed for the day" - #it_can "be closed until later in the day" - - end - - describe "with only special times" do - before(:each) do - add_constraint(@place) {|t| t[:override] == true } - end - - - validate_setup do - it "should not have regular times" do - @place.regular_operating_times.should be_empty - end - - it "should have special times" do - @place.special_operating_times.should_not be_empty - end - end - - it_can "be open now" - #it_can "be open 24 hours" - #it_can "be open later in the day" - #it_can "be open earlier in the day" - #it_can "be open past midnight (tonight)" - #it_can "be open past midnight (last night)" - - #it_can "be closed now" - #it_can "be closed all day" - #it_can "be closed for the day" - #it_can "be closed until later in the day" - - end - - describe "with regular and special times" do - describe "where the special times are overriding the regular times" do - #it_should_behave_like "a Place with all scheduling capabilities" - end - - describe "where the special times are not overriding the regular times" do - #it_should_behave_like "a Place with all scheduling capabilities" - end - end - - - describe "with special times" do - describe "extending normal hours" do - #it_should_behave_like "a Place with all scheduling capabilities" - end - - describe "reducing normal hours" do - #it_should_behave_like "a Place with all scheduling capabilities" - end - - describe "removing all hours" do - #it_should_behave_like "a Place with all scheduling capabilities" - end - - describe "moving normal hours (extending and reducing)" do - #it_should_behave_like "a Place with all scheduling capabilities" - end - end -end - - - +require File.expand_path(File.dirname(__FILE__) + '/schedules') describe Place do before(:each) do @valid_attributes = { :name => 'Test Place', :location => 'Somewhere', :phone => '(919) 555-1212' } @place = Place.create!(@valid_attributes) @place.class_eval <<EOM attr_accessor :constraints def operating_times regular_operating_times + special_operating_times end def regular_operating_times @regular_operating_times ||= [] end def special_operating_times @special_operating_times ||= [] end EOM @place.regular_operating_times.should == [] @place.special_operating_times.should == [] end it_should_behave_like "a Place with scheduling capabilities" it_should_behave_like "a Place with valid times" it "should create a new instance given valid attributes" do Place.create!(@valid_attributes) end it "should not create a new instance without a name" do @valid_attributes.delete(:name) lambda { Place.create!(@valid_attributes) }.should raise_error end describe "a Place with no times" do before(:each) do add_constraint(@place){ false } @at = Time.now.midnight + 7.hours @open_at = @at.midnight + 7.hours @closed_at = @at.midnight + 2.hours end it_can "be closed now", "be closed all day", "be closed for the day" end end =begin # TODO Create mocks for OperatingTime so we can test the scheduling methods describe "a Place with OperatingTimes", :shared => true do describe "that are valid now" do it "should have a valid schedule" do end it "should have a valid daily schedule" it "should have a valid current schedule" it "should have regular OperatingTimes" it "should have special OperatingTimes" end describe "that are not valid now" do end end describe Place do before(:each) do @valid_attributes = { :name => 'Test Place', :location => 'Somewhere', :phone => '(919) 555-1212' } end it "should create a new instance given valid attributes" do Place.create!(@valid_attributes) end it "should not create a new instance without a name" do @valid_attributes.delete(:name) lambda { Place.create!(@valid_attributes) }.should raise_error end it "should build a valid dailySchedule" do #TODO Test against a valid schedule as well place = Place.create!(@valid_attributes) place.should_receive(:schedule).with(instance_of(Time), instance_of(Time)).and_return([]) place.daySchedule(Date.today).should == [] end describe "with only special OperatingTimes" do end describe "with only regular OperatingTimes" do end describe "with special OperatingTimes overriding regular OperatingTimes" do end describe "that is currently open" do it_should_behave_like "a Place with OperatingTimes" before(:each) do @at = Time.now.midnight + 7.hours @currentSchedule = stub_times([{:start => 6.hours, :length => 2.hours}]) @daySchedule = [@currentSchedule] @place = Place.create!(@valid_attributes) @place.stub(:operating_times).and_return(@currentSchedule) @place.stub(:regular_operating_times).and_return(@currentSchedule) @place.stub(:special_operating_times).and_return(@currentSchedule) end it "should produce a valid daySchedule" do end it "should produce a valid currentSchedule" do end it "should be open" do @place.should_receive(:currentSchedule). with(duck_type(:midnight)). and_return(@currentSchedule) @place.open?(@at).should == true end end describe "that is closed, but opens later today" do it_should_behave_like "a Place with OperatingTimes" it "should be closed" it "should have a schedule for later today" end describe "that is closed for the day" do it_should_behave_like "a Place with OperatingTimes" it "should be closed" end describe "that is not open at all today" do it_should_behave_like "a Place with OperatingTimes" it "should be closed" it "should not have a schedule for the remainder of today" end describe "that is open past midnight today" do it_should_behave_like "a Place with OperatingTimes" end describe "that was open past midnight yesterday" do it_should_behave_like "a Place with OperatingTimes" end ###### Special Schedules ###### describe "that is normally open, but closed all day today" do it_should_behave_like "a Place with OperatingTimes" end describe "that has special (extended) hours" do it_should_behave_like "a Place with OperatingTimes" end describe "that has special (shortened) hours" do it_should_behave_like "a Place with OperatingTimes" end end describe "a capable Place", :shared => true do it_can_be "closed all day", "closed for the day", "closed until later today" #it_can_be "open past midnight tonight", "open past midnight last night" #it_can_be "open now", "closed now" end describe "a happy Place" do in_order_to_be "closed all day" do it "should be closed right now" do pending("There ain't no @place to test!") { @place.open?(@at) } @place.open?(@at).should == false end it "should have an empty schedule for the day" it "should not have a current schedule" end in_order_to_be "closed for the day" do before(:each) do end it "should be closed right now" it "should not have a current schedule" it_can "have no schedule elements later in the day" it_can "have schedule elements earlier in the day", "have no schedule elements earlier in the day" end in_order_to_be "closed until later today" do before(:each) do end end in_order_to "have schedule elements earlier in the day" do end in_order_to "have no schedule elements earlier in the day" do end in_order_to "have schedule elements later in the day" do end in_order_to "have no schedule elements later in the day" do end it_can_be "closed all day", "closed for the day", "closed until later today" describe "that has regular times" do describe "without special times" do it_should_behave_like "a capable Place" end describe "with special times" do describe "overriding the regular times" do it_should_behave_like "a capable Place" end describe "not overriding the regular times" do it_should_behave_like "a capable Place" end end end describe "that has no regular times" do describe "and no special times" do it_should_behave_like "a capable Place" end describe "but has special times" do it_should_behave_like "a capable Place" end end end =end diff --git a/spec/models/schedules.rb b/spec/models/schedules.rb new file mode 100644 index 0000000..46c28cf --- /dev/null +++ b/spec/models/schedules.rb @@ -0,0 +1,285 @@ +###################### +##### Scheduling ##### +###################### + +ConstraintDebugging = false + +def add_constraint(place, &block) + place.constraints ||= [] + place.constraints << block +end + +# Test +time+ against all constraints for +place+ +def acceptable_time(place, time) + if ConstraintDebugging + puts "Testing Time: #{time.inspect}" + end + + matched_all = true + place.constraints.each do |c| + matched = c.call(time) + + if ConstraintDebugging + if matched + puts "++ Time accepted by constraint" + else + puts "-- Time rejected by constraint" + end + puts " Constraint: #{c.to_s.sub(/^[^\@]*\@/,'')[0..-2]}" + end + + matched_all &= matched + end + + if ConstraintDebugging + if matched_all + puts "++ Time Accepted" + else + puts "-- Time Rejected" + end + puts "" + end + + matched_all +end + +def add_times(place, times = []) + times.each do |t| + unless t[:start] and t[:length] + raise ArgumentError, "Must specify a valid start offset and length" + end + + if acceptable_time(place, t) + t[:override] ||= false + t[:startDate] ||= Date.yesterday + t[:endDate] ||= Date.tomorrow + t[:daysOfWeek] ||= OperatingTime::ALL_DAYS + t[:place_id] ||= place.id + ot = OperatingTime.new + t.each{|k,v| ot.send(k.to_s+'=',v)} + + puts "Added time: #{ot.inspect}" if ConstraintDebugging + + if t[:override] + place.special_operating_times << ot + else + place.regular_operating_times << ot + end + + end + end + + if ConstraintDebugging + puts "Regular Times: #{place.regular_operating_times.inspect}" + puts "Special Times: #{place.special_operating_times.inspect}" + end + + place +end + +def remove_times(place, times = []) +end + + +describe "a Place with scheduling capabilities", :shared => true do + + in_order_to "be open now" do + before(:each) do + add_times(@place,[ + {:start => 6.hours, :length => 2.hours, :override => false}, + {:start => 6.hours, :length => 2.hours, :override => true} + ]) + @at = Time.now.midnight + 7.hours + end + + it "should have a schedule" do + @place.operating_times.should_not be_empty + @place.schedule(@at.midnight, @at.midnight + 1.day).should_not be_empty + @place.daySchedule(@at).should_not be_empty + @place.currentSchedule(@at).should_not be_nil + end + + it "should be open today" do + @place.open(@at).should == true + end + + it "should be open in the past" do + end + + it "should be open in the future" do + end + end + + in_order_to "be open 24 hours" do + end + + in_order_to "be open later in the day" do + before(:each) do + add_times(@place,[ + {:start => 16.hours, :length => 2.hours, :override => false}, + {:start => 16.hours, :length => 2.hours, :override => true} + ]) + @at = Time.now.midnight + 12.hours + end + + it "should have a schedule between now and midnight" do + @place.schedule(@at,@at.midnight + 24.hours).size.should > 0 + end + end + + in_order_to "be open earlier in the day" do + end + + in_order_to "be open past midnight (tonight)" do + before(:each) do + @at = Time.now.midnight + end + end + + in_order_to "be open past midnight (last night)" do + end + + + in_order_to "be closed now" do + before(:each) do + #add_constraint(@place) {|t| ( t[:start] > (@at - @at.midnight) ) or + #( (t[:start] + t[:length]) < (@at - @at.midnight) ) } + add_times(@place,[ + {:start => 6.hours, :length => 2.hours, :override => false}, + {:start => 6.hours, :length => 2.hours, :override => true} + ]) + @at = Time.now.midnight + 9.hours + end + + it "should be closed" do + @place.open(@at).should == false + end + end + + in_order_to "be closed all day" do + end + + in_order_to "be closed for the day" do + end + + in_order_to "be closed until later in the day" do + end + + in_order_to "have a valid schedule" do + it "should not have any overlapping times" + it "should have all times within the specified time range" + end +end + +describe "a Place with all scheduling capabilities", :shared => true do + it_can "be open now" + it_can "be open 24 hours" + it_can "be open later in the day" + it_can "be open earlier in the day" + it_can "be open past midnight (tonight)" + it_can "be open past midnight (last night)" + + it_can "be closed now" + it_can "be closed all day" + it_can "be closed for the day" + it_can "be closed until later in the day" +end + +describe "a Place with valid times", :shared => true do + before(:each) do + add_constraint(@place) { true } + end + + describe "with only regular times" do + before(:each) do + add_constraint(@place) {|t| t[:override] == false } + end + + validate_setup do + it "should have regular times" do + #puts "Regular Times: #{@place.regular_operating_times.inspect}" + @place.regular_operating_times.should_not be_empty + end + + it "should not have any special times" do + #puts "Special Times: #{@place.special_operating_times.inspect}" + @place.special_operating_times.should be_empty + end + end + + it_can "be open now" + #it_can "be open 24 hours" + #it_can "be open later in the day" + #it_can "be open earlier in the day" + #it_can "be open past midnight (tonight)" + #it_can "be open past midnight (last night)" + + #it_can "be closed now" + #it_can "be closed all day" + #it_can "be closed for the day" + #it_can "be closed until later in the day" + + end + + describe "with only special times" do + before(:each) do + add_constraint(@place) {|t| t[:override] == true } + end + + + validate_setup do + it "should not have regular times" do + @place.regular_operating_times.should be_empty + end + + it "should have special times" do + @place.special_operating_times.should_not be_empty + end + end + + it_can "be open now" + #it_can "be open 24 hours" + #it_can "be open later in the day" + #it_can "be open earlier in the day" + #it_can "be open past midnight (tonight)" + #it_can "be open past midnight (last night)" + + #it_can "be closed now" + #it_can "be closed all day" + #it_can "be closed for the day" + #it_can "be closed until later in the day" + + end + + describe "with regular and special times" do + describe "where the special times are overriding the regular times" do + #it_should_behave_like "a Place with all scheduling capabilities" + end + + describe "where the special times are not overriding the regular times" do + #it_should_behave_like "a Place with all scheduling capabilities" + end + end + + + describe "with special times" do + describe "extending normal hours" do + #it_should_behave_like "a Place with all scheduling capabilities" + end + + describe "reducing normal hours" do + #it_should_behave_like "a Place with all scheduling capabilities" + end + + describe "removing all hours" do + #it_should_behave_like "a Place with all scheduling capabilities" + end + + describe "moving normal hours (extending and reducing)" do + #it_should_behave_like "a Place with all scheduling capabilities" + end + end +end + + +
michaelansel/dukenow
fe240ca97c86a70a3033a3abc2e3e079af40f267
Extensive changes to scheduling logic and specs
diff --git a/TODO b/TODO index 9503715..6a9a698 100644 --- a/TODO +++ b/TODO @@ -1,112 +1,115 @@ vim:set syntax=todo: Database Places -- has_one :dining_extension \- name (string) -- location (lat/long) -- ?GeoKit Plugin? \- phone_number (string) DiningExtensions -- acts_as_taggable_on :dining_tags ## needs work -- **delivery/eat-in** ## operating_time details/tag -- more_info_url -- owner_operator -- payment_methods -- logo_url OperatingTimes \- place_id \- start (midnight offset in seconds) \- length (in seconds) \- startDate (Date) \- endDate (Date) \- details (String) - -- override - -- days_of_week (bit-wise AND of wday's) + \- override + \- days_of_week (bit-wise AND of wday's) OperatingTimesTags -- name OperatingTimesTaggings (clone auto-generated) !- clone Taggings schema -- operating_time_id -- operating_times_tag_id TimePeriods -- name (String) -- startDate (Date) -- endDate (Date) API Versioning -- Subdirectories -- rake task for adding new versions and deprecating old versions Places OperatingTimes -- Array of DateTime objects for the next N hours/days/etc -- Bulk import Excel spreadsheet -- What qualifies as a Tag versus an Attribute? -Milestones +Timeline OperatingTimes StartLengthSchema \- Migration Feature-parity -- schedule(from,to) -- daySchedule(date) -- currentSchedule(at) -- open?(at) - -- Full unit tests + validation - -- Prevent overlapping time periods without "override" flag + Testing + Unit Tests + -- Database accessors + Model Validations + -- Prevent overlapping time periods without "override" flag Extend API - -- Generate Time objects + \- Generate Time objects (Enumerable?) -- Add versioning DiningExtensions -- Migration -- Full unit tests + validation DiningExtensions Tags -- Migrations -- Full unit tests + validation OperatingTimes Tags -- Migration -- Full unit tests + validation -- Extend OperatingTimes.find to filter by tags -- Extend Places.open? to test delivery/dine-in tags TimePeriods -- Migration -- Full unit tests + validation -- Create integration -- View Integration API Versioning rake Tasks -- Clone for new version and increment version number -- Deprecate old version -- Hosting for web app/file server? -- Can I get help with the UI design, or will DukeMobile only be focusing on the iPhone side? -- Set "expiration" date; Send reminder emails; Show _nothing_ rather than inaccurate info Database Adjust schema to be more flexible !- Late nights: seamless midnight rollover -- Start,End => Start,Length (then, convert to real "Time"s based on @at) -- iCal RRULE (string) and parse with RiCal (pre-release) \- Add "midnight" method to Date, Time -- (?) Multiple "special"/override schedules (e.g. every weekday during Spring Break except Friday) -- Special: "normally open, but closed all day today" -- Semester-style schedules -- List of important dates (likely to be scheduling boundaries) Interface Index (Main Page) -- Hide nowIndicator after midnight instead of wrapping around -- JavaScript Tag Filtering -- Status @ DateTime Data Entry -- Bulk import (CSV, XML) -- Duke Dining PDF parser (?) -- Not worth the effort to get consistent data Web Form -- Text entry of times (drop downs, input fields) -- Quickly add/edit all times for a location -- Graphic schedule of current settings -- Show "normal" schedule in background if making an exception -- Drag/Drop/Resize-able blocks on schedule diff --git a/app/models/operating_time.rb b/app/models/operating_time.rb index 0d41aa0..35da623 100644 --- a/app/models/operating_time.rb +++ b/app/models/operating_time.rb @@ -1,184 +1,229 @@ class OperatingTime < ActiveRecord::Base belongs_to :place validates_presence_of :place_id validates_associated :place validate :end_after_start, :daysOfWeek_valid ## DaysOfWeek Constants ## SUNDAY = 0b00000001 MONDAY = 0b00000010 TUESDAY = 0b00000100 WEDNESDAY = 0b00001000 THURSDAY = 0b00010000 FRIDAY = 0b00100000 SATURDAY = 0b01000000 ALL_DAYS = (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) ## Validations ## def end_after_start if endDate < startDate errors.add_to_base("End date cannot preceed start date") end end def daysOfWeek_valid daysOfWeek == daysOfWeek & (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) end ## End Validations ## # TODO Is this OperatingTime applicable at +time+ def valid_at(time=Time.now) raise NotImplementedError end def override read_attribute(:override) == 1 end def override=(mode) if mode == true or mode == "true" or mode == 1 write_attribute(:override, true) elsif mode == false or mode == "false" or mode == 0 write_attribute(:override, false) else raise ArgumentError, "Invalid override value (#{mode.inspect}); Accepts true/false, 1/0" end end def daysOfWeek=(newDow) - if newDow & ALL_DAYS == newDow - write_attribute(:daysOfWeek, newDow & ALL_DAYS) - else + if not ( newDow & ALL_DAYS == newDow ) # Invalid input raise ArgumentError, "Not a valid value for daysOfWeek (#{newDow.inspect})" end + + write_attribute(:daysOfWeek, newDow & ALL_DAYS) + @daysOfWeekHash = nil + @daysOfWeekArray = nil + @daysOfWeekString = nil end ## daysOfWeek Helper/Accessors ## # Hash mapping day of week (Symbol) to valid(true)/invalid(false) def daysOfWeekHash - { :sunday => (daysOfWeek & SUNDAY ) > 0, + @daysOfWeekHash ||= { + :sunday => (daysOfWeek & SUNDAY ) > 0, :monday => (daysOfWeek & MONDAY ) > 0, :tuesday => (daysOfWeek & TUESDAY ) > 0, :wednesday => (daysOfWeek & WEDNESDAY ) > 0, :thursday => (daysOfWeek & THURSDAY ) > 0, :friday => (daysOfWeek & FRIDAY ) > 0, - :saturday => (daysOfWeek & SATURDAY ) > 0} + :saturday => (daysOfWeek & SATURDAY ) > 0 + } end # Array beginning with Sunday of valid(true)/inactive(false) values def daysOfWeekArray dow = daysOfWeekHash - [ dow[:sunday], + @daysOfWeekArray ||= [ + dow[:sunday], dow[:monday], dow[:tuesday], dow[:wednesday], dow[:thursday], dow[:friday], dow[:saturday] ] end # Human-readable string of applicable days of week def daysOfWeekString dow = daysOfWeekHash - str = "" - str += "Su" if dow[:sunday] - str += "M" if dow[:monday] - str += "Tu" if dow[:tuesday] - str += "W" if dow[:wednesday] - str += "Th" if dow[:thursday] - str += "F" if dow[:friday] - str += "Sa" if dow[:saturday] - - str + @daysOfWeekString ||= (dow[:sunday] ? "Su" : "") + + (dow[:monday] ? "M" : "") + + (dow[:tuesday] ? "Tu" : "") + + (dow[:wednesday] ? "W" : "") + + (dow[:thursday] ? "Th" : "") + + (dow[:friday] ? "F" : "") + + (dow[:saturday] ? "Sa" : "") end ## End daysOfWeek Helper/Accessors ## # Return array of times representing the open and close times at a certain occurence def to_times(at = Time.now) + # TODO Verify this is a valid occurrence open = at.midnight + start close = open + length [open,close] end def to_xml(params) super(params.merge({:only => [:id, :place_id, :flags], :methods => [ :opensAt, :closesAt, :startDate, :endDate ]})) end + # Returns the next full occurrence of these operating time rule. + # If we are currently within a valid time range, it will look forward for the + # <em>next</em> opening time + def next_times(at = Time.now) + return nil if at > endDate # This schedule has ended + at = startDate.midnight if at < startDate # This schedule hasn't started yet, skip to startDate + + # Next occurrence is later today + # This is the only time the "time" actually matters; + # after today, all we care about is the date + if daysOfWeekArray[at.wday] and + start >= (at - at.midnight) + return to_times(at) + end + + # We don't care about the time offset anymore, jump to the next midnight + at = at.midnight + 1.day + + # TODO Test for Sun, Sat, and one of M-F + dow = daysOfWeekArray[at.wday..-1] + daysOfWeekArray[0..at.wday] + + # Next day of the week this schedule is valid for + shift = dow.index(true) + if shift + # Skip forward + at = at + shift.days + else + # Give up, there are no more occurrences + # TODO Test edge case: valid for 1 day/week + return nil + end + + # Recurse to rerun the validation routines + return next_times(at) + end + + ##### TODO DEPRECATED METHODS ##### def at @at end def at=(time) @opensAt = nil @closesAt = nil @at = time end # Returns a Time object representing the beginning of this OperatingTime def opensAt @opensAt ||= relativeTime.openTime(at) end def closesAt @closesAt ||= relativeTime.closeTime(at) end # Sets the beginning of this OperatingTime # Input: params = { :hour => 12, :minute => 45 } def opensAt=(time) if time.class == Time @opensAt = relativeTime.openTime = time else super end end # Sets the end of this OperatingTime def closesAt=(time) @closesAt = relativeTime.closeTime = time end def start read_attribute(:opensAt) end + def start=(offset) + write_attribute(:opensAt,offset) + end + # Returns a RelativeTime object representing this OperatingTime def relativeTime @relativeTime ||= RelativeTime.new(self, :opensAt, :length) end; protected :relativeTime # Backwards compatibility with old database schema # TODO GET RID OF THIS!!! def flags ( (override ? 1 : 0) << 7) | read_attribute(:daysOfWeek) end # FIXME Deprecated, use +override+ instead def special override end # Input: isSpecial = true/false # FIXME Deprecated, use +override=+ instead def special=(isSpecial) if isSpecial == true or isSpecial == "true" or isSpecial == 1 self.override = true elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 self.override = false end end end diff --git a/app/models/place.rb b/app/models/place.rb index 63062ad..e225209 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,110 +1,129 @@ class Place < ActiveRecord::Base + DEBUG = defined? DEBUG ? DEBUG : false + has_many :operating_times acts_as_taggable_on :tags validates_presence_of :name def special_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 1}, :order => "startDate ASC, opensAt ASC" ) end def regular_operating_times OperatingTime.find( :all, :conditions => {:place_id => id, :override => 0}, :order => "startDate ASC, opensAt ASC" ) end # Returns an array of OperatingTimes def schedule(startAt,endAt) # TODO Returns the schedule for a specified time window # TODO Handle events starting within the range but ending outside of it? - regular_times = [] - regular_operating_times.each do |ot| - if ot.startDate >= startAt.to_date-1 and ot.endDate <= endAt.to_date+1 - - # Yesterday - open,close = ot.to_times((startAt.to_date - 1).midnight) - if false and close >= ot.at and ot.flags & 1<<ot.at.wday > 0 - t = ot.dup - t.opensAt = startAt - regular_times << t - t=nil - end - # Today - open,close = ot.to_times(startAt.to_date.midnight) - ## TODO Add all occurances to the array, not just the first one - regular_times << ot if open >= startAt and close < endAt and ot.flags & 1<<startAt.to_date.midnight.wday > 0 - - # Tomorrow - open,close = ot.to_times(endAt == endAt.midnight ? endAt : endAt.midnight + 1.days) - if false and open < endAt and ot.flags & 1<<ot.at.wday > 0 - t = ot.dup - t.closesAt = endAt - regular_times << t - t=nil + # TODO Offload this selection to the database; okay for testing + regular_operating_times = regular_operating_times().select{|t| t.startDate <= endAt.to_date and t.endDate >= startAt.to_date} + special_operating_times = special_operating_times().select{|t| t.startDate <= endAt.to_date and t.endDate >= startAt.to_date} + + regular_times = [] + special_times = [] + special_ranges = [] + + special_operating_times.each do |ot| + puts "\nSpecial Scheduling: #{ot.inspect}" if DEBUG + + open,close = ot.next_times(startAt-1.day) + next if open.nil? # No valid occurrences in the future + + while not open.nil? and open <= endAt do + if DEBUG + puts "Open: #{open}" + puts "Close: #{close}" + puts "Start Date: #{ot.startDate} (#{ot.startDate.class})" + puts "End Date: #{ot.endDate} (#{ot.endDate.class})" end + special_times << [open,close] + special_ranges << Range.new(ot.startDate,ot.endDate) + open,close = ot.next_times(close) end + end - special_times = special_operating_times.select do |ot| - ot.at = startAt - ot.startDate ||= startAt.to_date - ot.endDate ||= endAt.to_date - (ot.startDate <= startAt.to_date and ot.endDate >= endAt.to_date) and - ((ot.opensAt >= startAt and ot.opensAt <= endAt) or (ot.closesAt >= startAt and ot.closesAt <= endAt)) + puts "\nSpecial Times: #{special_times.inspect}" if DEBUG + puts "\nSpecial Ranges: #{special_ranges.inspect}" if DEBUG + + regular_operating_times.each do |ot| + puts "\nRegular Scheduling: #{ot.inspect}" if DEBUG + + open,close = ot.next_times(startAt-1.day) + next if open.nil? # No valid occurrences in the future + + while not open.nil? and open <= endAt do + puts "Open: #{open}" if DEBUG + puts "Close: #{close}" if DEBUG + + special_ranges.each do |sr| + next if sr.member?(open) + end + + regular_times << [open,close] + open,close = ot.next_times(close) + end + end + puts "\nRegular Times: #{regular_times.inspect}" if DEBUG + + # TODO Handle schedule overrides # TODO Handle combinations (i.e. part special, part regular) - special_times == [] ? regular_times : special_times - regular_times # Ignore, just return regular times + + (regular_times+special_times).sort{|a,b|a[0] <=> b[0]} end def daySchedule(at = Date.today) at = at.to_date if at.class == Time or at.class == DateTime schedule = schedule(at.midnight,(at+1).midnight) #schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } #schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end =end - schedule.sort{|a,b|a.start <=> b.start} + schedule.sort{|a,b|a[0] <=> b[0]} end def currentSchedule(at = Time.now) - current_schedule = nil - - daySchedule(at).select { |optime| - open, close = optime.to_times(at) + daySchedule(at).select { |open,close| + puts "Open(cS): #{open}" if DEBUG + puts "Close(cS): #{close}" if DEBUG open <= at and at <= close }[0] end def open?(at = Time.now) a = currentSchedule(at) return a ? true : false end # Alias for <tt>open?</tt> def open(at = Time.now); open? at ; end def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end def to_xml(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end end diff --git a/spec/capabilities.rb b/spec/capabilities.rb index 7bb0784..145fb19 100644 --- a/spec/capabilities.rb +++ b/spec/capabilities.rb @@ -1,52 +1,77 @@ require 'rubygems' require 'spec' module Spec module Example + class ExampleGroupHierarchy + def validation_blocks + @validation_blocks ||= collect {|klass| klass.validation_blocks}.flatten + end + end + module ExampleGroupMethods def it_can(*capabilities) capabilities.each do |c| include_capability(c) end end def it_can_be(*capabilities) capabilities.each do |c| it_can("be #{c}") end end def in_order_to(*args, &block) raise Spec::Example::NoDescriptionError.new("example group", caller(0)[1]) if args.empty? options = add_options(args) set_location(options, caller(0)[1]) Spec::Example::CapabilityFactory.create_capability(*args, &block) end def in_order_to_be(*args, &block) in_order_to("be", *args, &block) end def include_capability(capability) case capability when Capability include capability else unless example_group = Capability.find(capability) raise RuntimeError.new("Capability '#{capability}' can not be found") end include(example_group) end + + ExampleGroupHierarchy.new(self).validation_blocks.each do |validation_block| + describe("set up properly", &validation_block) + end + end + + def validation_blocks + @validation_blocks ||= [] + end + + def validate_setup(&block) + validation_blocks << block end end class Capability < SharedExampleGroup end class CapabilityFactory < ExampleGroupFactory def self.create_capability(*args, &capability_block) # :nodoc: - ::Spec::Example::Capability.register(*args, &capability_block) +=begin + ::Spec::Example::Capability.register(*args) do + describe("that can",*args) do + ::Spec::Example::Capability.register(*args,&capability_block) + end + end +=end + ::Spec::Example::Capability.register(*args,&capability_block) end end end end diff --git a/spec/models/place_spec.rb b/spec/models/place_spec.rb index f136f82..7ac59f9 100644 --- a/spec/models/place_spec.rb +++ b/spec/models/place_spec.rb @@ -1,451 +1,537 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') +ConstraintDebugging = defined? ConstraintDebugging ? ConstraintDebugging : false + def add_constraint(place, &block) place.constraints ||= [] place.constraints << block end -def add_times(place, times = []) - times.each do |t| - place.constraints.each do |c| - if c.call(t) # If it matches the constraint - - ot = mock_model(OperatingTime) - ot.stub(:start).and_return(t[:start]) - ot.stub(:length).and_return(t[:length]) - ot.stub(:override).and_return(t[:override] || 0) - ot.stub(:startDate).and_return(t[:startDate] || Date.yesterday) - ot.stub(:endDate).and_return(t[:endDate] || Date.tomorrow) - ot.stub(:flags).and_return(t[:flags] || OperatingTime::ALL_DAYS) - ot.stub(:place_id).and_return(place.id) - ot.should_receive(:to_times).any_number_of_times do |at| - at.should respond_to(:midnight) - - open = at.midnight + ot.start - close = open + ot.length - [open,close] - end - - if t[:override] - place.special_operating_times << ot - else - place.regular_operating_times << ot - end +# Test +time+ against all constraints for +place+ +def acceptable_time(place, time) + if ConstraintDebugging + puts "Testing Time: #{time.inspect}" + end + + matched_all = true + place.constraints.each do |c| + matched = c.call(time) + if ConstraintDebugging + if matched + puts "++ Time accepted by constraint" + else + puts "-- Time rejected by constraint" end + puts " Constraint: #{c.to_s.sub(/^[^\@]*\@/,'')[0..-2]}" end + + matched_all &= matched end -end -def remove_times(place, times = []) + if ConstraintDebugging + if matched_all + puts "++ Time Accepted" + else + puts "-- Time Rejected" + end + puts "" + end + + matched_all end -def build_place_from_times(times = []) - place = Place.create!(@valid_attributes) +def add_times(place, times = []) + times.each do |t| + unless t[:start] and t[:length] + raise ArgumentError, "Must specify a valid start offset and length" + end - regularTimes,specialTimes = stub_times(times, place.id) + if acceptable_time(place, t) + t[:override] ||= false + t[:startDate] ||= Date.yesterday + t[:endDate] ||= Date.tomorrow + t[:daysOfWeek] ||= OperatingTime::ALL_DAYS + t[:place_id] ||= place.id + ot = OperatingTime.new + t.each{|k,v| ot.send(k.to_s+'=',v)} + + puts "Added time: #{ot.inspect}" if ConstraintDebugging + + if t[:override] + place.special_operating_times << ot + else + place.regular_operating_times << ot + end - place.stub(:operating_times).and_return(regularTimes + specialTimes) - place.stub(:regular_operating_times).and_return(regularTimes) - place.stub(:special_operating_times).and_return(specialTimes) + end + end + + if ConstraintDebugging + puts "Regular Times: #{place.regular_operating_times.inspect}" + puts "Special Times: #{place.special_operating_times.inspect}" + end place end -def stub_times(times = [], place_id = 0) - regularTimes = [] - specialTimes = [] +def remove_times(place, times = []) +end + - times.each do |time| - ot = mock_model(OperatingTime) - ot.stub(:start).and_return(time[:start]) - ot.stub(:length).and_return(time[:length]) - ot.stub(:override).and_return(time[:override] || 0) - ot.stub(:startDate).and_return(time[:startDate] || Date.yesterday) - ot.stub(:endDate).and_return(time[:endDate] || Date.tomorrow) - ot.stub(:flags).and_return(time[:flags] || OperatingTime::ALL_DAYS) - ot.stub(:place_id).and_return(place_id) - ot.should_receive(:to_times).any_number_of_times do |at| - at.should respond_to(:midnight) +describe "a Place with scheduling capabilities", :shared => true do - open = at.midnight + ot.start - close = open + ot.length - [open,close] + in_order_to "be open now" do + before(:each) do + add_times(@place,[ + {:start => 6.hours, :length => 2.hours, :override => false}, + {:start => 6.hours, :length => 2.hours, :override => true} + ]) + @at = Time.now.midnight + 7.hours end - if time.keys.include?(:override) and time[:override] == 1 - specialTimes << ot - elsif time[:override].nil? or time[:override] == 0 - regularTimes << ot + it "should have a schedule" do + @place.operating_times.should_not be_empty + @place.schedule(@at.midnight, @at.midnight + 1.day).should_not be_empty + @place.daySchedule(@at).should_not be_empty + @place.currentSchedule(@at).should_not be_nil end - end - [regularTimes,specialTimes] -end + it "should be open today" do + @place.open(@at).should == true + end -describe "a Place with scheduling capabilities", :shared => true do + it "should be open in the past" do + end - in_order_to "be open now" do - it "should be open" do - @place.open(@open_at).should == true + it "should be open in the future" do end end in_order_to "be open 24 hours" do end in_order_to "be open later in the day" do + before(:each) do + add_times(@place,[ + {:start => 16.hours, :length => 2.hours, :override => false}, + {:start => 16.hours, :length => 2.hours, :override => true} + ]) + @at = Time.now.midnight + 12.hours + end + it "should have a schedule between now and midnight" do @place.schedule(@at,@at.midnight + 24.hours).size.should > 0 end end in_order_to "be open earlier in the day" do end in_order_to "be open past midnight (tonight)" do + before(:each) do + @at = Time.now.midnight + end end in_order_to "be open past midnight (last night)" do end in_order_to "be closed now" do + before(:each) do + #add_constraint(@place) {|t| ( t[:start] > (@at - @at.midnight) ) or + #( (t[:start] + t[:length]) < (@at - @at.midnight) ) } + add_times(@place,[ + {:start => 6.hours, :length => 2.hours, :override => false}, + {:start => 6.hours, :length => 2.hours, :override => true} + ]) + @at = Time.now.midnight + 9.hours + end + it "should be closed" do - @place.open(@closed_at).should == false + @place.open(@at).should == false end end in_order_to "be closed all day" do end in_order_to "be closed for the day" do end in_order_to "be closed until later in the day" do end in_order_to "have a valid schedule" do it "should not have any overlapping times" it "should have all times within the specified time range" end end describe "a Place with all scheduling capabilities", :shared => true do it_can "be open now" it_can "be open 24 hours" it_can "be open later in the day" it_can "be open earlier in the day" it_can "be open past midnight (tonight)" it_can "be open past midnight (last night)" it_can "be closed now" it_can "be closed all day" it_can "be closed for the day" it_can "be closed until later in the day" end -describe "a Place with no times", :shared => true do - before(:each) do - add_constraint(@place){ false } - @at = Time.now.midnight + 7.hours - @open_at = @at.midnight + 7.hours - @closed_at = @at.midnight + 2.hours - end - - it_should_behave_like "a Place with scheduling capabilities" - it_can "be closed now", "be closed all day", "be closed for the day" -end - describe "a Place with valid times", :shared => true do before(:each) do add_constraint(@place) { true } -=begin - add_times([{:start => 6.hours, :length => 2.hours}]) - @at = Time.now.midnight + 7.hours - @open_at = @at.midnight + 7.hours - @closed_at = @at.midnight + 2.hours -=end end - it_should_behave_like "a Place with scheduling capabilities" - describe "with only regular times" do before(:each) do - add_constraint(@place) {|t| not t[:override]} - add_times(@place, - [{:start => 6.hours, :length => 2.hours}, - {:start => 12.hours, :length => 6.hours}, - {:start => 20.hours, :length => 3.hours}] - ) - @open_at = @at.midnight + 7.hours - @closed_at = @at.midnight + 2.hours + add_constraint(@place) {|t| t[:override] == false } + end + + validate_setup do + it "should have regular times" do + #puts "Regular Times: #{@place.regular_operating_times.inspect}" + @place.regular_operating_times.should_not be_empty + end + + it "should not have any special times" do + #puts "Special Times: #{@place.special_operating_times.inspect}" + @place.special_operating_times.should be_empty + end end - it_should_behave_like "a Place with all scheduling capabilities" + it_can "be open now" + #it_can "be open 24 hours" + #it_can "be open later in the day" + #it_can "be open earlier in the day" + #it_can "be open past midnight (tonight)" + #it_can "be open past midnight (last night)" + + #it_can "be closed now" + #it_can "be closed all day" + #it_can "be closed for the day" + #it_can "be closed until later in the day" + end describe "with only special times" do - #it_should_behave_like "a Place with all scheduling capabilities" + before(:each) do + add_constraint(@place) {|t| t[:override] == true } + end + + + validate_setup do + it "should not have regular times" do + @place.regular_operating_times.should be_empty + end + + it "should have special times" do + @place.special_operating_times.should_not be_empty + end + end + + it_can "be open now" + #it_can "be open 24 hours" + #it_can "be open later in the day" + #it_can "be open earlier in the day" + #it_can "be open past midnight (tonight)" + #it_can "be open past midnight (last night)" + + #it_can "be closed now" + #it_can "be closed all day" + #it_can "be closed for the day" + #it_can "be closed until later in the day" + end describe "with regular and special times" do describe "where the special times are overriding the regular times" do #it_should_behave_like "a Place with all scheduling capabilities" end describe "where the special times are not overriding the regular times" do #it_should_behave_like "a Place with all scheduling capabilities" end end describe "with special times" do describe "extending normal hours" do #it_should_behave_like "a Place with all scheduling capabilities" end describe "reducing normal hours" do #it_should_behave_like "a Place with all scheduling capabilities" end describe "removing all hours" do #it_should_behave_like "a Place with all scheduling capabilities" end describe "moving normal hours (extending and reducing)" do #it_should_behave_like "a Place with all scheduling capabilities" end end end + + describe Place do before(:each) do @valid_attributes = { :name => 'Test Place', :location => 'Somewhere', :phone => '(919) 555-1212' } @place = Place.create!(@valid_attributes) - @place.class_eval("attr_accessor :constraints") - @place.stub(:regular_operating_times).and_return([]) - @place.stub(:special_operating_times).and_return([]) + @place.class_eval <<EOM + attr_accessor :constraints + + def operating_times + regular_operating_times + special_operating_times + end + + def regular_operating_times + @regular_operating_times ||= [] + end + def special_operating_times + @special_operating_times ||= [] + end +EOM + @place.regular_operating_times.should == [] + @place.special_operating_times.should == [] end - it_should_behave_like "a Place with no times" + it_should_behave_like "a Place with scheduling capabilities" it_should_behave_like "a Place with valid times" it "should create a new instance given valid attributes" do Place.create!(@valid_attributes) end it "should not create a new instance without a name" do @valid_attributes.delete(:name) lambda { Place.create!(@valid_attributes) }.should raise_error end + + describe "a Place with no times" do + before(:each) do + add_constraint(@place){ false } + @at = Time.now.midnight + 7.hours + @open_at = @at.midnight + 7.hours + @closed_at = @at.midnight + 2.hours + end + + it_can "be closed now", "be closed all day", "be closed for the day" + end end =begin # TODO Create mocks for OperatingTime so we can test the scheduling methods describe "a Place with OperatingTimes", :shared => true do describe "that are valid now" do it "should have a valid schedule" do end it "should have a valid daily schedule" it "should have a valid current schedule" it "should have regular OperatingTimes" it "should have special OperatingTimes" end describe "that are not valid now" do end end describe Place do before(:each) do @valid_attributes = { :name => 'Test Place', :location => 'Somewhere', :phone => '(919) 555-1212' } end it "should create a new instance given valid attributes" do Place.create!(@valid_attributes) end it "should not create a new instance without a name" do @valid_attributes.delete(:name) lambda { Place.create!(@valid_attributes) }.should raise_error end it "should build a valid dailySchedule" do #TODO Test against a valid schedule as well place = Place.create!(@valid_attributes) place.should_receive(:schedule).with(instance_of(Time), instance_of(Time)).and_return([]) place.daySchedule(Date.today).should == [] end describe "with only special OperatingTimes" do end describe "with only regular OperatingTimes" do end describe "with special OperatingTimes overriding regular OperatingTimes" do end describe "that is currently open" do it_should_behave_like "a Place with OperatingTimes" before(:each) do @at = Time.now.midnight + 7.hours @currentSchedule = stub_times([{:start => 6.hours, :length => 2.hours}]) @daySchedule = [@currentSchedule] @place = Place.create!(@valid_attributes) @place.stub(:operating_times).and_return(@currentSchedule) @place.stub(:regular_operating_times).and_return(@currentSchedule) @place.stub(:special_operating_times).and_return(@currentSchedule) end it "should produce a valid daySchedule" do end it "should produce a valid currentSchedule" do end it "should be open" do @place.should_receive(:currentSchedule). with(duck_type(:midnight)). and_return(@currentSchedule) @place.open?(@at).should == true end end describe "that is closed, but opens later today" do it_should_behave_like "a Place with OperatingTimes" it "should be closed" it "should have a schedule for later today" end describe "that is closed for the day" do it_should_behave_like "a Place with OperatingTimes" it "should be closed" end describe "that is not open at all today" do it_should_behave_like "a Place with OperatingTimes" it "should be closed" it "should not have a schedule for the remainder of today" end describe "that is open past midnight today" do it_should_behave_like "a Place with OperatingTimes" end describe "that was open past midnight yesterday" do it_should_behave_like "a Place with OperatingTimes" end ###### Special Schedules ###### describe "that is normally open, but closed all day today" do it_should_behave_like "a Place with OperatingTimes" end describe "that has special (extended) hours" do it_should_behave_like "a Place with OperatingTimes" end describe "that has special (shortened) hours" do it_should_behave_like "a Place with OperatingTimes" end end describe "a capable Place", :shared => true do it_can_be "closed all day", "closed for the day", "closed until later today" #it_can_be "open past midnight tonight", "open past midnight last night" #it_can_be "open now", "closed now" end describe "a happy Place" do in_order_to_be "closed all day" do it "should be closed right now" do pending("There ain't no @place to test!") { @place.open?(@at) } @place.open?(@at).should == false end it "should have an empty schedule for the day" it "should not have a current schedule" end in_order_to_be "closed for the day" do before(:each) do end it "should be closed right now" it "should not have a current schedule" it_can "have no schedule elements later in the day" it_can "have schedule elements earlier in the day", "have no schedule elements earlier in the day" end in_order_to_be "closed until later today" do before(:each) do end end in_order_to "have schedule elements earlier in the day" do end in_order_to "have no schedule elements earlier in the day" do end in_order_to "have schedule elements later in the day" do end in_order_to "have no schedule elements later in the day" do end it_can_be "closed all day", "closed for the day", "closed until later today" describe "that has regular times" do describe "without special times" do it_should_behave_like "a capable Place" end describe "with special times" do describe "overriding the regular times" do it_should_behave_like "a capable Place" end describe "not overriding the regular times" do it_should_behave_like "a capable Place" end end end describe "that has no regular times" do describe "and no special times" do it_should_behave_like "a capable Place" end describe "but has special times" do it_should_behave_like "a capable Place" end end end =end
michaelansel/dukenow
a74c21e8a76e27bd0d41bfb4ea41d7a5579a7f2f
Minor model refactoring; Massive rewrite of scheduling specs for Place model using new RSpec "capabilities"
diff --git a/app/models/place.rb b/app/models/place.rb index 3d1ba65..63062ad 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,115 +1,110 @@ class Place < ActiveRecord::Base has_many :operating_times acts_as_taggable_on :tags validates_presence_of :name def special_operating_times - OperatingTime.find( :all, :conditions => ["place_id = ? and override != 0", id], :order => "startDate ASC, opensAt ASC" ) + OperatingTime.find( :all, :conditions => {:place_id => id, :override => 1}, :order => "startDate ASC, opensAt ASC" ) end def regular_operating_times - OperatingTime.find( :all, :conditions => ["place_id = ? and override == 0", id], :order => "startDate ASC, opensAt ASC" ) + OperatingTime.find( :all, :conditions => {:place_id => id, :override => 0}, :order => "startDate ASC, opensAt ASC" ) end # Returns an array of OperatingTimes def schedule(startAt,endAt) # TODO Returns the schedule for a specified time window # TODO Handle events starting within the range but ending outside of it? regular_times = [] regular_operating_times.each do |ot| if ot.startDate >= startAt.to_date-1 and ot.endDate <= endAt.to_date+1 # Yesterday open,close = ot.to_times((startAt.to_date - 1).midnight) if false and close >= ot.at and ot.flags & 1<<ot.at.wday > 0 t = ot.dup t.opensAt = startAt regular_times << t t=nil end # Today open,close = ot.to_times(startAt.to_date.midnight) - regular_times << ot.dup if open >= startAt and close < endAt and ot.flags & 1<<startAt.to_date.midnight.wday > 0 + ## TODO Add all occurances to the array, not just the first one + regular_times << ot if open >= startAt and close < endAt and ot.flags & 1<<startAt.to_date.midnight.wday > 0 # Tomorrow open,close = ot.to_times(endAt == endAt.midnight ? endAt : endAt.midnight + 1.days) if false and open < endAt and ot.flags & 1<<ot.at.wday > 0 t = ot.dup t.closesAt = endAt regular_times << t t=nil end end end special_times = special_operating_times.select do |ot| ot.at = startAt ot.startDate ||= startAt.to_date ot.endDate ||= endAt.to_date (ot.startDate <= startAt.to_date and ot.endDate >= endAt.to_date) and ((ot.opensAt >= startAt and ot.opensAt <= endAt) or (ot.closesAt >= startAt and ot.closesAt <= endAt)) end # TODO Handle combinations (i.e. part special, part regular) special_times == [] ? regular_times : special_times - regular_times + regular_times # Ignore, just return regular times end def daySchedule(at = Date.today) at = at.to_date if at.class == Time or at.class == DateTime schedule = schedule(at.midnight,(at+1).midnight) #schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } #schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end - - schedule.sort{|a,b|a.opensAt <=> b.opensAt} =end + + schedule.sort{|a,b|a.start <=> b.start} end def currentSchedule(at = Time.now) current_schedule = nil - daySchedule(at).each do |optime| - if optime.opensAt <= at and - optime.closesAt >= at - #RAILS_DEFAULT_LOGGER.debug "Opens At: #{optime.opensAt.time(at).to_s}" - #RAILS_DEFAULT_LOGGER.debug "Closes At: #{optime.closesAt.time(at).to_s}" - current_schedule = optime - end - end - - current_schedule + daySchedule(at).select { |optime| + open, close = optime.to_times(at) + open <= at and at <= close + }[0] end def open?(at = Time.now) a = currentSchedule(at) return a ? true : false end # Alias for <tt>open?</tt> def open(at = Time.now); open? at ; end def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end def to_xml(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end end diff --git a/spec/models/place_spec.rb b/spec/models/place_spec.rb index 10996dc..f136f82 100644 --- a/spec/models/place_spec.rb +++ b/spec/models/place_spec.rb @@ -1,126 +1,451 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') -# TODO Create mocks for OperatingTime so we can test the scheduling methods -describe "a Place with OperatingTimes", :shared => true do - describe "that are valid now" do - it "should have a valid schedule" do +def add_constraint(place, &block) + place.constraints ||= [] + place.constraints << block +end + +def add_times(place, times = []) + times.each do |t| + place.constraints.each do |c| + if c.call(t) # If it matches the constraint + + ot = mock_model(OperatingTime) + ot.stub(:start).and_return(t[:start]) + ot.stub(:length).and_return(t[:length]) + ot.stub(:override).and_return(t[:override] || 0) + ot.stub(:startDate).and_return(t[:startDate] || Date.yesterday) + ot.stub(:endDate).and_return(t[:endDate] || Date.tomorrow) + ot.stub(:flags).and_return(t[:flags] || OperatingTime::ALL_DAYS) + ot.stub(:place_id).and_return(place.id) + ot.should_receive(:to_times).any_number_of_times do |at| + at.should respond_to(:midnight) + + open = at.midnight + ot.start + close = open + ot.length + [open,close] + end + + if t[:override] + place.special_operating_times << ot + else + place.regular_operating_times << ot + end + + end end - it "should have a valid daily schedule" - it "should have a valid current schedule" - it "should have regular OperatingTimes" - it "should have special OperatingTimes" end +end - describe "that are not valid now" do - end +def remove_times(place, times = []) end def build_place_from_times(times = []) place = Place.create!(@valid_attributes) + + regularTimes,specialTimes = stub_times(times, place.id) + + place.stub(:operating_times).and_return(regularTimes + specialTimes) + place.stub(:regular_operating_times).and_return(regularTimes) + place.stub(:special_operating_times).and_return(specialTimes) + + place +end + +def stub_times(times = [], place_id = 0) regularTimes = [] specialTimes = [] times.each do |time| ot = mock_model(OperatingTime) - ot.stub(:opensAt).and_return(time[:start]) + ot.stub(:start).and_return(time[:start]) ot.stub(:length).and_return(time[:length]) ot.stub(:override).and_return(time[:override] || 0) ot.stub(:startDate).and_return(time[:startDate] || Date.yesterday) ot.stub(:endDate).and_return(time[:endDate] || Date.tomorrow) ot.stub(:flags).and_return(time[:flags] || OperatingTime::ALL_DAYS) - ot.stub(:place_id).and_return(place.id) - ot.stub(:to_times).with(instance_of(Time)).and_return do |at| - open = at.midnight + ot.opensAt + ot.stub(:place_id).and_return(place_id) + ot.should_receive(:to_times).any_number_of_times do |at| + at.should respond_to(:midnight) + + open = at.midnight + ot.start close = open + ot.length [open,close] end if time.keys.include?(:override) and time[:override] == 1 specialTimes << ot elsif time[:override].nil? or time[:override] == 0 regularTimes << ot end end - place.stub(:operating_times).and_return(regularTimes + specialTimes) - place.stub(:regular_operating_times).and_return(regularTimes) - place.stub(:special_operating_times).and_return(specialTimes) + [regularTimes,specialTimes] +end - place +describe "a Place with scheduling capabilities", :shared => true do + + in_order_to "be open now" do + it "should be open" do + @place.open(@open_at).should == true + end + end + + in_order_to "be open 24 hours" do + end + + in_order_to "be open later in the day" do + it "should have a schedule between now and midnight" do + @place.schedule(@at,@at.midnight + 24.hours).size.should > 0 + end + end + + in_order_to "be open earlier in the day" do + end + + in_order_to "be open past midnight (tonight)" do + end + + in_order_to "be open past midnight (last night)" do + end + + + in_order_to "be closed now" do + it "should be closed" do + @place.open(@closed_at).should == false + end + end + + in_order_to "be closed all day" do + end + + in_order_to "be closed for the day" do + end + + in_order_to "be closed until later in the day" do + end + + in_order_to "have a valid schedule" do + it "should not have any overlapping times" + it "should have all times within the specified time range" + end +end + +describe "a Place with all scheduling capabilities", :shared => true do + it_can "be open now" + it_can "be open 24 hours" + it_can "be open later in the day" + it_can "be open earlier in the day" + it_can "be open past midnight (tonight)" + it_can "be open past midnight (last night)" + + it_can "be closed now" + it_can "be closed all day" + it_can "be closed for the day" + it_can "be closed until later in the day" +end + +describe "a Place with no times", :shared => true do + before(:each) do + add_constraint(@place){ false } + @at = Time.now.midnight + 7.hours + @open_at = @at.midnight + 7.hours + @closed_at = @at.midnight + 2.hours + end + + it_should_behave_like "a Place with scheduling capabilities" + it_can "be closed now", "be closed all day", "be closed for the day" +end + +describe "a Place with valid times", :shared => true do + before(:each) do + add_constraint(@place) { true } +=begin + add_times([{:start => 6.hours, :length => 2.hours}]) + @at = Time.now.midnight + 7.hours + @open_at = @at.midnight + 7.hours + @closed_at = @at.midnight + 2.hours +=end + end + + it_should_behave_like "a Place with scheduling capabilities" + + describe "with only regular times" do + before(:each) do + add_constraint(@place) {|t| not t[:override]} + add_times(@place, + [{:start => 6.hours, :length => 2.hours}, + {:start => 12.hours, :length => 6.hours}, + {:start => 20.hours, :length => 3.hours}] + ) + @open_at = @at.midnight + 7.hours + @closed_at = @at.midnight + 2.hours + end + + it_should_behave_like "a Place with all scheduling capabilities" + end + + describe "with only special times" do + #it_should_behave_like "a Place with all scheduling capabilities" + end + + describe "with regular and special times" do + describe "where the special times are overriding the regular times" do + #it_should_behave_like "a Place with all scheduling capabilities" + end + + describe "where the special times are not overriding the regular times" do + #it_should_behave_like "a Place with all scheduling capabilities" + end + end + + + describe "with special times" do + describe "extending normal hours" do + #it_should_behave_like "a Place with all scheduling capabilities" + end + + describe "reducing normal hours" do + #it_should_behave_like "a Place with all scheduling capabilities" + end + + describe "removing all hours" do + #it_should_behave_like "a Place with all scheduling capabilities" + end + + describe "moving normal hours (extending and reducing)" do + #it_should_behave_like "a Place with all scheduling capabilities" + end + end end + +describe Place do + before(:each) do + @valid_attributes = { + :name => 'Test Place', + :location => 'Somewhere', + :phone => '(919) 555-1212' + } + + @place = Place.create!(@valid_attributes) + @place.class_eval("attr_accessor :constraints") + + @place.stub(:regular_operating_times).and_return([]) + @place.stub(:special_operating_times).and_return([]) + end + + it_should_behave_like "a Place with no times" + it_should_behave_like "a Place with valid times" + + it "should create a new instance given valid attributes" do + Place.create!(@valid_attributes) + end + + it "should not create a new instance without a name" do + @valid_attributes.delete(:name) + lambda { Place.create!(@valid_attributes) }.should raise_error + end +end + + + + + + + +=begin +# TODO Create mocks for OperatingTime so we can test the scheduling methods +describe "a Place with OperatingTimes", :shared => true do + describe "that are valid now" do + it "should have a valid schedule" do + end + it "should have a valid daily schedule" + it "should have a valid current schedule" + it "should have regular OperatingTimes" + it "should have special OperatingTimes" + end + + describe "that are not valid now" do + end +end + + describe Place do before(:each) do @valid_attributes = { :name => 'Test Place', :location => 'Somewhere', :phone => '(919) 555-1212' } end it "should create a new instance given valid attributes" do Place.create!(@valid_attributes) end it "should not create a new instance without a name" do @valid_attributes.delete(:name) lambda { Place.create!(@valid_attributes) }.should raise_error end it "should build a valid dailySchedule" do #TODO Test against a valid schedule as well place = Place.create!(@valid_attributes) place.should_receive(:schedule).with(instance_of(Time), instance_of(Time)).and_return([]) place.daySchedule(Date.today).should == [] end + describe "with only special OperatingTimes" do + end + describe "with only regular OperatingTimes" do + end + describe "with special OperatingTimes overriding regular OperatingTimes" do + end + describe "that is currently open" do it_should_behave_like "a Place with OperatingTimes" before(:each) do - @place = build_place_from_times([{:start => 6.hours, :length => 2.hours}]) @at = Time.now.midnight + 7.hours + @currentSchedule = stub_times([{:start => 6.hours, :length => 2.hours}]) + @daySchedule = [@currentSchedule] + + @place = Place.create!(@valid_attributes) + @place.stub(:operating_times).and_return(@currentSchedule) + @place.stub(:regular_operating_times).and_return(@currentSchedule) + @place.stub(:special_operating_times).and_return(@currentSchedule) + end + + it "should produce a valid daySchedule" do + end + + it "should produce a valid currentSchedule" do end it "should be open" do + @place.should_receive(:currentSchedule). + with(duck_type(:midnight)). + and_return(@currentSchedule) + @place.open?(@at).should == true end end describe "that is closed, but opens later today" do it_should_behave_like "a Place with OperatingTimes" it "should be closed" it "should have a schedule for later today" end describe "that is closed for the day" do it_should_behave_like "a Place with OperatingTimes" it "should be closed" end describe "that is not open at all today" do it_should_behave_like "a Place with OperatingTimes" it "should be closed" it "should not have a schedule for the remainder of today" end describe "that is open past midnight today" do it_should_behave_like "a Place with OperatingTimes" end describe "that was open past midnight yesterday" do it_should_behave_like "a Place with OperatingTimes" end ###### Special Schedules ###### describe "that is normally open, but closed all day today" do it_should_behave_like "a Place with OperatingTimes" end describe "that has special (extended) hours" do it_should_behave_like "a Place with OperatingTimes" end describe "that has special (shortened) hours" do it_should_behave_like "a Place with OperatingTimes" end end + + + + +describe "a capable Place", :shared => true do + it_can_be "closed all day", "closed for the day", "closed until later today" + #it_can_be "open past midnight tonight", "open past midnight last night" + #it_can_be "open now", "closed now" +end + +describe "a happy Place" do + in_order_to_be "closed all day" do + + it "should be closed right now" do + pending("There ain't no @place to test!") { @place.open?(@at) } + @place.open?(@at).should == false + end + + it "should have an empty schedule for the day" + it "should not have a current schedule" + end + + in_order_to_be "closed for the day" do + before(:each) do + end + + it "should be closed right now" + it "should not have a current schedule" + it_can "have no schedule elements later in the day" + it_can "have schedule elements earlier in the day", "have no schedule elements earlier in the day" + end + + in_order_to_be "closed until later today" do + before(:each) do + end + + end + + in_order_to "have schedule elements earlier in the day" do + end + + in_order_to "have no schedule elements earlier in the day" do + end + + in_order_to "have schedule elements later in the day" do + end + + in_order_to "have no schedule elements later in the day" do + end + + it_can_be "closed all day", "closed for the day", "closed until later today" + + describe "that has regular times" do + describe "without special times" do + it_should_behave_like "a capable Place" + end + + describe "with special times" do + describe "overriding the regular times" do + it_should_behave_like "a capable Place" + end + + describe "not overriding the regular times" do + it_should_behave_like "a capable Place" + end + end + end + + describe "that has no regular times" do + describe "and no special times" do + it_should_behave_like "a capable Place" + end + + describe "but has special times" do + it_should_behave_like "a capable Place" + end + end + +end +=end
michaelansel/dukenow
f4139650dff37442e9854292c8c77e1f3d9aafc3
Bugfix to RSpec capabilities addon
diff --git a/spec/capabilities.rb b/spec/capabilities.rb index 30e5113..7bb0784 100644 --- a/spec/capabilities.rb +++ b/spec/capabilities.rb @@ -1,50 +1,52 @@ require 'rubygems' require 'spec' module Spec module Example module ExampleGroupMethods - def it_can(*capabilities) capabilities.each do |c| include_capability(c) end end def it_can_be(*capabilities) capabilities.each do |c| it_can("be #{c}") end end def in_order_to(*args, &block) + raise Spec::Example::NoDescriptionError.new("example group", caller(0)[1]) if args.empty? + options = add_options(args) + set_location(options, caller(0)[1]) Spec::Example::CapabilityFactory.create_capability(*args, &block) end def in_order_to_be(*args, &block) in_order_to("be", *args, &block) end def include_capability(capability) case capability when Capability include capability else unless example_group = Capability.find(capability) raise RuntimeError.new("Capability '#{capability}' can not be found") end include(example_group) end end end class Capability < SharedExampleGroup end class CapabilityFactory < ExampleGroupFactory - def self.create_capability(*args, &example_group_block) # :nodoc: - ::Spec::Example::Capability.register(*args, &example_group_block) + def self.create_capability(*args, &capability_block) # :nodoc: + ::Spec::Example::Capability.register(*args, &capability_block) end end end end
michaelansel/dukenow
4df280b89d09342a016d4e9734004527c57fdac9
Add 'capabilities' to RSpec DSL and include in spec_helper
diff --git a/spec/capabilities.rb b/spec/capabilities.rb new file mode 100644 index 0000000..30e5113 --- /dev/null +++ b/spec/capabilities.rb @@ -0,0 +1,50 @@ +require 'rubygems' +require 'spec' + +module Spec + module Example + module ExampleGroupMethods + + def it_can(*capabilities) + capabilities.each do |c| + include_capability(c) + end + end + def it_can_be(*capabilities) + capabilities.each do |c| + it_can("be #{c}") + end + end + + def in_order_to(*args, &block) + Spec::Example::CapabilityFactory.create_capability(*args, &block) + end + def in_order_to_be(*args, &block) + in_order_to("be", *args, &block) + end + + + def include_capability(capability) + case capability + when Capability + include capability + else + unless example_group = Capability.find(capability) + raise RuntimeError.new("Capability '#{capability}' can not be found") + end + include(example_group) + end + end + + end + + class Capability < SharedExampleGroup + end + + class CapabilityFactory < ExampleGroupFactory + def self.create_capability(*args, &example_group_block) # :nodoc: + ::Spec::Example::Capability.register(*args, &example_group_block) + end + end + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 0d10446..fa95031 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,47 +1,48 @@ # This file is copied to ~/spec when you run 'ruby script/generate rspec' # from the project root directory. ENV["RAILS_ENV"] ||= 'test' require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT) require 'spec/autorun' require 'spec/rails' +require 'spec/capabilities' Spec::Runner.configure do |config| # If you're not using ActiveRecord you should remove these # lines, delete config/database.yml and disable :active_record # in your config/boot.rb config.use_transactional_fixtures = true config.use_instantiated_fixtures = false config.fixture_path = RAILS_ROOT + '/spec/fixtures/' # == Fixtures # # You can declare fixtures for each example_group like this: # describe "...." do # fixtures :table_a, :table_b # # Alternatively, if you prefer to declare them only once, you can # do so right here. Just uncomment the next line and replace the fixture # names with your fixtures. # # config.global_fixtures = :table_a, :table_b # # If you declare global fixtures, be aware that they will be declared # for all of your examples, even those that don't use them. # # You can also declare which fixtures to use (for example fixtures for test/fixtures): # # config.fixture_path = RAILS_ROOT + '/spec/fixtures/' # # == Mock Framework # # RSpec uses it's own mocking framework by default. If you prefer to # use mocha, flexmock or RR, uncomment the appropriate line: # # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr # # == Notes # # For more information take a look at Spec::Runner::Configuration and Spec::Runner end
michaelansel/dukenow
a5aca8b7bb4b15a23326c5f7845fa82cbd3b297a
Start adding specs for Place.schedule and fixing model as necessary
diff --git a/app/models/place.rb b/app/models/place.rb index 00d480d..3d1ba65 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,119 +1,115 @@ class Place < ActiveRecord::Base has_many :operating_times acts_as_taggable_on :tags validates_presence_of :name def special_operating_times OperatingTime.find( :all, :conditions => ["place_id = ? and override != 0", id], :order => "startDate ASC, opensAt ASC" ) end def regular_operating_times OperatingTime.find( :all, :conditions => ["place_id = ? and override == 0", id], :order => "startDate ASC, opensAt ASC" ) end # Returns an array of OperatingTimes def schedule(startAt,endAt) # TODO Returns the schedule for a specified time window # TODO Handle events starting within the range but ending outside of it? regular_times = [] regular_operating_times.each do |ot| - ot.startDate ||= startAt.to_date - ot.endDate ||= endAt.to_date - if ot.startDate >= startAt.to_date-1 and ot.endDate <= endAt.to_date+1 - ot.at = nil # Yesterday - ot.at = (startAt.to_date - 1).midnight - if ot.closesAt >= ot.at and ot.flags & 1<<ot.at.wday > 0 + open,close = ot.to_times((startAt.to_date - 1).midnight) + if false and close >= ot.at and ot.flags & 1<<ot.at.wday > 0 t = ot.dup t.opensAt = startAt regular_times << t t=nil end # Today - ot.at = startAt.to_date.midnight - regular_times << ot.dup if ot.opensAt >= startAt and ot.opensAt < endAt and ot.flags & 1<<ot.at.wday > 0 + open,close = ot.to_times(startAt.to_date.midnight) + regular_times << ot.dup if open >= startAt and close < endAt and ot.flags & 1<<startAt.to_date.midnight.wday > 0 # Tomorrow - ot.at = endAt == endAt.midnight ? endAt : endAt.midnight + 1.days - if ot.opensAt < endAt and ot.flags & 1<<ot.at.wday > 0 + open,close = ot.to_times(endAt == endAt.midnight ? endAt : endAt.midnight + 1.days) + if false and open < endAt and ot.flags & 1<<ot.at.wday > 0 t = ot.dup t.closesAt = endAt regular_times << t t=nil end end end special_times = special_operating_times.select do |ot| ot.at = startAt ot.startDate ||= startAt.to_date ot.endDate ||= endAt.to_date (ot.startDate <= startAt.to_date and ot.endDate >= endAt.to_date) and ((ot.opensAt >= startAt and ot.opensAt <= endAt) or (ot.closesAt >= startAt and ot.closesAt <= endAt)) end # TODO Handle combinations (i.e. part special, part regular) special_times == [] ? regular_times : special_times regular_times end def daySchedule(at = Date.today) at = at.to_date if at.class == Time or at.class == DateTime schedule = schedule(at.midnight,(at+1).midnight) #schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } #schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end schedule.sort{|a,b|a.opensAt <=> b.opensAt} =end end def currentSchedule(at = Time.now) current_schedule = nil daySchedule(at).each do |optime| if optime.opensAt <= at and optime.closesAt >= at #RAILS_DEFAULT_LOGGER.debug "Opens At: #{optime.opensAt.time(at).to_s}" #RAILS_DEFAULT_LOGGER.debug "Closes At: #{optime.closesAt.time(at).to_s}" current_schedule = optime end end current_schedule end def open?(at = Time.now) a = currentSchedule(at) return a ? true : false end # Alias for <tt>open?</tt> def open(at = Time.now); open? at ; end def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end def to_xml(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end end diff --git a/spec/models/place_spec.rb b/spec/models/place_spec.rb index 0fbb4fd..10996dc 100644 --- a/spec/models/place_spec.rb +++ b/spec/models/place_spec.rb @@ -1,71 +1,126 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') # TODO Create mocks for OperatingTime so we can test the scheduling methods describe "a Place with OperatingTimes", :shared => true do - it "should have a valid daily schedule" - it "should have a valid current schedule" - it "should have regular OperatingTimes" - it "should have special OperatingTimes" + describe "that are valid now" do + it "should have a valid schedule" do + end + it "should have a valid daily schedule" + it "should have a valid current schedule" + it "should have regular OperatingTimes" + it "should have special OperatingTimes" + end + + describe "that are not valid now" do + end +end + +def build_place_from_times(times = []) + place = Place.create!(@valid_attributes) + regularTimes = [] + specialTimes = [] + + times.each do |time| + ot = mock_model(OperatingTime) + ot.stub(:opensAt).and_return(time[:start]) + ot.stub(:length).and_return(time[:length]) + ot.stub(:override).and_return(time[:override] || 0) + ot.stub(:startDate).and_return(time[:startDate] || Date.yesterday) + ot.stub(:endDate).and_return(time[:endDate] || Date.tomorrow) + ot.stub(:flags).and_return(time[:flags] || OperatingTime::ALL_DAYS) + ot.stub(:place_id).and_return(place.id) + ot.stub(:to_times).with(instance_of(Time)).and_return do |at| + open = at.midnight + ot.opensAt + close = open + ot.length + [open,close] + end + + if time.keys.include?(:override) and time[:override] == 1 + specialTimes << ot + elsif time[:override].nil? or time[:override] == 0 + regularTimes << ot + end + end + + place.stub(:operating_times).and_return(regularTimes + specialTimes) + place.stub(:regular_operating_times).and_return(regularTimes) + place.stub(:special_operating_times).and_return(specialTimes) + + place end describe Place do before(:each) do @valid_attributes = { :name => 'Test Place', :location => 'Somewhere', :phone => '(919) 555-1212' } end it "should create a new instance given valid attributes" do Place.create!(@valid_attributes) end it "should not create a new instance without a name" do @valid_attributes.delete(:name) lambda { Place.create!(@valid_attributes) }.should raise_error end + it "should build a valid dailySchedule" do + #TODO Test against a valid schedule as well + place = Place.create!(@valid_attributes) + place.should_receive(:schedule).with(instance_of(Time), instance_of(Time)).and_return([]) + place.daySchedule(Date.today).should == [] + end + describe "that is currently open" do it_should_behave_like "a Place with OperatingTimes" - it "should be open" + before(:each) do + @place = build_place_from_times([{:start => 6.hours, :length => 2.hours}]) + @at = Time.now.midnight + 7.hours + end + + it "should be open" do + @place.open?(@at).should == true + end end describe "that is closed, but opens later today" do it_should_behave_like "a Place with OperatingTimes" it "should be closed" it "should have a schedule for later today" end describe "that is closed for the day" do it_should_behave_like "a Place with OperatingTimes" it "should be closed" end describe "that is not open at all today" do it_should_behave_like "a Place with OperatingTimes" it "should be closed" it "should not have a schedule for the remainder of today" end describe "that is open past midnight today" do it_should_behave_like "a Place with OperatingTimes" end describe "that was open past midnight yesterday" do it_should_behave_like "a Place with OperatingTimes" end ###### Special Schedules ###### describe "that is normally open, but closed all day today" do it_should_behave_like "a Place with OperatingTimes" end describe "that has special (extended) hours" do it_should_behave_like "a Place with OperatingTimes" end describe "that has special (shortened) hours" do it_should_behave_like "a Place with OperatingTimes" end end
michaelansel/dukenow
381ef728a477b65fc292e2aadf6acb9c000eb838
Implement and test OperatingTime.to_times
diff --git a/app/models/operating_time.rb b/app/models/operating_time.rb index 1ef3a01..0d41aa0 100644 --- a/app/models/operating_time.rb +++ b/app/models/operating_time.rb @@ -1,186 +1,184 @@ class OperatingTime < ActiveRecord::Base belongs_to :place validates_presence_of :place_id validates_associated :place validate :end_after_start, :daysOfWeek_valid ## DaysOfWeek Constants ## SUNDAY = 0b00000001 MONDAY = 0b00000010 TUESDAY = 0b00000100 WEDNESDAY = 0b00001000 THURSDAY = 0b00010000 FRIDAY = 0b00100000 SATURDAY = 0b01000000 ALL_DAYS = (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) ## Validations ## def end_after_start if endDate < startDate errors.add_to_base("End date cannot preceed start date") end end def daysOfWeek_valid daysOfWeek == daysOfWeek & (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) end ## End Validations ## # TODO Is this OperatingTime applicable at +time+ def valid_at(time=Time.now) raise NotImplementedError end def override read_attribute(:override) == 1 end def override=(mode) if mode == true or mode == "true" or mode == 1 write_attribute(:override, true) elsif mode == false or mode == "false" or mode == 0 write_attribute(:override, false) else raise ArgumentError, "Invalid override value (#{mode.inspect}); Accepts true/false, 1/0" end end def daysOfWeek=(newDow) if newDow & ALL_DAYS == newDow write_attribute(:daysOfWeek, newDow & ALL_DAYS) else # Invalid input raise ArgumentError, "Not a valid value for daysOfWeek (#{newDow.inspect})" end end ## daysOfWeek Helper/Accessors ## # Hash mapping day of week (Symbol) to valid(true)/invalid(false) def daysOfWeekHash { :sunday => (daysOfWeek & SUNDAY ) > 0, :monday => (daysOfWeek & MONDAY ) > 0, :tuesday => (daysOfWeek & TUESDAY ) > 0, :wednesday => (daysOfWeek & WEDNESDAY ) > 0, :thursday => (daysOfWeek & THURSDAY ) > 0, :friday => (daysOfWeek & FRIDAY ) > 0, :saturday => (daysOfWeek & SATURDAY ) > 0} end # Array beginning with Sunday of valid(true)/inactive(false) values def daysOfWeekArray dow = daysOfWeekHash [ dow[:sunday], dow[:monday], dow[:tuesday], dow[:wednesday], dow[:thursday], dow[:friday], dow[:saturday] ] end # Human-readable string of applicable days of week def daysOfWeekString dow = daysOfWeekHash str = "" str += "Su" if dow[:sunday] str += "M" if dow[:monday] str += "Tu" if dow[:tuesday] str += "W" if dow[:wednesday] str += "Th" if dow[:thursday] str += "F" if dow[:friday] str += "Sa" if dow[:saturday] str end ## End daysOfWeek Helper/Accessors ## - # TODO Return array of times representing the open and close times at a certain occurence + # Return array of times representing the open and close times at a certain occurence def to_times(at = Time.now) - raise NotImplementedError - open = Time.now - close = Time.now + open = at.midnight + start + close = open + length [open,close] end def to_xml(params) super(params.merge({:only => [:id, :place_id, :flags], :methods => [ :opensAt, :closesAt, :startDate, :endDate ]})) end ##### TODO DEPRECATED METHODS ##### def at @at end def at=(time) @opensAt = nil @closesAt = nil @at = time end # Returns a Time object representing the beginning of this OperatingTime def opensAt @opensAt ||= relativeTime.openTime(at) end def closesAt @closesAt ||= relativeTime.closeTime(at) end # Sets the beginning of this OperatingTime # Input: params = { :hour => 12, :minute => 45 } def opensAt=(time) if time.class == Time @opensAt = relativeTime.openTime = time else super end end # Sets the end of this OperatingTime def closesAt=(time) @closesAt = relativeTime.closeTime = time end - - def length - closesAt - opensAt + def start + read_attribute(:opensAt) end # Returns a RelativeTime object representing this OperatingTime def relativeTime @relativeTime ||= RelativeTime.new(self, :opensAt, :length) end; protected :relativeTime # Backwards compatibility with old database schema # TODO GET RID OF THIS!!! def flags ( (override ? 1 : 0) << 7) | read_attribute(:daysOfWeek) end # FIXME Deprecated, use +override+ instead def special override end # Input: isSpecial = true/false # FIXME Deprecated, use +override=+ instead def special=(isSpecial) if isSpecial == true or isSpecial == "true" or isSpecial == 1 self.override = true elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 self.override = false end end end diff --git a/spec/models/operating_time_spec.rb b/spec/models/operating_time_spec.rb index 7650029..26b2e15 100644 --- a/spec/models/operating_time_spec.rb +++ b/spec/models/operating_time_spec.rb @@ -1,115 +1,146 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe OperatingTime do before(:each) do @place = mock_model(Place) @valid_attributes = { :place_id => @place.id, :opensAt => (Time.now - 1.hours).to_i, :length => 2.hours, :daysOfWeek => OperatingTime::ALL_DAYS, :startDate => Date.yesterday, :endDate => Date.tomorrow, :override => false } @operating_time = OperatingTime.create!(@valid_attributes) end it "should create a new instance given all valid attributes" do OperatingTime.create!(@valid_attributes) end describe "missing required attributes" do it "should not create a new instance without a valid start time" it "should not create a new instance without a valid length" it "should not create a new instance without a valid Place reference" it "should not create a new instance without a valid start date" it "should not create a new instance without a valid end date" end describe "missing default-able attributes" do it "should default daysOfWeek to 0" do @valid_attributes.delete(:daysOfWeek) if @valid_attributes[:daysOfWeek] OperatingTime.create!(@valid_attributes).daysOfWeek.should == 0 end it "should default override to false" do @valid_attributes.delete(:override) if @valid_attributes[:override] OperatingTime.create!(@valid_attributes).override.should == false end end describe "given invalid attributes" do def create @operating_time = OperatingTime.create!(@valid_attributes) end =begin it "should create a new instance, but ignore an invalid override value" do @valid_attributes[:override] = "invalid" create @operating_time.override.should == false # where false is the default value @valid_attributes[:override] = 10 create @operating_time.override.should == false # where false is the default value end it "should create a new instance, but ignore an invalid daysOfWeek value" do @valid_attributes[:daysOfWeek] = 1000 create @operating_time.daysOfWeek.should == 0 # where 0 is the default value end =end it "should not create a new instance with an invalid start time" it "should not create a new instance with an invalid length" it "should not create a new instance with an invalid Place reference" it "should not create a new instance with an invalid start date" it "should not create a new instance with an invalid end date" end it "should enable override mode" do @operating_time.should_receive(:write_attribute).with(:override, true).exactly(3).times @operating_time.override = true @operating_time.override = "true" @operating_time.override = 1 end it "should disable override mode" do @operating_time.should_receive(:write_attribute).with(:override, false).exactly(3).times @operating_time.override = false @operating_time.override = "false" @operating_time.override = 0 end it "should complain about invalid override values, but not change the value" do @operating_time.override = true @operating_time.override.should == true #TODO Should nil be ignored or errored? lambda { @operating_time.override = nil }.should raise_error(ArgumentError) @operating_time.override.should == true lambda { @operating_time.override = "invalid" }.should raise_error(ArgumentError) @operating_time.override.should == true lambda { @operating_time.override = false }.should_not raise_error @operating_time.override.should == false end it "should complain about invalid daysOfWeek values, but not change the value" do @operating_time.daysOfWeek = OperatingTime::SUNDAY @operating_time.daysOfWeek.should == OperatingTime::SUNDAY #TODO Should nil be ignored or errored? lambda { @operating_time.daysOfWeek = nil }.should raise_error(ArgumentError) @operating_time.daysOfWeek.should == OperatingTime::SUNDAY lambda { @operating_time.daysOfWeek = 200 }.should raise_error(ArgumentError) @operating_time.daysOfWeek.should == OperatingTime::SUNDAY lambda { @operating_time.daysOfWeek= OperatingTime::MONDAY }.should_not raise_error @operating_time.daysOfWeek.should == OperatingTime::MONDAY end + + describe "with open and close times" do + before(:each) do + @now = Time.now + + @open = @now - 1.hours + @close = @now + 1.hours + + start = @open - @open.midnight + length = @close - @open + @valid_attributes.update({ + :opensAt => start, + :length => length + }) + @operating_time = OperatingTime.create!(@valid_attributes) + end + + it "should return valid open and close times for 'now'" do + open,close = @operating_time.to_times() + open.to_i.should == @open.to_i + close.to_i.should == @close.to_i + end + + it "should return valid open and close times for a given time" do + @open, @close, @now = [@open,@close,@now].collect{|t| t + 5.days} + + open,close = @operating_time.to_times( @now ) + open.to_i.should == @open.to_i + close.to_i.should == @close.to_i + end + end end
michaelansel/dukenow
56f9db6c189f0742eb097b8b4d230ec62d23b360
Make errors more descriptive
diff --git a/app/models/operating_time.rb b/app/models/operating_time.rb index 9ff4933..1ef3a01 100644 --- a/app/models/operating_time.rb +++ b/app/models/operating_time.rb @@ -1,186 +1,186 @@ class OperatingTime < ActiveRecord::Base belongs_to :place validates_presence_of :place_id validates_associated :place validate :end_after_start, :daysOfWeek_valid ## DaysOfWeek Constants ## SUNDAY = 0b00000001 MONDAY = 0b00000010 TUESDAY = 0b00000100 WEDNESDAY = 0b00001000 THURSDAY = 0b00010000 FRIDAY = 0b00100000 SATURDAY = 0b01000000 ALL_DAYS = (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) ## Validations ## def end_after_start if endDate < startDate errors.add_to_base("End date cannot preceed start date") end end def daysOfWeek_valid daysOfWeek == daysOfWeek & (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) end ## End Validations ## # TODO Is this OperatingTime applicable at +time+ def valid_at(time=Time.now) raise NotImplementedError end def override read_attribute(:override) == 1 end def override=(mode) if mode == true or mode == "true" or mode == 1 write_attribute(:override, true) elsif mode == false or mode == "false" or mode == 0 write_attribute(:override, false) else - raise ArgumentError, "Invalid override value; Accepts true/false, 1/0" + raise ArgumentError, "Invalid override value (#{mode.inspect}); Accepts true/false, 1/0" end end def daysOfWeek=(newDow) if newDow & ALL_DAYS == newDow write_attribute(:daysOfWeek, newDow & ALL_DAYS) else # Invalid input - raise ArgumentError, "Not a valid value for daysOfWeek" + raise ArgumentError, "Not a valid value for daysOfWeek (#{newDow.inspect})" end end ## daysOfWeek Helper/Accessors ## # Hash mapping day of week (Symbol) to valid(true)/invalid(false) def daysOfWeekHash { :sunday => (daysOfWeek & SUNDAY ) > 0, :monday => (daysOfWeek & MONDAY ) > 0, :tuesday => (daysOfWeek & TUESDAY ) > 0, :wednesday => (daysOfWeek & WEDNESDAY ) > 0, :thursday => (daysOfWeek & THURSDAY ) > 0, :friday => (daysOfWeek & FRIDAY ) > 0, :saturday => (daysOfWeek & SATURDAY ) > 0} end # Array beginning with Sunday of valid(true)/inactive(false) values def daysOfWeekArray dow = daysOfWeekHash [ dow[:sunday], dow[:monday], dow[:tuesday], dow[:wednesday], dow[:thursday], dow[:friday], dow[:saturday] ] end # Human-readable string of applicable days of week def daysOfWeekString dow = daysOfWeekHash str = "" str += "Su" if dow[:sunday] str += "M" if dow[:monday] str += "Tu" if dow[:tuesday] str += "W" if dow[:wednesday] str += "Th" if dow[:thursday] str += "F" if dow[:friday] str += "Sa" if dow[:saturday] str end ## End daysOfWeek Helper/Accessors ## # TODO Return array of times representing the open and close times at a certain occurence def to_times(at = Time.now) raise NotImplementedError open = Time.now close = Time.now [open,close] end def to_xml(params) super(params.merge({:only => [:id, :place_id, :flags], :methods => [ :opensAt, :closesAt, :startDate, :endDate ]})) end ##### TODO DEPRECATED METHODS ##### def at @at end def at=(time) @opensAt = nil @closesAt = nil @at = time end # Returns a Time object representing the beginning of this OperatingTime def opensAt @opensAt ||= relativeTime.openTime(at) end def closesAt @closesAt ||= relativeTime.closeTime(at) end # Sets the beginning of this OperatingTime # Input: params = { :hour => 12, :minute => 45 } def opensAt=(time) if time.class == Time @opensAt = relativeTime.openTime = time else super end end # Sets the end of this OperatingTime def closesAt=(time) @closesAt = relativeTime.closeTime = time end def length closesAt - opensAt end # Returns a RelativeTime object representing this OperatingTime def relativeTime @relativeTime ||= RelativeTime.new(self, :opensAt, :length) end; protected :relativeTime # Backwards compatibility with old database schema # TODO GET RID OF THIS!!! def flags ( (override ? 1 : 0) << 7) | read_attribute(:daysOfWeek) end # FIXME Deprecated, use +override+ instead def special override end # Input: isSpecial = true/false # FIXME Deprecated, use +override=+ instead def special=(isSpecial) if isSpecial == true or isSpecial == "true" or isSpecial == 1 self.override = true elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 self.override = false end end end
michaelansel/dukenow
d4663269dd40fcb1346062e04d05030798117f73
OperatingTime model: Add stricter argument handling for override and daysOfWeek; Add appropriate specs
diff --git a/app/models/operating_time.rb b/app/models/operating_time.rb index 6fa84aa..9ff4933 100644 --- a/app/models/operating_time.rb +++ b/app/models/operating_time.rb @@ -1,170 +1,186 @@ class OperatingTime < ActiveRecord::Base belongs_to :place validates_presence_of :place_id validates_associated :place validate :end_after_start, :daysOfWeek_valid ## DaysOfWeek Constants ## SUNDAY = 0b00000001 MONDAY = 0b00000010 TUESDAY = 0b00000100 WEDNESDAY = 0b00001000 THURSDAY = 0b00010000 FRIDAY = 0b00100000 SATURDAY = 0b01000000 + ALL_DAYS = (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) ## Validations ## def end_after_start if endDate < startDate errors.add_to_base("End date cannot preceed start date") end end def daysOfWeek_valid daysOfWeek == daysOfWeek & (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) end ## End Validations ## # TODO Is this OperatingTime applicable at +time+ def valid_at(time=Time.now) raise NotImplementedError end def override read_attribute(:override) == 1 end def override=(mode) if mode == true or mode == "true" or mode == 1 write_attribute(:override, true) elsif mode == false or mode == "false" or mode == 0 write_attribute(:override, false) + else + raise ArgumentError, "Invalid override value; Accepts true/false, 1/0" + end + end + + def daysOfWeek=(newDow) + if newDow & ALL_DAYS == newDow + write_attribute(:daysOfWeek, newDow & ALL_DAYS) + else + # Invalid input + raise ArgumentError, "Not a valid value for daysOfWeek" end end ## daysOfWeek Helper/Accessors ## # Hash mapping day of week (Symbol) to valid(true)/invalid(false) def daysOfWeekHash { :sunday => (daysOfWeek & SUNDAY ) > 0, :monday => (daysOfWeek & MONDAY ) > 0, :tuesday => (daysOfWeek & TUESDAY ) > 0, :wednesday => (daysOfWeek & WEDNESDAY ) > 0, :thursday => (daysOfWeek & THURSDAY ) > 0, :friday => (daysOfWeek & FRIDAY ) > 0, :saturday => (daysOfWeek & SATURDAY ) > 0} end # Array beginning with Sunday of valid(true)/inactive(false) values def daysOfWeekArray dow = daysOfWeekHash [ dow[:sunday], dow[:monday], dow[:tuesday], dow[:wednesday], dow[:thursday], dow[:friday], dow[:saturday] ] end # Human-readable string of applicable days of week def daysOfWeekString dow = daysOfWeekHash str = "" str += "Su" if dow[:sunday] str += "M" if dow[:monday] str += "Tu" if dow[:tuesday] str += "W" if dow[:wednesday] str += "Th" if dow[:thursday] str += "F" if dow[:friday] str += "Sa" if dow[:saturday] str end ## End daysOfWeek Helper/Accessors ## # TODO Return array of times representing the open and close times at a certain occurence def to_times(at = Time.now) raise NotImplementedError open = Time.now close = Time.now [open,close] end def to_xml(params) super(params.merge({:only => [:id, :place_id, :flags], :methods => [ :opensAt, :closesAt, :startDate, :endDate ]})) end ##### TODO DEPRECATED METHODS ##### def at @at end def at=(time) @opensAt = nil @closesAt = nil @at = time end # Returns a Time object representing the beginning of this OperatingTime def opensAt @opensAt ||= relativeTime.openTime(at) end def closesAt @closesAt ||= relativeTime.closeTime(at) end # Sets the beginning of this OperatingTime # Input: params = { :hour => 12, :minute => 45 } def opensAt=(time) - @opensAt = relativeTime.openTime = time + if time.class == Time + @opensAt = relativeTime.openTime = time + else + super + end end # Sets the end of this OperatingTime def closesAt=(time) @closesAt = relativeTime.closeTime = time end def length closesAt - opensAt end # Returns a RelativeTime object representing this OperatingTime def relativeTime @relativeTime ||= RelativeTime.new(self, :opensAt, :length) end; protected :relativeTime # Backwards compatibility with old database schema # TODO GET RID OF THIS!!! def flags ( (override ? 1 : 0) << 7) | read_attribute(:daysOfWeek) end # FIXME Deprecated, use +override+ instead def special override end # Input: isSpecial = true/false # FIXME Deprecated, use +override=+ instead def special=(isSpecial) if isSpecial == true or isSpecial == "true" or isSpecial == 1 self.override = true elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 self.override = false end end end diff --git a/spec/models/operating_time_spec.rb b/spec/models/operating_time_spec.rb index febb22b..7650029 100644 --- a/spec/models/operating_time_spec.rb +++ b/spec/models/operating_time_spec.rb @@ -1,23 +1,115 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe OperatingTime do before(:each) do @place = mock_model(Place) @valid_attributes = { - :place_id => @place.id, - :startDate => Date.yesterday, - :endDate => Date.tomorrow + :place_id => @place.id, + :opensAt => (Time.now - 1.hours).to_i, + :length => 2.hours, + :daysOfWeek => OperatingTime::ALL_DAYS, + :startDate => Date.yesterday, + :endDate => Date.tomorrow, + :override => false } + @operating_time = OperatingTime.create!(@valid_attributes) end - it "should create a new instance given valid attributes" do + it "should create a new instance given all valid attributes" do OperatingTime.create!(@valid_attributes) end - # TODO: Add spec code - it "should not create a new instance without a valid start time" - it "should not create a new instance without a valid length" - it "should not create a new instance without a valid Place reference" - it "should not create a new instance without a valid start date" - it "should not create a new instance without a valid end date" + describe "missing required attributes" do + it "should not create a new instance without a valid start time" + it "should not create a new instance without a valid length" + it "should not create a new instance without a valid Place reference" + it "should not create a new instance without a valid start date" + it "should not create a new instance without a valid end date" + end + + describe "missing default-able attributes" do + it "should default daysOfWeek to 0" do + @valid_attributes.delete(:daysOfWeek) if @valid_attributes[:daysOfWeek] + OperatingTime.create!(@valid_attributes).daysOfWeek.should == 0 + end + + it "should default override to false" do + @valid_attributes.delete(:override) if @valid_attributes[:override] + OperatingTime.create!(@valid_attributes).override.should == false + end + end + + describe "given invalid attributes" do + def create + @operating_time = OperatingTime.create!(@valid_attributes) + end + +=begin + it "should create a new instance, but ignore an invalid override value" do + @valid_attributes[:override] = "invalid" + create + @operating_time.override.should == false # where false is the default value + + @valid_attributes[:override] = 10 + create + @operating_time.override.should == false # where false is the default value + end + + it "should create a new instance, but ignore an invalid daysOfWeek value" do + @valid_attributes[:daysOfWeek] = 1000 + create + @operating_time.daysOfWeek.should == 0 # where 0 is the default value + end +=end + + it "should not create a new instance with an invalid start time" + it "should not create a new instance with an invalid length" + it "should not create a new instance with an invalid Place reference" + it "should not create a new instance with an invalid start date" + it "should not create a new instance with an invalid end date" + end + + it "should enable override mode" do + @operating_time.should_receive(:write_attribute).with(:override, true).exactly(3).times + @operating_time.override = true + @operating_time.override = "true" + @operating_time.override = 1 + end + + it "should disable override mode" do + @operating_time.should_receive(:write_attribute).with(:override, false).exactly(3).times + @operating_time.override = false + @operating_time.override = "false" + @operating_time.override = 0 + end + + it "should complain about invalid override values, but not change the value" do + @operating_time.override = true + @operating_time.override.should == true + + #TODO Should nil be ignored or errored? + lambda { @operating_time.override = nil }.should raise_error(ArgumentError) + @operating_time.override.should == true + + lambda { @operating_time.override = "invalid" }.should raise_error(ArgumentError) + @operating_time.override.should == true + + lambda { @operating_time.override = false }.should_not raise_error + @operating_time.override.should == false + end + + it "should complain about invalid daysOfWeek values, but not change the value" do + @operating_time.daysOfWeek = OperatingTime::SUNDAY + @operating_time.daysOfWeek.should == OperatingTime::SUNDAY + + #TODO Should nil be ignored or errored? + lambda { @operating_time.daysOfWeek = nil }.should raise_error(ArgumentError) + @operating_time.daysOfWeek.should == OperatingTime::SUNDAY + + lambda { @operating_time.daysOfWeek = 200 }.should raise_error(ArgumentError) + @operating_time.daysOfWeek.should == OperatingTime::SUNDAY + + lambda { @operating_time.daysOfWeek= OperatingTime::MONDAY }.should_not raise_error + @operating_time.daysOfWeek.should == OperatingTime::MONDAY + end end
michaelansel/dukenow
6642ca3ef3ca949c1da9631678589380a5ffe974
OperatingTimes model: Add validations, Reimplement "override" and "daysOfWeek", Seperate all deprecated methods
diff --git a/app/models/operating_time.rb b/app/models/operating_time.rb index 4eb7d5e..6fa84aa 100644 --- a/app/models/operating_time.rb +++ b/app/models/operating_time.rb @@ -1,155 +1,170 @@ class OperatingTime < ActiveRecord::Base belongs_to :place validates_presence_of :place_id validates_associated :place + validate :end_after_start, :daysOfWeek_valid + + ## DaysOfWeek Constants ## + SUNDAY = 0b00000001 + MONDAY = 0b00000010 + TUESDAY = 0b00000100 + WEDNESDAY = 0b00001000 + THURSDAY = 0b00010000 + FRIDAY = 0b00100000 + SATURDAY = 0b01000000 + + ## Validations ## + def end_after_start + if endDate < startDate + errors.add_to_base("End date cannot preceed start date") + end + end - # Base flags - SUNDAY_FLAG = 0b00000000001 - MONDAY_FLAG = 0b00000000010 - TUESDAY_FLAG = 0b00000000100 - WEDNESDAY_FLAG = 0b00000001000 - THURSDAY_FLAG = 0b00000010000 - FRIDAY_FLAG = 0b00000100000 - SATURDAY_FLAG = 0b00001000000 - SPECIAL_FLAG = 0b00010000000 - DINE_IN_FLAG = 0b00100000000 - DELIVERY_FLAG = 0b01000000000 + def daysOfWeek_valid + daysOfWeek == daysOfWeek & (SUNDAY + MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY + SATURDAY) + end + ## End Validations ## + # TODO Is this OperatingTime applicable at +time+ + def valid_at(time=Time.now) + raise NotImplementedError + end - # Combinations - ALLDAYS_FLAG = 0b00001111111 - WEEKDAYS_FLAG = 0b00000111110 - WEEKENDS_FLAG = 0b00001000001 - ALL_FLAGS = 0b01111111111 - def initialize(params = nil) - super + def override + read_attribute(:override) == 1 + end + def override=(mode) + if mode == true or mode == "true" or mode == 1 + write_attribute(:override, true) + elsif mode == false or mode == "false" or mode == 0 + write_attribute(:override, false) + end + end + + + ## daysOfWeek Helper/Accessors ## - # Default values - self.flags = 0 unless self.flags - self.startDate = Time.now unless self.startDate - self.endDate = Time.now unless self.endDate - @at = Time.now + # Hash mapping day of week (Symbol) to valid(true)/invalid(false) + def daysOfWeekHash + { :sunday => (daysOfWeek & SUNDAY ) > 0, + :monday => (daysOfWeek & MONDAY ) > 0, + :tuesday => (daysOfWeek & TUESDAY ) > 0, + :wednesday => (daysOfWeek & WEDNESDAY ) > 0, + :thursday => (daysOfWeek & THURSDAY ) > 0, + :friday => (daysOfWeek & FRIDAY ) > 0, + :saturday => (daysOfWeek & SATURDAY ) > 0} end - # Backwards compatibility with old database schema - # TODO GET RID OF THIS!!! - def flags - (override << 7) | read_attribute(:daysOfWeek) + # Array beginning with Sunday of valid(true)/inactive(false) values + def daysOfWeekArray + dow = daysOfWeekHash + + [ dow[:sunday], + dow[:monday], + dow[:tuesday], + dow[:wednesday], + dow[:thursday], + dow[:friday], + dow[:saturday] + ] end - def length - closesAt - opensAt + # Human-readable string of applicable days of week + def daysOfWeekString + dow = daysOfWeekHash + str = "" + + str += "Su" if dow[:sunday] + str += "M" if dow[:monday] + str += "Tu" if dow[:tuesday] + str += "W" if dow[:wednesday] + str += "Th" if dow[:thursday] + str += "F" if dow[:friday] + str += "Sa" if dow[:saturday] + + str + end + + ## End daysOfWeek Helper/Accessors ## + + # TODO Return array of times representing the open and close times at a certain occurence + def to_times(at = Time.now) + raise NotImplementedError + open = Time.now + close = Time.now + [open,close] end + def to_xml(params) + super(params.merge({:only => [:id, :place_id, :flags], :methods => [ :opensAt, :closesAt, :startDate, :endDate ]})) + end + + + + + + +##### TODO DEPRECATED METHODS ##### def at @at end def at=(time) @opensAt = nil @closesAt = nil @at = time end - - def special - (self.flags & SPECIAL_FLAG) == SPECIAL_FLAG - end - # Input: isSpecial = true/false - def special=(isSpecial) - if isSpecial == true or isSpecial == "true" or isSpecial == 1 - self.flags = self.flags | SPECIAL_FLAG - elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 - self.flags = self.flags & ~SPECIAL_FLAG - end - end - - # Returns a Time object representing the beginning of this OperatingTime def opensAt @opensAt ||= relativeTime.openTime(at) end def closesAt @closesAt ||= relativeTime.closeTime(at) end - - - # Returns a RelativeTime object representing this OperatingTime - def relativeTime - @relativeTime ||= RelativeTime.new(self, :opensAt, :length) - end; protected :relativeTime - - # Sets the beginning of this OperatingTime # Input: params = { :hour => 12, :minute => 45 } def opensAt=(time) @opensAt = relativeTime.openTime = time end # Sets the end of this OperatingTime def closesAt=(time) @closesAt = relativeTime.closeTime = time end - # Hash mapping day of week (Symbol) to valid(true)/invalid(false) - def daysOfWeekHash - a=daysOfWeek - daysOfWeek = 127 if a.nil? - daysOfWeek = a - { :sunday => (daysOfWeek & 1) > 0, # Sunday - :monday => (daysOfWeek & 2) > 0, # Monday - :tuesday => (daysOfWeek & 4) > 0, # Tuesday - :wednesday => (daysOfWeek & 8) > 0, # Wednesday - :thursday => (daysOfWeek & 16) > 0, # Thursday - :friday => (daysOfWeek & 32) > 0, # Friday - :saturday => (daysOfWeek & 64) > 0} # Saturday + def length + closesAt - opensAt end - # Array beginning with Sunday of valid(true)/inactive(false) values - def daysOfWeekArray - a=daysOfWeek - daysOfWeek = 127 if a.nil? - daysOfWeek = a - - [ daysOfWeek & 1 > 0, # Sunday - daysOfWeek & 2 > 0, # Monday - daysOfWeek & 4 > 0, # Tuesday - daysOfWeek & 8 > 0, # Wednesday - daysOfWeek & 16 > 0, # Thursday - daysOfWeek & 32 > 0, # Friday - daysOfWeek & 64 > 0] # Saturday - end - - # Days of week valid (sum of flags) - def daysOfWeek - sum = 0 - 7.times do |i| - sum += ( (flags & ALLDAYS_FLAG) & (1 << i) ) - end + # Returns a RelativeTime object representing this OperatingTime + def relativeTime + @relativeTime ||= RelativeTime.new(self, :opensAt, :length) + end; protected :relativeTime - sum + # Backwards compatibility with old database schema + # TODO GET RID OF THIS!!! + def flags + ( (override ? 1 : 0) << 7) | read_attribute(:daysOfWeek) end - # Human-readable string of days of week valid - def daysOfWeekString - str = "" - - str += "Su" if flags & SUNDAY_FLAG > 0 - str += "M" if flags & MONDAY_FLAG > 0 - str += "Tu" if flags & TUESDAY_FLAG > 0 - str += "W" if flags & WEDNESDAY_FLAG > 0 - str += "Th" if flags & THURSDAY_FLAG > 0 - str += "F" if flags & FRIDAY_FLAG > 0 - str += "Sa" if flags & SATURDAY_FLAG > 0 - - str + # FIXME Deprecated, use +override+ instead + def special + override end - - def to_xml(params) - super(params.merge({:only => [:id, :place_id, :flags], :methods => [ :opensAt, :closesAt, :startDate, :endDate ]})) + # Input: isSpecial = true/false + # FIXME Deprecated, use +override=+ instead + def special=(isSpecial) + if isSpecial == true or isSpecial == "true" or isSpecial == 1 + self.override = true + elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 + self.override = false + end end + + end diff --git a/spec/models/operating_time_spec.rb b/spec/models/operating_time_spec.rb index fa0fed0..febb22b 100644 --- a/spec/models/operating_time_spec.rb +++ b/spec/models/operating_time_spec.rb @@ -1,21 +1,23 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe OperatingTime do before(:each) do @place = mock_model(Place) @valid_attributes = { - :place_id => @place.id + :place_id => @place.id, + :startDate => Date.yesterday, + :endDate => Date.tomorrow } end it "should create a new instance given valid attributes" do OperatingTime.create!(@valid_attributes) end # TODO: Add spec code it "should not create a new instance without a valid start time" it "should not create a new instance without a valid length" it "should not create a new instance without a valid Place reference" it "should not create a new instance without a valid start date" it "should not create a new instance without a valid end date" end
michaelansel/dukenow
23b77654d532f2c59da1210e456f46c1783232a3
Renamed OperatingTimes column "days_of_week" to "daysOfWeek" and updated model to make specs pass
diff --git a/app/models/operating_time.rb b/app/models/operating_time.rb index 4cc67aa..4eb7d5e 100644 --- a/app/models/operating_time.rb +++ b/app/models/operating_time.rb @@ -1,155 +1,155 @@ class OperatingTime < ActiveRecord::Base belongs_to :place validates_presence_of :place_id validates_associated :place # Base flags SUNDAY_FLAG = 0b00000000001 MONDAY_FLAG = 0b00000000010 TUESDAY_FLAG = 0b00000000100 WEDNESDAY_FLAG = 0b00000001000 THURSDAY_FLAG = 0b00000010000 FRIDAY_FLAG = 0b00000100000 SATURDAY_FLAG = 0b00001000000 SPECIAL_FLAG = 0b00010000000 DINE_IN_FLAG = 0b00100000000 DELIVERY_FLAG = 0b01000000000 # Combinations ALLDAYS_FLAG = 0b00001111111 WEEKDAYS_FLAG = 0b00000111110 WEEKENDS_FLAG = 0b00001000001 ALL_FLAGS = 0b01111111111 def initialize(params = nil) super # Default values self.flags = 0 unless self.flags self.startDate = Time.now unless self.startDate self.endDate = Time.now unless self.endDate @at = Time.now end # Backwards compatibility with old database schema # TODO GET RID OF THIS!!! def flags - (override << 7) | days_of_week + (override << 7) | read_attribute(:daysOfWeek) end def length closesAt - opensAt end def at @at end def at=(time) @opensAt = nil @closesAt = nil @at = time end def special (self.flags & SPECIAL_FLAG) == SPECIAL_FLAG end # Input: isSpecial = true/false def special=(isSpecial) if isSpecial == true or isSpecial == "true" or isSpecial == 1 self.flags = self.flags | SPECIAL_FLAG elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 self.flags = self.flags & ~SPECIAL_FLAG end end # Returns a Time object representing the beginning of this OperatingTime def opensAt @opensAt ||= relativeTime.openTime(at) end def closesAt @closesAt ||= relativeTime.closeTime(at) end # Returns a RelativeTime object representing this OperatingTime def relativeTime @relativeTime ||= RelativeTime.new(self, :opensAt, :length) end; protected :relativeTime # Sets the beginning of this OperatingTime # Input: params = { :hour => 12, :minute => 45 } def opensAt=(time) @opensAt = relativeTime.openTime = time end # Sets the end of this OperatingTime def closesAt=(time) @closesAt = relativeTime.closeTime = time end # Hash mapping day of week (Symbol) to valid(true)/invalid(false) def daysOfWeekHash a=daysOfWeek daysOfWeek = 127 if a.nil? daysOfWeek = a { :sunday => (daysOfWeek & 1) > 0, # Sunday :monday => (daysOfWeek & 2) > 0, # Monday :tuesday => (daysOfWeek & 4) > 0, # Tuesday :wednesday => (daysOfWeek & 8) > 0, # Wednesday :thursday => (daysOfWeek & 16) > 0, # Thursday :friday => (daysOfWeek & 32) > 0, # Friday :saturday => (daysOfWeek & 64) > 0} # Saturday end # Array beginning with Sunday of valid(true)/inactive(false) values def daysOfWeekArray a=daysOfWeek daysOfWeek = 127 if a.nil? daysOfWeek = a [ daysOfWeek & 1 > 0, # Sunday daysOfWeek & 2 > 0, # Monday daysOfWeek & 4 > 0, # Tuesday daysOfWeek & 8 > 0, # Wednesday daysOfWeek & 16 > 0, # Thursday daysOfWeek & 32 > 0, # Friday daysOfWeek & 64 > 0] # Saturday end # Days of week valid (sum of flags) def daysOfWeek sum = 0 7.times do |i| sum += ( (flags & ALLDAYS_FLAG) & (1 << i) ) end sum end # Human-readable string of days of week valid def daysOfWeekString str = "" str += "Su" if flags & SUNDAY_FLAG > 0 str += "M" if flags & MONDAY_FLAG > 0 str += "Tu" if flags & TUESDAY_FLAG > 0 str += "W" if flags & WEDNESDAY_FLAG > 0 str += "Th" if flags & THURSDAY_FLAG > 0 str += "F" if flags & FRIDAY_FLAG > 0 str += "Sa" if flags & SATURDAY_FLAG > 0 str end def to_xml(params) super(params.merge({:only => [:id, :place_id, :flags], :methods => [ :opensAt, :closesAt, :startDate, :endDate ]})) end end diff --git a/db/migrate/20090629201611_days_of_week_to_days_of_week.rb b/db/migrate/20090629201611_days_of_week_to_days_of_week.rb new file mode 100644 index 0000000..0d53b5c --- /dev/null +++ b/db/migrate/20090629201611_days_of_week_to_days_of_week.rb @@ -0,0 +1,9 @@ +class DaysOfWeekToDaysOfWeek < ActiveRecord::Migration + def self.up + rename_column "operating_times", "days_of_week", "daysOfWeek" + end + + def self.down + rename_column "operating_times", "daysOfWeek", "days_of_week" + end +end diff --git a/db/schema.rb b/db/schema.rb index 3d28291..3967d72 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,80 +1,80 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20090626212057) do +ActiveRecord::Schema.define(:version => 20090629201611) do create_table "eateries", :force => true do |t| t.string "name" t.string "location" t.string "phone" t.datetime "created_at" t.datetime "updated_at" end create_table "operating_times", :force => true do |t| t.integer "place_id" t.integer "opensAt" t.integer "length" t.text "details" t.date "startDate" t.date "endDate" t.datetime "created_at" t.datetime "updated_at" - t.integer "override", :default => 0, :null => false - t.integer "days_of_week", :default => 0, :null => false + t.integer "override", :default => 0, :null => false + t.integer "daysOfWeek", :default => 0, :null => false end create_table "places", :force => true do |t| t.string "name" t.string "location" t.string "phone" t.datetime "created_at" t.datetime "updated_at" end create_table "regular_operating_times", :force => true do |t| t.integer "eatery_id" t.integer "opensAt" t.integer "closesAt" t.integer "daysOfWeek" t.datetime "created_at" t.datetime "updated_at" end create_table "special_operating_times", :force => true do |t| t.integer "eatery_id" t.integer "opensAt" t.integer "closesAt" t.integer "daysOfWeek" t.date "start" t.date "end" t.datetime "created_at" t.datetime "updated_at" end create_table "taggings", :force => true do |t| t.integer "tag_id" t.integer "taggable_id" t.integer "tagger_id" t.string "tagger_type" t.string "taggable_type" t.string "context" t.datetime "created_at" end add_index "taggings", ["tag_id"], :name => "index_taggings_on_tag_id" add_index "taggings", ["taggable_id", "taggable_type", "context"], :name => "index_taggings_on_taggable_id_and_taggable_type_and_context" create_table "tags", :force => true do |t| t.string "name" end end
michaelansel/dukenow
76b37ff3adc18e814bf02475b333df7ed338fd8a
Add minor fixes so specs will pass following OperatingTimes migration (flags => override,days_of_week)
diff --git a/TODO b/TODO index da82102..9503715 100644 --- a/TODO +++ b/TODO @@ -1,112 +1,112 @@ vim:set syntax=todo: Database Places -- has_one :dining_extension \- name (string) -- location (lat/long) -- ?GeoKit Plugin? \- phone_number (string) DiningExtensions -- acts_as_taggable_on :dining_tags ## needs work -- **delivery/eat-in** ## operating_time details/tag -- more_info_url -- owner_operator -- payment_methods -- logo_url OperatingTimes \- place_id \- start (midnight offset in seconds) \- length (in seconds) \- startDate (Date) \- endDate (Date) \- details (String) -- override -- days_of_week (bit-wise AND of wday's) OperatingTimesTags -- name OperatingTimesTaggings (clone auto-generated) !- clone Taggings schema -- operating_time_id -- operating_times_tag_id TimePeriods -- name (String) -- startDate (Date) -- endDate (Date) API Versioning -- Subdirectories -- rake task for adding new versions and deprecating old versions Places OperatingTimes -- Array of DateTime objects for the next N hours/days/etc -- Bulk import Excel spreadsheet -- What qualifies as a Tag versus an Attribute? Milestones OperatingTimes StartLengthSchema - -- Migration + \- Migration Feature-parity -- schedule(from,to) -- daySchedule(date) -- currentSchedule(at) -- open?(at) -- Full unit tests + validation -- Prevent overlapping time periods without "override" flag Extend API -- Generate Time objects -- Add versioning DiningExtensions -- Migration -- Full unit tests + validation DiningExtensions Tags -- Migrations -- Full unit tests + validation OperatingTimes Tags -- Migration -- Full unit tests + validation -- Extend OperatingTimes.find to filter by tags -- Extend Places.open? to test delivery/dine-in tags TimePeriods -- Migration -- Full unit tests + validation -- Create integration -- View Integration API Versioning rake Tasks -- Clone for new version and increment version number -- Deprecate old version -- Hosting for web app/file server? -- Can I get help with the UI design, or will DukeMobile only be focusing on the iPhone side? -- Set "expiration" date; Send reminder emails; Show _nothing_ rather than inaccurate info Database Adjust schema to be more flexible !- Late nights: seamless midnight rollover -- Start,End => Start,Length (then, convert to real "Time"s based on @at) -- iCal RRULE (string) and parse with RiCal (pre-release) \- Add "midnight" method to Date, Time -- (?) Multiple "special"/override schedules (e.g. every weekday during Spring Break except Friday) -- Special: "normally open, but closed all day today" -- Semester-style schedules -- List of important dates (likely to be scheduling boundaries) Interface Index (Main Page) -- Hide nowIndicator after midnight instead of wrapping around -- JavaScript Tag Filtering -- Status @ DateTime Data Entry -- Bulk import (CSV, XML) -- Duke Dining PDF parser (?) -- Not worth the effort to get consistent data Web Form -- Text entry of times (drop downs, input fields) -- Quickly add/edit all times for a location -- Graphic schedule of current settings -- Show "normal" schedule in background if making an exception -- Drag/Drop/Resize-able blocks on schedule diff --git a/app/models/operating_time.rb b/app/models/operating_time.rb index d0c89bc..4cc67aa 100644 --- a/app/models/operating_time.rb +++ b/app/models/operating_time.rb @@ -1,149 +1,155 @@ class OperatingTime < ActiveRecord::Base belongs_to :place validates_presence_of :place_id validates_associated :place # Base flags SUNDAY_FLAG = 0b00000000001 MONDAY_FLAG = 0b00000000010 TUESDAY_FLAG = 0b00000000100 WEDNESDAY_FLAG = 0b00000001000 THURSDAY_FLAG = 0b00000010000 FRIDAY_FLAG = 0b00000100000 SATURDAY_FLAG = 0b00001000000 SPECIAL_FLAG = 0b00010000000 DINE_IN_FLAG = 0b00100000000 DELIVERY_FLAG = 0b01000000000 # Combinations ALLDAYS_FLAG = 0b00001111111 WEEKDAYS_FLAG = 0b00000111110 WEEKENDS_FLAG = 0b00001000001 ALL_FLAGS = 0b01111111111 def initialize(params = nil) super # Default values self.flags = 0 unless self.flags self.startDate = Time.now unless self.startDate self.endDate = Time.now unless self.endDate @at = Time.now end + # Backwards compatibility with old database schema + # TODO GET RID OF THIS!!! + def flags + (override << 7) | days_of_week + end + def length closesAt - opensAt end def at @at end def at=(time) @opensAt = nil @closesAt = nil @at = time end def special (self.flags & SPECIAL_FLAG) == SPECIAL_FLAG end # Input: isSpecial = true/false def special=(isSpecial) if isSpecial == true or isSpecial == "true" or isSpecial == 1 self.flags = self.flags | SPECIAL_FLAG elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 self.flags = self.flags & ~SPECIAL_FLAG end end # Returns a Time object representing the beginning of this OperatingTime def opensAt @opensAt ||= relativeTime.openTime(at) end def closesAt @closesAt ||= relativeTime.closeTime(at) end # Returns a RelativeTime object representing this OperatingTime def relativeTime @relativeTime ||= RelativeTime.new(self, :opensAt, :length) end; protected :relativeTime # Sets the beginning of this OperatingTime # Input: params = { :hour => 12, :minute => 45 } def opensAt=(time) @opensAt = relativeTime.openTime = time end # Sets the end of this OperatingTime def closesAt=(time) @closesAt = relativeTime.closeTime = time end # Hash mapping day of week (Symbol) to valid(true)/invalid(false) def daysOfWeekHash a=daysOfWeek daysOfWeek = 127 if a.nil? daysOfWeek = a { :sunday => (daysOfWeek & 1) > 0, # Sunday :monday => (daysOfWeek & 2) > 0, # Monday :tuesday => (daysOfWeek & 4) > 0, # Tuesday :wednesday => (daysOfWeek & 8) > 0, # Wednesday :thursday => (daysOfWeek & 16) > 0, # Thursday :friday => (daysOfWeek & 32) > 0, # Friday :saturday => (daysOfWeek & 64) > 0} # Saturday end # Array beginning with Sunday of valid(true)/inactive(false) values def daysOfWeekArray a=daysOfWeek daysOfWeek = 127 if a.nil? daysOfWeek = a [ daysOfWeek & 1 > 0, # Sunday daysOfWeek & 2 > 0, # Monday daysOfWeek & 4 > 0, # Tuesday daysOfWeek & 8 > 0, # Wednesday daysOfWeek & 16 > 0, # Thursday daysOfWeek & 32 > 0, # Friday daysOfWeek & 64 > 0] # Saturday end # Days of week valid (sum of flags) def daysOfWeek sum = 0 7.times do |i| sum += ( (flags & ALLDAYS_FLAG) & (1 << i) ) end sum end # Human-readable string of days of week valid def daysOfWeekString str = "" str += "Su" if flags & SUNDAY_FLAG > 0 str += "M" if flags & MONDAY_FLAG > 0 str += "Tu" if flags & TUESDAY_FLAG > 0 str += "W" if flags & WEDNESDAY_FLAG > 0 str += "Th" if flags & THURSDAY_FLAG > 0 str += "F" if flags & FRIDAY_FLAG > 0 str += "Sa" if flags & SATURDAY_FLAG > 0 str end def to_xml(params) super(params.merge({:only => [:id, :place_id, :flags], :methods => [ :opensAt, :closesAt, :startDate, :endDate ]})) end end diff --git a/app/models/place.rb b/app/models/place.rb index 96876f9..00d480d 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,119 +1,119 @@ class Place < ActiveRecord::Base has_many :operating_times acts_as_taggable_on :tags validates_presence_of :name def special_operating_times - OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0", id], :order => "startDate ASC, opensAt ASC" ) + OperatingTime.find( :all, :conditions => ["place_id = ? and override != 0", id], :order => "startDate ASC, opensAt ASC" ) end def regular_operating_times - OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0", id], :order => "startDate ASC, opensAt ASC" ) + OperatingTime.find( :all, :conditions => ["place_id = ? and override == 0", id], :order => "startDate ASC, opensAt ASC" ) end # Returns an array of OperatingTimes def schedule(startAt,endAt) # TODO Returns the schedule for a specified time window # TODO Handle events starting within the range but ending outside of it? regular_times = [] regular_operating_times.each do |ot| ot.startDate ||= startAt.to_date ot.endDate ||= endAt.to_date if ot.startDate >= startAt.to_date-1 and ot.endDate <= endAt.to_date+1 ot.at = nil # Yesterday ot.at = (startAt.to_date - 1).midnight if ot.closesAt >= ot.at and ot.flags & 1<<ot.at.wday > 0 t = ot.dup t.opensAt = startAt regular_times << t t=nil end # Today ot.at = startAt.to_date.midnight regular_times << ot.dup if ot.opensAt >= startAt and ot.opensAt < endAt and ot.flags & 1<<ot.at.wday > 0 # Tomorrow ot.at = endAt == endAt.midnight ? endAt : endAt.midnight + 1.days if ot.opensAt < endAt and ot.flags & 1<<ot.at.wday > 0 t = ot.dup t.closesAt = endAt regular_times << t t=nil end end end special_times = special_operating_times.select do |ot| ot.at = startAt ot.startDate ||= startAt.to_date ot.endDate ||= endAt.to_date (ot.startDate <= startAt.to_date and ot.endDate >= endAt.to_date) and ((ot.opensAt >= startAt and ot.opensAt <= endAt) or (ot.closesAt >= startAt and ot.closesAt <= endAt)) end # TODO Handle combinations (i.e. part special, part regular) special_times == [] ? regular_times : special_times regular_times end def daySchedule(at = Date.today) at = at.to_date if at.class == Time or at.class == DateTime schedule = schedule(at.midnight,(at+1).midnight) #schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } #schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end schedule.sort{|a,b|a.opensAt <=> b.opensAt} =end end def currentSchedule(at = Time.now) current_schedule = nil daySchedule(at).each do |optime| if optime.opensAt <= at and optime.closesAt >= at #RAILS_DEFAULT_LOGGER.debug "Opens At: #{optime.opensAt.time(at).to_s}" #RAILS_DEFAULT_LOGGER.debug "Closes At: #{optime.closesAt.time(at).to_s}" current_schedule = optime end end current_schedule end def open?(at = Time.now) a = currentSchedule(at) return a ? true : false end # Alias for <tt>open?</tt> def open(at = Time.now); open? at ; end def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end def to_xml(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end end
michaelansel/dukenow
f25ed21a28a5bed64c54a2a83c0b5a44ea89a2ee
Added migration for new OperatingTimes schema (override and days_of_week columns instead of flags)
diff --git a/db/migrate/20090626212057_override_and_days_of_week_flags.rb b/db/migrate/20090626212057_override_and_days_of_week_flags.rb new file mode 100644 index 0000000..5e40402 --- /dev/null +++ b/db/migrate/20090626212057_override_and_days_of_week_flags.rb @@ -0,0 +1,28 @@ +class OverrideAndDaysOfWeekFlags < ActiveRecord::Migration + def self.up + add_column "operating_times", "override", :integer, :null => false, :default => 0 + add_column "operating_times", "days_of_week", :integer, :null => false, :default => 0 + + OperatingTime.reset_column_information + OperatingTime.find(:all).each do |ot| + ot.write_attribute(:override, ot.read_attribute(:flags) & 128) # 128 == Special Flag + ot.write_attribute(:days_of_week, ot.read_attribute(:flags) & (1+2+4+8+16+32+64) ) # Sum == Flag for each day of the week + ot.save + end + + remove_column("operating_times", "flags") + end + + def self.down + add_column("operating_times","flags",:integer, :null => false, :default => 0) + + OperatingTime.reset_column_information + OperatingTime.find(:all).each do |ot| + ot.write_attribute(:flags, (ot.read_attribute(:override) << 7) | ot.read_attribute(:days_of_week) ) + ot.save + end + + remove_column("operating_times", "override") + remove_column("operating_times", "days_of_week") + end +end diff --git a/db/schema.rb b/db/schema.rb index be3ef1f..3d28291 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,51 +1,80 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20090616040958) do +ActiveRecord::Schema.define(:version => 20090626212057) do + + create_table "eateries", :force => true do |t| + t.string "name" + t.string "location" + t.string "phone" + t.datetime "created_at" + t.datetime "updated_at" + end create_table "operating_times", :force => true do |t| t.integer "place_id" t.integer "opensAt" t.integer "length" t.text "details" - t.integer "flags" t.date "startDate" t.date "endDate" t.datetime "created_at" t.datetime "updated_at" + t.integer "override", :default => 0, :null => false + t.integer "days_of_week", :default => 0, :null => false end create_table "places", :force => true do |t| t.string "name" t.string "location" t.string "phone" t.datetime "created_at" t.datetime "updated_at" end + create_table "regular_operating_times", :force => true do |t| + t.integer "eatery_id" + t.integer "opensAt" + t.integer "closesAt" + t.integer "daysOfWeek" + t.datetime "created_at" + t.datetime "updated_at" + end + + create_table "special_operating_times", :force => true do |t| + t.integer "eatery_id" + t.integer "opensAt" + t.integer "closesAt" + t.integer "daysOfWeek" + t.date "start" + t.date "end" + t.datetime "created_at" + t.datetime "updated_at" + end + create_table "taggings", :force => true do |t| t.integer "tag_id" t.integer "taggable_id" t.integer "tagger_id" t.string "tagger_type" t.string "taggable_type" t.string "context" t.datetime "created_at" end add_index "taggings", ["tag_id"], :name => "index_taggings_on_tag_id" add_index "taggings", ["taggable_id", "taggable_type", "context"], :name => "index_taggings_on_taggable_id_and_taggable_type_and_context" create_table "tags", :force => true do |t| t.string "name" end end
michaelansel/dukenow
1f6f7c42cd7bd5887862695c3c11801f74fc6b4e
Added spec outline for Places model
diff --git a/spec/models/place_spec.rb b/spec/models/place_spec.rb index 211457f..0fbb4fd 100644 --- a/spec/models/place_spec.rb +++ b/spec/models/place_spec.rb @@ -1,45 +1,71 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') # TODO Create mocks for OperatingTime so we can test the scheduling methods describe "a Place with OperatingTimes", :shared => true do it "should have a valid daily schedule" it "should have a valid current schedule" it "should have regular OperatingTimes" it "should have special OperatingTimes" end describe Place do before(:each) do @valid_attributes = { :name => 'Test Place', :location => 'Somewhere', :phone => '(919) 555-1212' } end it "should create a new instance given valid attributes" do Place.create!(@valid_attributes) end it "should not create a new instance without a name" do @valid_attributes.delete(:name) lambda { Place.create!(@valid_attributes) }.should raise_error end describe "that is currently open" do it_should_behave_like "a Place with OperatingTimes" it "should be open" end - describe "that is closed for the day" - describe "that is not open at all today" + describe "that is closed, but opens later today" do + it_should_behave_like "a Place with OperatingTimes" + + it "should be closed" + it "should have a schedule for later today" + end + + describe "that is closed for the day" do + it_should_behave_like "a Place with OperatingTimes" + + it "should be closed" + end + describe "that is not open at all today" do + it_should_behave_like "a Place with OperatingTimes" + + it "should be closed" + it "should not have a schedule for the remainder of today" + end - describe "that is open past midnight today" - describe "that was open past midnight yesterday" + describe "that is open past midnight today" do + it_should_behave_like "a Place with OperatingTimes" + end + describe "that was open past midnight yesterday" do + it_should_behave_like "a Place with OperatingTimes" + end ###### Special Schedules ###### - describe "that is normally open, but closed all day today" - describe "that has special (extended) hours" - describe "that has special (shortened) hours" + describe "that is normally open, but closed all day today" do + it_should_behave_like "a Place with OperatingTimes" + end + describe "that has special (extended) hours" do + it_should_behave_like "a Place with OperatingTimes" + end + describe "that has special (shortened) hours" do + it_should_behave_like "a Place with OperatingTimes" + end end
michaelansel/dukenow
faa047308e95340ce69db18175187d0ff4494fc6
Add spec outlines for schedules and OperatingTimes; Temporarily disable some known-bad view specs until model logic complete
diff --git a/spec/models/operating_time_spec.rb b/spec/models/operating_time_spec.rb index 62ca71d..fa0fed0 100644 --- a/spec/models/operating_time_spec.rb +++ b/spec/models/operating_time_spec.rb @@ -1,14 +1,21 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe OperatingTime do before(:each) do @place = mock_model(Place) @valid_attributes = { :place_id => @place.id } end it "should create a new instance given valid attributes" do OperatingTime.create!(@valid_attributes) end + + # TODO: Add spec code + it "should not create a new instance without a valid start time" + it "should not create a new instance without a valid length" + it "should not create a new instance without a valid Place reference" + it "should not create a new instance without a valid start date" + it "should not create a new instance without a valid end date" end diff --git a/spec/models/place_spec.rb b/spec/models/place_spec.rb index 6819a7d..211457f 100644 --- a/spec/models/place_spec.rb +++ b/spec/models/place_spec.rb @@ -1,22 +1,45 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') +# TODO Create mocks for OperatingTime so we can test the scheduling methods +describe "a Place with OperatingTimes", :shared => true do + it "should have a valid daily schedule" + it "should have a valid current schedule" + it "should have regular OperatingTimes" + it "should have special OperatingTimes" +end + describe Place do before(:each) do @valid_attributes = { :name => 'Test Place', :location => 'Somewhere', :phone => '(919) 555-1212' } end it "should create a new instance given valid attributes" do Place.create!(@valid_attributes) end it "should not create a new instance without a name" do @valid_attributes.delete(:name) lambda { Place.create!(@valid_attributes) }.should raise_error end - # TODO Create mocks for OperatingTime so we can test the scheduling methods + describe "that is currently open" do + it_should_behave_like "a Place with OperatingTimes" + + it "should be open" + end + + describe "that is closed for the day" + describe "that is not open at all today" + + describe "that is open past midnight today" + describe "that was open past midnight yesterday" + +###### Special Schedules ###### + describe "that is normally open, but closed all day today" + describe "that has special (extended) hours" + describe "that has special (shortened) hours" end diff --git a/spec/views/operating_times/edit.html.erb_spec.rb b/spec/views/operating_times/edit.html.erb_spec.rb index 58fc10a..ed83008 100644 --- a/spec/views/operating_times/edit.html.erb_spec.rb +++ b/spec/views/operating_times/edit.html.erb_spec.rb @@ -1,21 +1,22 @@ require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe "/operating_times/edit.html.erb" do include OperatingTimesHelper before(:each) do assigns[:operating_time] = @operating_time = stub_model(OperatingTime, :new_record? => false ) assigns[:places] = @places = [stub_model(Place),stub_model(Place)] end it "renders the edit operating_time form" do + pending('Fix libRelativeTime') render response.should have_tag("form[action=#{operating_time_path(@operating_time)}][method=post]") do end end end diff --git a/spec/views/operating_times/index.html.erb_spec.rb b/spec/views/operating_times/index.html.erb_spec.rb index f2da7ff..a12aee0 100644 --- a/spec/views/operating_times/index.html.erb_spec.rb +++ b/spec/views/operating_times/index.html.erb_spec.rb @@ -1,20 +1,21 @@ require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe "/operating_times/index.html.erb" do include OperatingTimesHelper before(:each) do @operating_times = [ stub_model(OperatingTime), stub_model(OperatingTime) ] @operating_times[0].place = stub_model(Place) @operating_times[1].place = stub_model(Place) assigns[:operating_times] = @operating_times end it "renders a list of operating_times" do + pending('Fix libRelativeTime') render end end diff --git a/spec/views/operating_times/new.html.erb_spec.rb b/spec/views/operating_times/new.html.erb_spec.rb index 76b2375..7db35ab 100644 --- a/spec/views/operating_times/new.html.erb_spec.rb +++ b/spec/views/operating_times/new.html.erb_spec.rb @@ -1,21 +1,22 @@ require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe "/operating_times/new.html.erb" do include OperatingTimesHelper before(:each) do assigns[:operating_time] = stub_model(OperatingTime, :new_record? => true ) assigns[:places] = @places = [stub_model(Place),stub_model(Place)] end it "renders new operating_time form" do + pending('Fix libRelativeTime') render response.should have_tag("form[action=?][method=post]", operating_times_path) do end end end diff --git a/spec/views/operating_times/show.html.erb_spec.rb b/spec/views/operating_times/show.html.erb_spec.rb index a52c3cd..0c73606 100644 --- a/spec/views/operating_times/show.html.erb_spec.rb +++ b/spec/views/operating_times/show.html.erb_spec.rb @@ -1,18 +1,16 @@ require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe "/operating_times/show.html.erb" do include OperatingTimesHelper before(:each) do assigns[:operating_time] = @operating_time = stub_model(OperatingTime) - assigns[:place] = @place = stub_model(Place) @operating_time.place = @place - - assigns[:at] = @at = Date.today end it "renders attributes in <p>" do + pending('Fix libRelativeTime') render end end
michaelansel/dukenow
a977700168d4892d76c1447b5b84dc58dc226c08
Continue to rework OperatingTimes to be completely Time based and handle midnight rollovers gracefully
diff --git a/app/models/operating_time.rb b/app/models/operating_time.rb index 54d3ea2..d0c89bc 100644 --- a/app/models/operating_time.rb +++ b/app/models/operating_time.rb @@ -1,153 +1,149 @@ class OperatingTime < ActiveRecord::Base belongs_to :place validates_presence_of :place_id validates_associated :place # Base flags SUNDAY_FLAG = 0b00000000001 MONDAY_FLAG = 0b00000000010 TUESDAY_FLAG = 0b00000000100 WEDNESDAY_FLAG = 0b00000001000 THURSDAY_FLAG = 0b00000010000 FRIDAY_FLAG = 0b00000100000 SATURDAY_FLAG = 0b00001000000 SPECIAL_FLAG = 0b00010000000 DINE_IN_FLAG = 0b00100000000 DELIVERY_FLAG = 0b01000000000 # Combinations ALLDAYS_FLAG = 0b00001111111 WEEKDAYS_FLAG = 0b00000111110 WEEKENDS_FLAG = 0b00001000001 ALL_FLAGS = 0b01111111111 def initialize(params = nil) super # Default values self.flags = 0 unless self.flags self.startDate = Time.now unless self.startDate self.endDate = Time.now unless self.endDate @at = Time.now end def length closesAt - opensAt end def at - @at ||= Time.now + @at end def at=(time) + @opensAt = nil + @closesAt = nil @at = time end def special (self.flags & SPECIAL_FLAG) == SPECIAL_FLAG end # Input: isSpecial = true/false def special=(isSpecial) if isSpecial == true or isSpecial == "true" or isSpecial == 1 self.flags = self.flags | SPECIAL_FLAG elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 self.flags = self.flags & ~SPECIAL_FLAG end end # Returns a Time object representing the beginning of this OperatingTime def opensAt - relativeOpensAt.time(at) + @opensAt ||= relativeTime.openTime(at) end - # Returns a RelativeTime object representing the beginning of this OperatingTime - def relativeOpensAt - @relativeOpensAt ||= RelativeTime.new(self,:opensAt) if @relativeOpensAt.nil? - @relativeOpensAt - end; protected :relativeOpensAt - # Sets the beginning of this OperatingTime - # Input: params = { :hour => 12, :minute => 45 } - def opensAt=(params = {}) - params[:hour] = 0 if params[:hour].nil? - params[:minute] = 0 if params[:minute].nil? - relativeOpensAt.offset = params[:hour].to_i.hours + params[:minute].to_i.minutes + def closesAt + @closesAt ||= relativeTime.closeTime(at) end - # Returns a Time object representing the end of this OperatingTime - def closesAt - relativeClosesAt.time(at) + + # Returns a RelativeTime object representing this OperatingTime + def relativeTime + @relativeTime ||= RelativeTime.new(self, :opensAt, :length) + end; protected :relativeTime + + + # Sets the beginning of this OperatingTime + # Input: params = { :hour => 12, :minute => 45 } + def opensAt=(time) + @opensAt = relativeTime.openTime = time end - # Returns a RelativeTime object representing the beginning of this OperatingTime - def relativeClosesAt - @relativeClosesAt ||= RelativeTime.new(self,:closesAt) if @relativeClosesAt.nil? - @relativeClosesAt - end; protected :relativeClosesAt + # Sets the end of this OperatingTime - # Input: params = { :hour => 12, :minute => 45 } - def closesAt=(params = {}) - relativeClosesAt.offset = params[:hour].to_i.hours + params[:minute].to_i.minutes + def closesAt=(time) + @closesAt = relativeTime.closeTime = time end # Hash mapping day of week (Symbol) to valid(true)/invalid(false) def daysOfWeekHash a=daysOfWeek daysOfWeek = 127 if a.nil? daysOfWeek = a { :sunday => (daysOfWeek & 1) > 0, # Sunday :monday => (daysOfWeek & 2) > 0, # Monday :tuesday => (daysOfWeek & 4) > 0, # Tuesday :wednesday => (daysOfWeek & 8) > 0, # Wednesday :thursday => (daysOfWeek & 16) > 0, # Thursday :friday => (daysOfWeek & 32) > 0, # Friday :saturday => (daysOfWeek & 64) > 0} # Saturday end # Array beginning with Sunday of valid(true)/inactive(false) values def daysOfWeekArray a=daysOfWeek daysOfWeek = 127 if a.nil? daysOfWeek = a [ daysOfWeek & 1 > 0, # Sunday daysOfWeek & 2 > 0, # Monday daysOfWeek & 4 > 0, # Tuesday daysOfWeek & 8 > 0, # Wednesday daysOfWeek & 16 > 0, # Thursday daysOfWeek & 32 > 0, # Friday daysOfWeek & 64 > 0] # Saturday end # Days of week valid (sum of flags) def daysOfWeek sum = 0 7.times do |i| sum += ( (flags & ALLDAYS_FLAG) & (1 << i) ) end sum end # Human-readable string of days of week valid def daysOfWeekString str = "" str += "Su" if flags & SUNDAY_FLAG > 0 str += "M" if flags & MONDAY_FLAG > 0 str += "Tu" if flags & TUESDAY_FLAG > 0 str += "W" if flags & WEDNESDAY_FLAG > 0 str += "Th" if flags & THURSDAY_FLAG > 0 str += "F" if flags & FRIDAY_FLAG > 0 str += "Sa" if flags & SATURDAY_FLAG > 0 str end def to_xml(params) super(params.merge({:only => [:id, :place_id, :flags], :methods => [ :opensAt, :closesAt, :startDate, :endDate ]})) end end diff --git a/app/models/place.rb b/app/models/place.rb index 5ba65ad..96876f9 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,92 +1,119 @@ class Place < ActiveRecord::Base has_many :operating_times acts_as_taggable_on :tags validates_presence_of :name def special_operating_times OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0", id], :order => "startDate ASC, opensAt ASC" ) end def regular_operating_times OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0", id], :order => "startDate ASC, opensAt ASC" ) end # Returns an array of OperatingTimes def schedule(startAt,endAt) # TODO Returns the schedule for a specified time window # TODO Handle events starting within the range but ending outside of it? - regular_times = regular_operating_times.select do |ot| - ot.at = startAt + regular_times = [] + regular_operating_times.each do |ot| ot.startDate ||= startAt.to_date ot.endDate ||= endAt.to_date - (ot.startDate <= startAt.to_date and ot.endDate >= endAt.to_date) and - ((ot.opensAt >= startAt and ot.opensAt <= endAt) or (ot.closesAt >= startAt and ot.closesAt <= endAt)) + + if ot.startDate >= startAt.to_date-1 and ot.endDate <= endAt.to_date+1 + ot.at = nil + + # Yesterday + ot.at = (startAt.to_date - 1).midnight + if ot.closesAt >= ot.at and ot.flags & 1<<ot.at.wday > 0 + t = ot.dup + t.opensAt = startAt + regular_times << t + t=nil + end + + # Today + ot.at = startAt.to_date.midnight + regular_times << ot.dup if ot.opensAt >= startAt and ot.opensAt < endAt and ot.flags & 1<<ot.at.wday > 0 + + # Tomorrow + ot.at = endAt == endAt.midnight ? endAt : endAt.midnight + 1.days + if ot.opensAt < endAt and ot.flags & 1<<ot.at.wday > 0 + t = ot.dup + t.closesAt = endAt + regular_times << t + t=nil + end + + end end + special_times = special_operating_times.select do |ot| ot.at = startAt ot.startDate ||= startAt.to_date ot.endDate ||= endAt.to_date (ot.startDate <= startAt.to_date and ot.endDate >= endAt.to_date) and ((ot.opensAt >= startAt and ot.opensAt <= endAt) or (ot.closesAt >= startAt and ot.closesAt <= endAt)) end # TODO Handle combinations (i.e. part special, part regular) special_times == [] ? regular_times : special_times + regular_times end def daySchedule(at = Date.today) at = at.to_date if at.class == Time or at.class == DateTime schedule = schedule(at.midnight,(at+1).midnight) - schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } - schedule.each {|t| t.at = at } + #schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } + #schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end schedule.sort{|a,b|a.opensAt <=> b.opensAt} =end end def currentSchedule(at = Time.now) current_schedule = nil daySchedule(at).each do |optime| if optime.opensAt <= at and optime.closesAt >= at #RAILS_DEFAULT_LOGGER.debug "Opens At: #{optime.opensAt.time(at).to_s}" #RAILS_DEFAULT_LOGGER.debug "Closes At: #{optime.closesAt.time(at).to_s}" current_schedule = optime end end current_schedule end def open?(at = Time.now) a = currentSchedule(at) return a ? true : false end # Alias for <tt>open?</tt> def open(at = Time.now); open? at ; end def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end def to_xml(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end end diff --git a/db/migrate/20090616040958_start_length_schema.rb b/db/migrate/20090616040958_start_length_schema.rb new file mode 100644 index 0000000..7dfc5de --- /dev/null +++ b/db/migrate/20090616040958_start_length_schema.rb @@ -0,0 +1,11 @@ +class StartLengthSchema < ActiveRecord::Migration + def self.up + OperatingTime.find(:all).each{|ot| ot.write_attribute(:closesAt, ot.read_attribute(:closesAt) - ot.read_attribute(:opensAt)) ; ot.save } + rename_column('operating_times', 'closesAt', 'length') + end + + def self.down + OperatingTime.find(:all).each{|ot| ot.length = ot.length + ot.read_attribute(:opensAt) ; ot.save } + rename_column('operating_times', 'length', 'closesAt') + end +end diff --git a/db/schema.rb b/db/schema.rb index b7bf019..be3ef1f 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,51 +1,51 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20090324042504) do +ActiveRecord::Schema.define(:version => 20090616040958) do create_table "operating_times", :force => true do |t| t.integer "place_id" t.integer "opensAt" - t.integer "closesAt" + t.integer "length" t.text "details" t.integer "flags" t.date "startDate" t.date "endDate" t.datetime "created_at" t.datetime "updated_at" end create_table "places", :force => true do |t| t.string "name" t.string "location" t.string "phone" t.datetime "created_at" t.datetime "updated_at" end create_table "taggings", :force => true do |t| t.integer "tag_id" t.integer "taggable_id" t.integer "tagger_id" t.string "tagger_type" t.string "taggable_type" t.string "context" t.datetime "created_at" end add_index "taggings", ["tag_id"], :name => "index_taggings_on_tag_id" add_index "taggings", ["taggable_id", "taggable_type", "context"], :name => "index_taggings_on_taggable_id_and_taggable_type_and_context" create_table "tags", :force => true do |t| t.string "name" end end diff --git a/lib/relative_time.rb b/lib/relative_time.rb index 7b9c465..246d9d5 100644 --- a/lib/relative_time.rb +++ b/lib/relative_time.rb @@ -1,61 +1,79 @@ class RelativeTime require 'time' def self._relativeTime(offset, baseTime = Time.now) offset = 0 if offset.nil? #offset = 86399 if offset >= 86400 Time.local(baseTime.year, baseTime.month, baseTime.day, (offset/3600).to_i, ((offset % 3600)/60).to_i) end def self._getMidnightOffset(time) time = Time.now if time.nil? time.hour * 3600 + time.min * 60 end - def initialize(object,attribute) + def initialize(object,startAttribute,lengthAttribute) @object = object - @attribute = attribute + @startAttribute = startAttribute + @lengthAttribute = lengthAttribute end +=begin def hour (offset / 3600).to_i end def hour=(hour) # hour_seconds + remainder_seconds offset = (hour * 3600) + (offset % 3600) end def minute ( (offset % 3600) / 60 ).to_i end def minute=(minute) # hour_seconds + minute_seconds + remainder_seconds offset = (hour * 3600) + (minute * 60) + (offset % 60) end +=end def offset - @object.send(:read_attribute,@attribute) + @object.send(:read_attribute,@startAttribute) end def offset=(newOffset) - @object.send(:write_attribute,@attribute,newOffset) + @object.send(:write_attribute,@startAttribute,newOffset) + end + + def length + @object.send(:read_attribute,@lengthAttribute) + end + def length=(newLength) + @object.send(:write_attribute,@lengthAttribute,newLength) end - def time(baseTime = Time.now) + def openTime(baseTime = Time.now) RelativeTime._relativeTime(offset, baseTime) end - def time=(newTime = Time.now) + def openTime=(newTime = Time.now) RAILS_DEFAULT_LOGGER.debug "Updating offset using Time object: #{newTime.inspect} ; offset = #{RelativeTime._getMidnightOffset(newTime)}" offset = RelativeTime._getMidnightOffset(newTime) end + def closeTime(baseTime = Time.now) + RelativeTime._relativeTime(offset, baseTime) + length + end + def closeTime=(newTime = Time.now) + RAILS_DEFAULT_LOGGER.debug "Updating offset using Time object: #{newTime.inspect} ; offset = #{RelativeTime._getMidnightOffset(newTime)}" + length = newTime - openTime + length = length + 24*60*60 if length < 0 + end def to_s '%02d:%02d' % [hour,minute] time.to_s end end diff --git a/test/fixtures/operating_times.yml b/test/fixtures/operating_times.yml index b38bdad..9f97dcd 100644 --- a/test/fixtures/operating_times.yml +++ b/test/fixtures/operating_times.yml @@ -1,25 +1,25 @@ # Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html openNow: place: greathall opensAt: <%= RelativeTime._getMidnightOffset(Time.now - 1.hours) %> - closesAt: <%= RelativeTime._getMidnightOffset(Time.now + 1.hours) %> + length: <%= 1.hours %> details: Open right now for dine-in (not special) flags: <%= OperatingTime::ALLDAYS_FLAG | OperatingTime::DINE_IN_FLAG %> openNowDifferentWeekday: place: greathall opensAt: <%= RelativeTime._getMidnightOffset(Time.now - 1.hours) %> - closesAt: <%= RelativeTime._getMidnightOffset(Time.now + 1.hours) %> + length: <%= 1.hours %> details: Open right now for dine-in, but on a different day of the week (not special) flags: <%= OperatingTime::DINE_IN_FLAG %> openNowSpecial: place: greathall opensAt: <%= RelativeTime._getMidnightOffset(Time.now - 1.hours) %> - closesAt: <%= RelativeTime._getMidnightOffset(Time.now + 1.hours) %> + length: <%= 1.hours %> startDate: <%= Date.today - 1.day %> endDate: <%= Date.today + 1.day %> details: Open right now for dine-in (not special) flags: <%= OperatingTime::ALLDAYS_FLAG | OperatingTime::DINE_IN_FLAG | OperatingTime::SPECIAL_FLAG %>
michaelansel/dukenow
812e6a0d4a9aea16a9cd0188d50fa782fac4a8c6
Set up milestones for database changes
diff --git a/TODO b/TODO index bf2bf63..da82102 100644 --- a/TODO +++ b/TODO @@ -1,80 +1,112 @@ vim:set syntax=todo: Database Places -- has_one :dining_extension \- name (string) -- location (lat/long) -- ?GeoKit Plugin? \- phone_number (string) DiningExtensions -- acts_as_taggable_on :dining_tags ## needs work -- **delivery/eat-in** ## operating_time details/tag -- more_info_url -- owner_operator -- payment_methods -- logo_url OperatingTimes \- place_id \- start (midnight offset in seconds) \- length (in seconds) \- startDate (Date) \- endDate (Date) \- details (String) -- override -- days_of_week (bit-wise AND of wday's) OperatingTimesTags -- name OperatingTimesTaggings (clone auto-generated) !- clone Taggings schema -- operating_time_id -- operating_times_tag_id TimePeriods -- name (String) -- startDate (Date) -- endDate (Date) API Versioning -- Subdirectories -- rake task for adding new versions and deprecating old versions Places OperatingTimes -- Array of DateTime objects for the next N hours/days/etc -- Bulk import Excel spreadsheet -- What qualifies as a Tag versus an Attribute? +Milestones + OperatingTimes StartLengthSchema + -- Migration + Feature-parity + -- schedule(from,to) + -- daySchedule(date) + -- currentSchedule(at) + -- open?(at) + -- Full unit tests + validation + -- Prevent overlapping time periods without "override" flag + Extend API + -- Generate Time objects + -- Add versioning + DiningExtensions + -- Migration + -- Full unit tests + validation + DiningExtensions Tags + -- Migrations + -- Full unit tests + validation + OperatingTimes Tags + -- Migration + -- Full unit tests + validation + -- Extend OperatingTimes.find to filter by tags + -- Extend Places.open? to test delivery/dine-in tags + TimePeriods + -- Migration + -- Full unit tests + validation + -- Create integration + -- View Integration + API Versioning rake Tasks + -- Clone for new version and increment version number + -- Deprecate old version -- Hosting for web app/file server? -- Can I get help with the UI design, or will DukeMobile only be focusing on the iPhone side? -- Set "expiration" date; Send reminder emails; Show _nothing_ rather than inaccurate info Database Adjust schema to be more flexible !- Late nights: seamless midnight rollover -- Start,End => Start,Length (then, convert to real "Time"s based on @at) -- iCal RRULE (string) and parse with RiCal (pre-release) \- Add "midnight" method to Date, Time -- (?) Multiple "special"/override schedules (e.g. every weekday during Spring Break except Friday) -- Special: "normally open, but closed all day today" -- Semester-style schedules -- List of important dates (likely to be scheduling boundaries) Interface Index (Main Page) -- Hide nowIndicator after midnight instead of wrapping around -- JavaScript Tag Filtering -- Status @ DateTime Data Entry -- Bulk import (CSV, XML) -- Duke Dining PDF parser (?) -- Not worth the effort to get consistent data Web Form -- Text entry of times (drop downs, input fields) -- Quickly add/edit all times for a location -- Graphic schedule of current settings -- Show "normal" schedule in background if making an exception -- Drag/Drop/Resize-able blocks on schedule
michaelansel/dukenow
50d00d90a3ab106ca9b2989c42a56e9b439fbf4a
Set up ToDo list for DB schema changes
diff --git a/TODO b/TODO new file mode 100644 index 0000000..bf2bf63 --- /dev/null +++ b/TODO @@ -0,0 +1,80 @@ +vim:set syntax=todo: + +Database + Places + -- has_one :dining_extension + \- name (string) + -- location (lat/long) -- ?GeoKit Plugin? + \- phone_number (string) + DiningExtensions + -- acts_as_taggable_on :dining_tags ## needs work + -- **delivery/eat-in** ## operating_time details/tag + -- more_info_url + -- owner_operator + -- payment_methods + -- logo_url + OperatingTimes + \- place_id + \- start (midnight offset in seconds) + \- length (in seconds) + \- startDate (Date) + \- endDate (Date) + \- details (String) + -- override + -- days_of_week (bit-wise AND of wday's) + OperatingTimesTags + -- name + OperatingTimesTaggings (clone auto-generated) + !- clone Taggings schema + -- operating_time_id + -- operating_times_tag_id + TimePeriods + -- name (String) + -- startDate (Date) + -- endDate (Date) + +API + Versioning + -- Subdirectories + -- rake task for adding new versions and deprecating old versions + Places + OperatingTimes + -- Array of DateTime objects for the next N hours/days/etc + + + +-- Bulk import Excel spreadsheet +-- What qualifies as a Tag versus an Attribute? + + + + + + +-- Hosting for web app/file server? +-- Can I get help with the UI design, or will DukeMobile only be focusing on the iPhone side? +-- Set "expiration" date; Send reminder emails; Show _nothing_ rather than inaccurate info +Database + Adjust schema to be more flexible + !- Late nights: seamless midnight rollover + -- Start,End => Start,Length (then, convert to real "Time"s based on @at) + -- iCal RRULE (string) and parse with RiCal (pre-release) + \- Add "midnight" method to Date, Time + -- (?) Multiple "special"/override schedules (e.g. every weekday during Spring Break except Friday) + -- Special: "normally open, but closed all day today" + -- Semester-style schedules + -- List of important dates (likely to be scheduling boundaries) +Interface + Index (Main Page) + -- Hide nowIndicator after midnight instead of wrapping around + -- JavaScript Tag Filtering + -- Status @ DateTime + Data Entry + -- Bulk import (CSV, XML) + -- Duke Dining PDF parser (?) -- Not worth the effort to get consistent data + Web Form + -- Text entry of times (drop downs, input fields) + -- Quickly add/edit all times for a location + -- Graphic schedule of current settings + -- Show "normal" schedule in background if making an exception + -- Drag/Drop/Resize-able blocks on schedule
michaelansel/dukenow
7aa056329cc442461822a0b459aeb13a98e2fdf5
Added ResetDatabase migration to clean up RunCodeRun test database
diff --git a/db/migrate/20090101000000_reset_database.rb b/db/migrate/20090101000000_reset_database.rb new file mode 100644 index 0000000..e7752c9 --- /dev/null +++ b/db/migrate/20090101000000_reset_database.rb @@ -0,0 +1,15 @@ +class ResetDatabase < ActiveRecord::Migration + def self.up + execute 'DELETE FROM schema_migrations WHERE 1;' rescue Exception + drop_table :places rescue Exception + drop_table :eateries rescue Exception + drop_table :operating_times rescue Exception + drop_table :regular_operating_times rescue Exception + drop_table :special_operating_times rescue Exception + drop_table :tags rescue Exception + drop_table :taggings rescue Exception + end + + def self.down + end +end diff --git a/db/migrate/20090314001220_create_operating_times.rb b/db/migrate/20090314001220_create_operating_times.rb index 6cc15fb..53b572d 100644 --- a/db/migrate/20090314001220_create_operating_times.rb +++ b/db/migrate/20090314001220_create_operating_times.rb @@ -1,23 +1,23 @@ class CreateOperatingTimes < ActiveRecord::Migration def self.up create_table :operating_times do |t| t.references :place t.integer :opensAt t.integer :closesAt t.text :details t.integer :flags t.date :startDate t.date :endDate t.timestamps end - execute "insert into operating_times (place_id, opensAt, closesAt, flags) select eatery_id as place_id,opensAt,closesAt,daysOfWeek as flags from regular_operating_times" - execute "insert into operating_times (place_id, opensAt, closesAt, flags, startDate, endDate) select eatery_id as place_id,opensAt,closesAt,daysOfWeek as flags,start as startDate,end as endDate from special_operating_times" - execute "update operating_times set flags = (flags + 128) where startDate not null and endDate not null" + #execute "insert into operating_times (place_id, opensAt, closesAt, flags) select eatery_id as place_id,opensAt,closesAt,daysOfWeek as flags from regular_operating_times" + #execute "insert into operating_times (place_id, opensAt, closesAt, flags, startDate, endDate) select eatery_id as place_id,opensAt,closesAt,daysOfWeek as flags,start as startDate,end as endDate from special_operating_times" + #execute "update operating_times set flags = (flags + 128) where startDate not null and endDate not null" end def self.down drop_table :operating_times end end
michaelansel/dukenow
fc7277aeba6d64aaa4768ecf1c65f6b27cd640d0
Finish cleanup of Eateries & Regular/SpecialOperatingTimes
diff --git a/db/migrate/20090312163647_create_places.rb b/db/migrate/20090312163647_create_places.rb index 118e4b4..8b1c915 100644 --- a/db/migrate/20090312163647_create_places.rb +++ b/db/migrate/20090312163647_create_places.rb @@ -1,16 +1,15 @@ class CreatePlaces < ActiveRecord::Migration def self.up create_table :places do |t| t.string :name t.string :location t.string :phone t.timestamps end - execute "insert into places select * from eateries" end def self.down drop_table :places end end diff --git a/db/schema.rb b/db/schema.rb index ce7628f..b7bf019 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,79 +1,51 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. ActiveRecord::Schema.define(:version => 20090324042504) do - create_table "eateries", :force => true do |t| - t.string "name" - t.string "location" - t.string "phone" - t.datetime "created_at" - t.datetime "updated_at" - end - create_table "operating_times", :force => true do |t| t.integer "place_id" t.integer "opensAt" t.integer "closesAt" t.text "details" t.integer "flags" t.date "startDate" t.date "endDate" t.datetime "created_at" t.datetime "updated_at" end create_table "places", :force => true do |t| t.string "name" t.string "location" t.string "phone" t.datetime "created_at" t.datetime "updated_at" end - create_table "regular_operating_times", :force => true do |t| - t.integer "eatery_id" - t.integer "opensAt" - t.integer "closesAt" - t.integer "daysOfWeek" - t.datetime "created_at" - t.datetime "updated_at" - end - - create_table "special_operating_times", :force => true do |t| - t.integer "eatery_id" - t.integer "opensAt" - t.integer "closesAt" - t.integer "daysOfWeek" - t.date "start" - t.date "end" - t.datetime "created_at" - t.datetime "updated_at" - end - create_table "taggings", :force => true do |t| t.integer "tag_id" t.integer "taggable_id" t.integer "tagger_id" t.string "tagger_type" t.string "taggable_type" t.string "context" t.datetime "created_at" end add_index "taggings", ["tag_id"], :name => "index_taggings_on_tag_id" add_index "taggings", ["taggable_id", "taggable_type", "context"], :name => "index_taggings_on_taggable_id_and_taggable_type_and_context" create_table "tags", :force => true do |t| t.string "name" end end
michaelansel/dukenow
c53515b588b1a6aa661f673f70ba7e7528cec3c5
Added Place model specs
diff --git a/app/models/place.rb b/app/models/place.rb index 73cbecb..5ba65ad 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,103 +1,92 @@ class Place < ActiveRecord::Base has_many :operating_times acts_as_taggable_on :tags + validates_presence_of :name def special_operating_times OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0", id], :order => "startDate ASC, opensAt ASC" ) end def regular_operating_times OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0", id], :order => "startDate ASC, opensAt ASC" ) end # Returns an array of OperatingTimes def schedule(startAt,endAt) # TODO Returns the schedule for a specified time window # TODO Handle events starting within the range but ending outside of it? regular_times = regular_operating_times.select do |ot| ot.at = startAt ot.startDate ||= startAt.to_date ot.endDate ||= endAt.to_date (ot.startDate <= startAt.to_date and ot.endDate >= endAt.to_date) and ((ot.opensAt >= startAt and ot.opensAt <= endAt) or (ot.closesAt >= startAt and ot.closesAt <= endAt)) end special_times = special_operating_times.select do |ot| ot.at = startAt ot.startDate ||= startAt.to_date ot.endDate ||= endAt.to_date (ot.startDate <= startAt.to_date and ot.endDate >= endAt.to_date) and ((ot.opensAt >= startAt and ot.opensAt <= endAt) or (ot.closesAt >= startAt and ot.closesAt <= endAt)) end # TODO Handle combinations (i.e. part special, part regular) special_times == [] ? regular_times : special_times end def daySchedule(at = Date.today) - if at.nil? - instance_eval("class Place::MonkeyButt < StandardError ; end") - raise MonkeyButt, "Oh no! It looks like we found a monkey butt!" - end at = at.to_date if at.class == Time or at.class == DateTime schedule = schedule(at.midnight,(at+1).midnight) schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end schedule.sort{|a,b|a.opensAt <=> b.opensAt} =end end def currentSchedule(at = Time.now) - if at.nil? - instance_eval("class Place::MonkeyButt < StandardError ; end") - raise MonkeyButt, "Oh no! It looks like we found a monkey butt!" - end current_schedule = nil daySchedule(at).each do |optime| if optime.opensAt <= at and optime.closesAt >= at #RAILS_DEFAULT_LOGGER.debug "Opens At: #{optime.opensAt.time(at).to_s}" #RAILS_DEFAULT_LOGGER.debug "Closes At: #{optime.closesAt.time(at).to_s}" current_schedule = optime end end current_schedule end def open?(at = Time.now) - if at.nil? - instance_eval("class Place::MonkeyButt < StandardError ; end") - raise MonkeyButt, "Oh no! It looks like we found a monkey butt!" - end a = currentSchedule(at) return a ? true : false end # Alias for <tt>open?</tt> def open(at = Time.now); open? at ; end def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end def to_xml(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end end diff --git a/config/environment.rb b/config/environment.rb index 004aa75..7caf417 100644 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,76 +1,76 @@ # Be sure to restart your server when you modify this file # Uncomment below to force Rails into production mode when # you don't control web/app server and can't set it the proper way # ENV['RAILS_ENV'] ||= 'production' # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.2.2' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # See Rails::Configuration for more options. # Skip frameworks you're not going to use. To use Rails without a database # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Specify gems that this application depends on. # They can then be installed with "rake gems:install" on new installations. # You have to specify the :lib option for libraries, where the Gem name (sqlite3-ruby) differs from the file itself (sqlite3) # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" - # config.gem "sqlite3-ruby", :lib => "sqlite3" + config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" config.gem "mbleigh-acts-as-taggable-on", :source => "http://gems.github.com", :lib => "acts-as-taggable-on" # Only load the plugins named here, in the order given. By default, all plugins # in vendor/plugins are loaded in alphabetical order. # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Force all environments to use the same logger level # (by default production uses :info, the others :debug) # config.log_level = :debug # Make Time.zone default to the specified zone, and make Active Record store time values # in the database in UTC, and return them converted to the specified local zone. # Run "rake -D time" for a list of tasks for finding time zone names. Comment line to use default local time. #config.time_zone = 'UTC' # The internationalization framework can be changed to have another default locale (standard is :en) or more load paths. # All files from config/locales/*.rb,yml are added automatically. # config.i18n.load_path << Dir[File.join(RAILS_ROOT, 'my', 'locales', '*.{rb,yml}')] # config.i18n.default_locale = :de # Your secret key for verifying cookie session data integrity. # If you change this key, all old sessions will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. config.action_controller.session = { :session_key => '_DukeNow_session', :secret => '8e8355b37da6a989cc5989da3b5bcb79f4b30d3e4b02ecf47ba68d716292194eb939ea71e068c13f3676158f16dd74577017f3838505ef7ed8043f3a65e87741' } # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rake db:sessions:create") # config.action_controller.session_store = :active_record_store # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Activate observers that should always be running # Please note that observers generated using script/generate observer need to have an _observer suffix # config.active_record.observers = :cacher, :garbage_collector, :forum_observer end diff --git a/spec/models/place_spec.rb b/spec/models/place_spec.rb index 646bbe8..6819a7d 100644 --- a/spec/models/place_spec.rb +++ b/spec/models/place_spec.rb @@ -1,12 +1,22 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe Place do before(:each) do @valid_attributes = { + :name => 'Test Place', + :location => 'Somewhere', + :phone => '(919) 555-1212' } end it "should create a new instance given valid attributes" do Place.create!(@valid_attributes) end + + it "should not create a new instance without a name" do + @valid_attributes.delete(:name) + lambda { Place.create!(@valid_attributes) }.should raise_error + end + + # TODO Create mocks for OperatingTime so we can test the scheduling methods end
michaelansel/dukenow
981e75312ef06822f787c686020b91e82f83403d
Fixed RSpec scaffolds to at least pass
diff --git a/app/controllers/operating_times_controller.rb b/app/controllers/operating_times_controller.rb index 638b231..59266ea 100644 --- a/app/controllers/operating_times_controller.rb +++ b/app/controllers/operating_times_controller.rb @@ -1,137 +1,138 @@ class OperatingTimesController < ApplicationController # GET /operating_times # GET /operating_times.xml def index if params[:place_id] @operating_times = OperatingTime.find(:all, :conditions => ['place_id = ?',params[:place_id]]) else @operating_times = OperatingTime.find(:all) end request.format = :html if request.format == :iphone respond_to do |format| format.html # index.html.erb format.xml { render :xml => @operating_times } end end # GET /operating_times/1 # GET /operating_times/1.xml def show @operating_time = OperatingTime.find(params[:id]) request.format = :html if request.format == :iphone respond_to do |format| format.html # show.html.erb format.xml { render :xml => @operating_time } end end # GET /operating_times/new # GET /operating_times/new.xml def new @operating_time = OperatingTime.new @places = Place.find(:all, :order => "name ASC") request.format = :html if request.format == :iphone respond_to do |format| format.html # new.html.erb format.xml { render :xml => @operating_time } end end # GET /operating_times/1/edit def edit @operating_time = OperatingTime.find(params[:id]) @places = Place.find(:all, :order => "name ASC") request.format = :html if request.format == :iphone end # POST /operating_times # POST /operating_times.xml def create params[:operating_time] = operatingTimesFormHandler(params[:operating_time]) @operating_time = OperatingTime.new(params[:operating_time]) request.format = :html if request.format == :iphone respond_to do |format| if @operating_time.save flash[:notice] = 'OperatingTime was successfully created.' format.html { redirect_to(@operating_time) } format.xml { render :xml => @operating_time, :status => :created, :location => @operating_time } else format.html { render :action => "new" } format.xml { render :xml => @operating_time.errors, :status => :unprocessable_entity } end end end # PUT /operating_times/1 # PUT /operating_times/1.xml def update @operating_time = OperatingTime.find(params[:id]) params[:operating_time] = operatingTimesFormHandler(params[:operating_time]) request.format = :html if request.format == :iphone respond_to do |format| if @operating_time.update_attributes(params[:operating_time]) flash[:notice] = 'OperatingTime was successfully updated.' format.html { redirect_to(@operating_time) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @operating_time.errors, :status => :unprocessable_entity } end end end # DELETE /operating_times/1 # DELETE /operating_times/1.xml def destroy @operating_time = OperatingTime.find(params[:id]) @operating_time.destroy request.format = :html if request.format == :iphone respond_to do |format| format.html { redirect_to(operating_times_url) } format.xml { head :ok } end end ## Helpers ## - def operatingTimesFormHandler(operatingTimesParams) + def operatingTimesFormHandler(operatingTimesParams={}) + operatingTimesParams ||= {} =begin params[:regular_operating_time][:opensAtOffset] = params[:regular_operating_time].delete('opensAtHour') * 3600 + params[:regular_operating_time].delete('opensAtMinute') * 60 params[:regular_operating_time][:closesAtOffset] = params[:regular_operating_time].delete('closesAtHour') * 3600 + params[:regular_operating_time].delete('closesAtMinute') * 60 =end if operatingTimesParams[:daysOfWeekHash] != nil daysOfWeek = 0 operatingTimesParams[:daysOfWeekHash].each do |dayOfWeek| daysOfWeek += 1 << Date::DAYNAMES.index(dayOfWeek.capitalize) end operatingTimesParams.delete('daysOfWeekHash') operatingTimesParams[:flags] = 0 if operatingTimesParams[:flags].nil? operatingTimesParams[:flags] = operatingTimesParams[:flags] & ~OperatingTime::ALLDAYS_FLAG operatingTimesParams[:flags] = operatingTimesParams[:flags] | daysOfWeek end return operatingTimesParams end end diff --git a/app/controllers/places_controller.rb b/app/controllers/places_controller.rb index 632ee75..7a64ac8 100644 --- a/app/controllers/places_controller.rb +++ b/app/controllers/places_controller.rb @@ -1,172 +1,172 @@ class PlacesController < ApplicationController ActionView::Base.send :include, TagsHelper before_filter :get_at_date def get_at_date params[:at] = Date.today.to_s if params[:at].nil? @at = Date.parse(params[:at]) end # GET /places # GET /places.xml def index @places = Place.find(:all, :order => "name ASC") if params[:tags] @selected_tags = params[:tags].split(/[,+ ][ ]*/) else @selected_tags = [] end # Restrict to specific tags @selected_tags.each do |tag| RAILS_DEFAULT_LOGGER.debug "Restricting by tag: #{tag}" @places = @places & Place.tagged_with(tag, :on => :tags) end # Don't display machineAdded Places on the main listing @places = @places - Place.tagged_with("machineAdded", :on => :tags) unless @selected_tags.include?("machineAdded") # Calculate tag count for all Places with Tags #@tags = Place.tag_counts_on(:tags, :at_least => 1) # Manually calculate tag counts for only displayed places tags = [] @places.each do |place| tags = tags + place.tag_list end # Remove already selected tags tags = tags - @selected_tags # Count tags and make a set of [name,count] pairs @tag_counts = tags.uniq.collect {|tag| [tag,tags.select{|a|a == tag}.size] } # Filter out single tags @tag_counts = @tag_counts.select{|name,count| count > 1} # Make the count arrays act like tags for the tag cloud @tag_counts.each do |a| a.instance_eval <<-RUBY def count self[1] end def name self[0] end RUBY end respond_to do |format| format.html # index.html.erb format.iphone # index.iphone.erb format.json { render :json => @places } format.xml { render :xml => @places } end end def tag redirect_to :action => :index, :tags => params.delete(:id) end # GET /places/1 # GET /places/1.xml def show @place = Place.find(params[:id]) request.format = :html if request.format == :iphone respond_to do |format| format.html # show.html.erb format.xml { render :xml => @place } end end # GET /places/new # GET /places/new.xml def new @place = Place.new request.format = :html if request.format == :iphone respond_to do |format| format.html # new.html.erb format.xml { render :xml => @place } end end # GET /places/1/edit def edit @place = Place.find(params[:id]) request.format = :html if request.format == :iphone end # POST /places # POST /places.xml def create - if params[:place][:tag_list] + if params[:place] and params[:place][:tag_list] params[:place][:tag_list].strip! params[:place][:tag_list].gsub!(/( )+/,', ') end @place = Place.new(params[:place]) request.format = :html if request.format == :iphone respond_to do |format| if @place.save flash[:notice] = 'Place was successfully created.' format.html { redirect_to(@place) } format.xml { render :xml => @place, :status => :created, :location => @place } else format.html { render :action => "new" } format.xml { render :xml => @place.errors, :status => :unprocessable_entity } end end end # PUT /places/1 # PUT /places/1.xml def update @place = Place.find(params[:id]) - if params[:place][:tag_list] + if params[:place] and params[:place][:tag_list] params[:place][:tag_list].strip! params[:place][:tag_list].gsub!(/( )+/,', ') end request.format = :html if request.format == :iphone respond_to do |format| if @place.update_attributes(params[:place]) flash[:notice] = 'Place was successfully updated.' format.html { redirect_to(@place) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @place.errors, :status => :unprocessable_entity } end end end # DELETE /places/1 # DELETE /places/1.xml def destroy @place = Place.find(params[:id]) @place.destroy request.format = :html if request.format == :iphone respond_to do |format| format.html { redirect_to(places_url) } format.xml { head :ok } end end # GET /places/open # GET /places/open.xml def open @place = Place.find(params[:id]) request.format = :html if request.format == :iphone respond_to do |format| format.html # open.html.erb format.xml { render :xml => @place } end end end diff --git a/app/models/place.rb b/app/models/place.rb index bfc585e..73cbecb 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,91 +1,103 @@ class Place < ActiveRecord::Base has_many :operating_times acts_as_taggable_on :tags def special_operating_times OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0", id], :order => "startDate ASC, opensAt ASC" ) end def regular_operating_times OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0", id], :order => "startDate ASC, opensAt ASC" ) end # Returns an array of OperatingTimes def schedule(startAt,endAt) # TODO Returns the schedule for a specified time window # TODO Handle events starting within the range but ending outside of it? regular_times = regular_operating_times.select do |ot| ot.at = startAt ot.startDate ||= startAt.to_date ot.endDate ||= endAt.to_date (ot.startDate <= startAt.to_date and ot.endDate >= endAt.to_date) and ((ot.opensAt >= startAt and ot.opensAt <= endAt) or (ot.closesAt >= startAt and ot.closesAt <= endAt)) end special_times = special_operating_times.select do |ot| ot.at = startAt ot.startDate ||= startAt.to_date ot.endDate ||= endAt.to_date (ot.startDate <= startAt.to_date and ot.endDate >= endAt.to_date) and ((ot.opensAt >= startAt and ot.opensAt <= endAt) or (ot.closesAt >= startAt and ot.closesAt <= endAt)) end # TODO Handle combinations (i.e. part special, part regular) special_times == [] ? regular_times : special_times end def daySchedule(at = Date.today) + if at.nil? + instance_eval("class Place::MonkeyButt < StandardError ; end") + raise MonkeyButt, "Oh no! It looks like we found a monkey butt!" + end at = at.to_date if at.class == Time or at.class == DateTime schedule = schedule(at.midnight,(at+1).midnight) schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } schedule.each {|t| t.at = at } =begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end schedule.sort{|a,b|a.opensAt <=> b.opensAt} =end end def currentSchedule(at = Time.now) + if at.nil? + instance_eval("class Place::MonkeyButt < StandardError ; end") + raise MonkeyButt, "Oh no! It looks like we found a monkey butt!" + end current_schedule = nil daySchedule(at).each do |optime| if optime.opensAt <= at and optime.closesAt >= at #RAILS_DEFAULT_LOGGER.debug "Opens At: #{optime.opensAt.time(at).to_s}" #RAILS_DEFAULT_LOGGER.debug "Closes At: #{optime.closesAt.time(at).to_s}" current_schedule = optime end end current_schedule end def open?(at = Time.now) + if at.nil? + instance_eval("class Place::MonkeyButt < StandardError ; end") + raise MonkeyButt, "Oh no! It looks like we found a monkey butt!" + end a = currentSchedule(at) return a ? true : false end # Alias for <tt>open?</tt> def open(at = Time.now); open? at ; end def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end def to_xml(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end end diff --git a/spec/controllers/places_controller_spec.rb b/spec/controllers/places_controller_spec.rb index 70655f5..7cedbcc 100644 --- a/spec/controllers/places_controller_spec.rb +++ b/spec/controllers/places_controller_spec.rb @@ -1,131 +1,132 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe PlacesController do def mock_place(stubs={}) @mock_place ||= mock_model(Place, stubs) end describe "GET index" do it "assigns all places as @places" do + pending("Need to adjust test to work with tag filtering") Place.stub!(:find).with(:all).and_return([mock_place]) get :index assigns[:places].should == [mock_place] end end describe "GET show" do it "assigns the requested place as @place" do Place.stub!(:find).with("37").and_return(mock_place) get :show, :id => "37" assigns[:place].should equal(mock_place) end end describe "GET new" do it "assigns a new place as @place" do Place.stub!(:new).and_return(mock_place) get :new assigns[:place].should equal(mock_place) end end describe "GET edit" do it "assigns the requested place as @place" do Place.stub!(:find).with("37").and_return(mock_place) get :edit, :id => "37" assigns[:place].should equal(mock_place) end end describe "POST create" do describe "with valid params" do it "assigns a newly created place as @place" do Place.stub!(:new).with({'these' => 'params'}).and_return(mock_place(:save => true)) post :create, :place => {:these => 'params'} assigns[:place].should equal(mock_place) end it "redirects to the created place" do Place.stub!(:new).and_return(mock_place(:save => true)) post :create, :place => {} response.should redirect_to(place_url(mock_place)) end end describe "with invalid params" do it "assigns a newly created but unsaved place as @place" do Place.stub!(:new).with({'these' => 'params'}).and_return(mock_place(:save => false)) post :create, :place => {:these => 'params'} assigns[:place].should equal(mock_place) end it "re-renders the 'new' template" do Place.stub!(:new).and_return(mock_place(:save => false)) post :create, :place => {} response.should render_template('new') end end end describe "PUT update" do describe "with valid params" do it "updates the requested place" do Place.should_receive(:find).with("37").and_return(mock_place) mock_place.should_receive(:update_attributes).with({'these' => 'params'}) put :update, :id => "37", :place => {:these => 'params'} end it "assigns the requested place as @place" do Place.stub!(:find).and_return(mock_place(:update_attributes => true)) put :update, :id => "1" assigns[:place].should equal(mock_place) end it "redirects to the place" do Place.stub!(:find).and_return(mock_place(:update_attributes => true)) put :update, :id => "1" response.should redirect_to(place_url(mock_place)) end end describe "with invalid params" do it "updates the requested place" do Place.should_receive(:find).with("37").and_return(mock_place) mock_place.should_receive(:update_attributes).with({'these' => 'params'}) put :update, :id => "37", :place => {:these => 'params'} end it "assigns the place as @place" do Place.stub!(:find).and_return(mock_place(:update_attributes => false)) put :update, :id => "1" assigns[:place].should equal(mock_place) end it "re-renders the 'edit' template" do Place.stub!(:find).and_return(mock_place(:update_attributes => false)) put :update, :id => "1" response.should render_template('edit') end end end describe "DELETE destroy" do it "destroys the requested place" do Place.should_receive(:find).with("37").and_return(mock_place) mock_place.should_receive(:destroy) delete :destroy, :id => "37" end it "redirects to the places list" do Place.stub!(:find).and_return(mock_place(:destroy => true)) delete :destroy, :id => "1" response.should redirect_to(places_url) end end end diff --git a/spec/models/operating_time_spec.rb b/spec/models/operating_time_spec.rb index f1227da..62ca71d 100644 --- a/spec/models/operating_time_spec.rb +++ b/spec/models/operating_time_spec.rb @@ -1,12 +1,14 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe OperatingTime do before(:each) do + @place = mock_model(Place) @valid_attributes = { + :place_id => @place.id } end it "should create a new instance given valid attributes" do OperatingTime.create!(@valid_attributes) end end diff --git a/spec/views/operating_times/edit.html.erb_spec.rb b/spec/views/operating_times/edit.html.erb_spec.rb index 2064e9d..58fc10a 100644 --- a/spec/views/operating_times/edit.html.erb_spec.rb +++ b/spec/views/operating_times/edit.html.erb_spec.rb @@ -1,20 +1,21 @@ require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe "/operating_times/edit.html.erb" do include OperatingTimesHelper before(:each) do assigns[:operating_time] = @operating_time = stub_model(OperatingTime, :new_record? => false ) + assigns[:places] = @places = [stub_model(Place),stub_model(Place)] end it "renders the edit operating_time form" do render response.should have_tag("form[action=#{operating_time_path(@operating_time)}][method=post]") do end end end diff --git a/spec/views/operating_times/index.html.erb_spec.rb b/spec/views/operating_times/index.html.erb_spec.rb index d29de81..f2da7ff 100644 --- a/spec/views/operating_times/index.html.erb_spec.rb +++ b/spec/views/operating_times/index.html.erb_spec.rb @@ -1,17 +1,20 @@ require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe "/operating_times/index.html.erb" do include OperatingTimesHelper before(:each) do - assigns[:operating_times] = [ + @operating_times = [ stub_model(OperatingTime), stub_model(OperatingTime) ] + @operating_times[0].place = stub_model(Place) + @operating_times[1].place = stub_model(Place) + assigns[:operating_times] = @operating_times end it "renders a list of operating_times" do render end end diff --git a/spec/views/operating_times/new.html.erb_spec.rb b/spec/views/operating_times/new.html.erb_spec.rb index 4abe237..76b2375 100644 --- a/spec/views/operating_times/new.html.erb_spec.rb +++ b/spec/views/operating_times/new.html.erb_spec.rb @@ -1,20 +1,21 @@ require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe "/operating_times/new.html.erb" do include OperatingTimesHelper before(:each) do assigns[:operating_time] = stub_model(OperatingTime, :new_record? => true ) + assigns[:places] = @places = [stub_model(Place),stub_model(Place)] end it "renders new operating_time form" do render response.should have_tag("form[action=?][method=post]", operating_times_path) do end end end diff --git a/spec/views/operating_times/show.html.erb_spec.rb b/spec/views/operating_times/show.html.erb_spec.rb index 239a2fb..a52c3cd 100644 --- a/spec/views/operating_times/show.html.erb_spec.rb +++ b/spec/views/operating_times/show.html.erb_spec.rb @@ -1,13 +1,18 @@ require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe "/operating_times/show.html.erb" do include OperatingTimesHelper before(:each) do assigns[:operating_time] = @operating_time = stub_model(OperatingTime) + + assigns[:place] = @place = stub_model(Place) + @operating_time.place = @place + + assigns[:at] = @at = Date.today end it "renders attributes in <p>" do render end end diff --git a/spec/views/places/show.html.erb_spec.rb b/spec/views/places/show.html.erb_spec.rb index c9a1097..1f77dbc 100644 --- a/spec/views/places/show.html.erb_spec.rb +++ b/spec/views/places/show.html.erb_spec.rb @@ -1,13 +1,14 @@ require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe "/places/show.html.erb" do include PlacesHelper before(:each) do assigns[:place] = @place = stub_model(Place) + assigns[:at] = @at = Date.today end it "renders attributes in <p>" do render end end
michaelansel/dukenow
028321a2a54dea42fb205ba3ecec2774cc1fdfc5
Added RSpec scaffolds (broken)
diff --git a/.autotest b/.autotest deleted file mode 100644 index 3f63d3f..0000000 --- a/.autotest +++ /dev/null @@ -1,31 +0,0 @@ -#vim:set syntax=ruby: -require 'autotest/redgreen.rb' - - - -module Autotest::GnomeNotify - - # Time notification will be displayed before disappearing automatically - EXPIRATION_IN_SECONDS = 2 - ERROR_STOCK_ICON = "gtk-dialog-error" - SUCCESS_STOCK_ICON = "gtk-dialog-info" - - # Convenience method to send an error notification message - # - # [stock_icon] Stock icon name of icon to display - # [title] Notification message title - # [message] Core message for the notification - def self.notify stock_icon, title, message - options = "-t #{EXPIRATION_IN_SECONDS * 1000} -i #{stock_icon}" - system "notify-send #{options} '#{title}' '#{message}'" - end - - Autotest.add_hook :red do |at| - notify ERROR_STOCK_ICON, "Tests failed", "#{at.files_to_test.size} tests failed" - end - - Autotest.add_hook :green do |at| - notify SUCCESS_STOCK_ICON, "All tests passed, good job!", "" - end - -end diff --git a/lib/tasks/rspec.rake b/lib/tasks/rspec.rake new file mode 100644 index 0000000..9bec754 --- /dev/null +++ b/lib/tasks/rspec.rake @@ -0,0 +1,167 @@ +gem 'test-unit', '1.2.3' if RUBY_VERSION.to_f >= 1.9 +rspec_plugin_dir = File.expand_path(File.dirname(__FILE__) + '/../../vendor/plugins/rspec') +$LOAD_PATH.unshift("#{rspec_plugin_dir}/lib") if File.exist?(rspec_plugin_dir) + +# Don't load rspec if running "rake gems:*" +unless ARGV.any? {|a| a =~ /^gems/} + +begin + require 'spec/rake/spectask' +rescue MissingSourceFile + module Spec + module Rake + class SpecTask + def initialize(name) + task name do + # if rspec-rails is a configured gem, this will output helpful material and exit ... + require File.expand_path(File.dirname(__FILE__) + "/../../config/environment") + + # ... otherwise, do this: + raise <<-MSG + +#{"*" * 80} +* You are trying to run an rspec rake task defined in +* #{__FILE__}, +* but rspec can not be found in vendor/gems, vendor/plugins or system gems. +#{"*" * 80} +MSG + end + end + end + end + end +end + +Rake.application.instance_variable_get('@tasks').delete('default') + +spec_prereq = File.exist?(File.join(RAILS_ROOT, 'config', 'database.yml')) ? "db:test:prepare" : :noop +task :noop do +end + +task :default => :spec +task :stats => "spec:statsetup" + +desc "Run all specs in spec directory (excluding plugin specs)" +Spec::Rake::SpecTask.new(:spec => spec_prereq) do |t| + t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""] + t.spec_files = FileList['spec/**/*/*_spec.rb'] +end + +namespace :spec do + desc "Run all specs in spec directory with RCov (excluding plugin specs)" + Spec::Rake::SpecTask.new(:rcov) do |t| + t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""] + t.spec_files = FileList['spec/**/*/*_spec.rb'] + t.rcov = true + t.rcov_opts = lambda do + IO.readlines("#{RAILS_ROOT}/spec/rcov.opts").map {|l| l.chomp.split " "}.flatten + end + end + + desc "Print Specdoc for all specs (excluding plugin specs)" + Spec::Rake::SpecTask.new(:doc) do |t| + t.spec_opts = ["--format", "specdoc", "--dry-run"] + t.spec_files = FileList['spec/**/*/*_spec.rb'] + end + + desc "Print Specdoc for all plugin examples" + Spec::Rake::SpecTask.new(:plugin_doc) do |t| + t.spec_opts = ["--format", "specdoc", "--dry-run"] + t.spec_files = FileList['vendor/plugins/**/spec/**/*/*_spec.rb'].exclude('vendor/plugins/rspec/*') + end + + [:models, :controllers, :views, :helpers, :lib].each do |sub| + desc "Run the code examples in spec/#{sub}" + Spec::Rake::SpecTask.new(sub => spec_prereq) do |t| + t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""] + t.spec_files = FileList["spec/#{sub}/**/*_spec.rb"] + end + end + + desc "Run the code examples in vendor/plugins (except RSpec's own)" + Spec::Rake::SpecTask.new(:plugins => spec_prereq) do |t| + t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""] + t.spec_files = FileList['vendor/plugins/**/spec/**/*/*_spec.rb'].exclude('vendor/plugins/rspec/*').exclude("vendor/plugins/rspec-rails/*") + end + + namespace :plugins do + desc "Runs the examples for rspec_on_rails" + Spec::Rake::SpecTask.new(:rspec_on_rails) do |t| + t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""] + t.spec_files = FileList['vendor/plugins/rspec-rails/spec/**/*/*_spec.rb'] + end + end + + # Setup specs for stats + task :statsetup do + require 'code_statistics' + ::STATS_DIRECTORIES << %w(Model\ specs spec/models) if File.exist?('spec/models') + ::STATS_DIRECTORIES << %w(View\ specs spec/views) if File.exist?('spec/views') + ::STATS_DIRECTORIES << %w(Controller\ specs spec/controllers) if File.exist?('spec/controllers') + ::STATS_DIRECTORIES << %w(Helper\ specs spec/helpers) if File.exist?('spec/helpers') + ::STATS_DIRECTORIES << %w(Library\ specs spec/lib) if File.exist?('spec/lib') + ::STATS_DIRECTORIES << %w(Routing\ specs spec/routing) if File.exist?('spec/routing') + ::CodeStatistics::TEST_TYPES << "Model specs" if File.exist?('spec/models') + ::CodeStatistics::TEST_TYPES << "View specs" if File.exist?('spec/views') + ::CodeStatistics::TEST_TYPES << "Controller specs" if File.exist?('spec/controllers') + ::CodeStatistics::TEST_TYPES << "Helper specs" if File.exist?('spec/helpers') + ::CodeStatistics::TEST_TYPES << "Library specs" if File.exist?('spec/lib') + ::CodeStatistics::TEST_TYPES << "Routing specs" if File.exist?('spec/routing') + end + + namespace :db do + namespace :fixtures do + desc "Load fixtures (from spec/fixtures) into the current environment's database. Load specific fixtures using FIXTURES=x,y. Load from subdirectory in test/fixtures using FIXTURES_DIR=z." + task :load => :environment do + ActiveRecord::Base.establish_connection(Rails.env) + base_dir = File.join(Rails.root, 'spec', 'fixtures') + fixtures_dir = ENV['FIXTURES_DIR'] ? File.join(base_dir, ENV['FIXTURES_DIR']) : base_dir + + require 'active_record/fixtures' + (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/).map {|f| File.join(fixtures_dir, f) } : Dir.glob(File.join(fixtures_dir, '*.{yml,csv}'))).each do |fixture_file| + Fixtures.create_fixtures(File.dirname(fixture_file), File.basename(fixture_file, '.*')) + end + end + end + end + + namespace :server do + daemonized_server_pid = File.expand_path("#{RAILS_ROOT}/tmp/pids/spec_server.pid") + + desc "start spec_server." + task :start do + if File.exist?(daemonized_server_pid) + $stderr.puts "spec_server is already running." + else + $stderr.puts %Q{Starting up spec_server ...} + FileUtils.mkdir_p('tmp/pids') unless test ?d, 'tmp/pids' + system("ruby", "script/spec_server", "--daemon", "--pid", daemonized_server_pid) + end + end + + desc "stop spec_server." + task :stop do + unless File.exist?(daemonized_server_pid) + $stderr.puts "No server running." + else + $stderr.puts "Shutting down spec_server ..." + system("kill", "-s", "TERM", File.read(daemonized_server_pid).strip) && + File.delete(daemonized_server_pid) + end + end + + desc "restart spec_server." + task :restart => [:stop, :start] + + desc "check if spec server is running" + task :status do + if File.exist?(daemonized_server_pid) + $stderr.puts %Q{spec_server is running (PID: #{File.read(daemonized_server_pid).gsub("\n","")})} + else + $stderr.puts "No server running." + end + end + end +end + +end diff --git a/script/autospec b/script/autospec new file mode 100755 index 0000000..837bbd7 --- /dev/null +++ b/script/autospec @@ -0,0 +1,6 @@ +#!/usr/bin/env ruby +gem 'test-unit', '1.2.3' if RUBY_VERSION.to_f >= 1.9 +ENV['RSPEC'] = 'true' # allows autotest to discover rspec +ENV['AUTOTEST'] = 'true' # allows autotest to run w/ color on linux +system((RUBY_PLATFORM =~ /mswin|mingw/ ? 'autotest.bat' : 'autotest'), *ARGV) || + $stderr.puts("Unable to find autotest. Please install ZenTest or fix your PATH") diff --git a/script/spec b/script/spec new file mode 100755 index 0000000..46fdbe6 --- /dev/null +++ b/script/spec @@ -0,0 +1,10 @@ +#!/usr/bin/env ruby +if ARGV.any? {|arg| %w[--drb -X --generate-options -G --help -h --version -v].include?(arg)} + require 'rubygems' unless ENV['NO_RUBYGEMS'] +else + gem 'test-unit', '1.2.3' if RUBY_VERSION.to_f >= 1.9 + ENV["RAILS_ENV"] ||= 'test' + require File.expand_path(File.dirname(__FILE__) + "/../config/environment") unless defined?(RAILS_ROOT) +end +require 'spec/autorun' +exit ::Spec::Runner::CommandLine.run diff --git a/script/spec_server b/script/spec_server new file mode 100755 index 0000000..941fc9d --- /dev/null +++ b/script/spec_server @@ -0,0 +1,9 @@ +#!/usr/bin/env ruby +gem 'test-unit', '1.2.3' if RUBY_VERSION.to_f >= 1.9 + +puts "Loading Rails environment" +ENV["RAILS_ENV"] ||= 'test' +require File.expand_path(File.dirname(__FILE__) + "/../config/environment") unless defined?(RAILS_ROOT) + +require 'optparse' +require 'spec/rails/spec_server' diff --git a/spec/controllers/operating_times_controller_spec.rb b/spec/controllers/operating_times_controller_spec.rb new file mode 100644 index 0000000..a5402fe --- /dev/null +++ b/spec/controllers/operating_times_controller_spec.rb @@ -0,0 +1,131 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') + +describe OperatingTimesController do + + def mock_operating_time(stubs={}) + @mock_operating_time ||= mock_model(OperatingTime, stubs) + end + + describe "GET index" do + it "assigns all operating_times as @operating_times" do + OperatingTime.stub!(:find).with(:all).and_return([mock_operating_time]) + get :index + assigns[:operating_times].should == [mock_operating_time] + end + end + + describe "GET show" do + it "assigns the requested operating_time as @operating_time" do + OperatingTime.stub!(:find).with("37").and_return(mock_operating_time) + get :show, :id => "37" + assigns[:operating_time].should equal(mock_operating_time) + end + end + + describe "GET new" do + it "assigns a new operating_time as @operating_time" do + OperatingTime.stub!(:new).and_return(mock_operating_time) + get :new + assigns[:operating_time].should equal(mock_operating_time) + end + end + + describe "GET edit" do + it "assigns the requested operating_time as @operating_time" do + OperatingTime.stub!(:find).with("37").and_return(mock_operating_time) + get :edit, :id => "37" + assigns[:operating_time].should equal(mock_operating_time) + end + end + + describe "POST create" do + + describe "with valid params" do + it "assigns a newly created operating_time as @operating_time" do + OperatingTime.stub!(:new).with({'these' => 'params'}).and_return(mock_operating_time(:save => true)) + post :create, :operating_time => {:these => 'params'} + assigns[:operating_time].should equal(mock_operating_time) + end + + it "redirects to the created operating_time" do + OperatingTime.stub!(:new).and_return(mock_operating_time(:save => true)) + post :create, :operating_time => {} + response.should redirect_to(operating_time_url(mock_operating_time)) + end + end + + describe "with invalid params" do + it "assigns a newly created but unsaved operating_time as @operating_time" do + OperatingTime.stub!(:new).with({'these' => 'params'}).and_return(mock_operating_time(:save => false)) + post :create, :operating_time => {:these => 'params'} + assigns[:operating_time].should equal(mock_operating_time) + end + + it "re-renders the 'new' template" do + OperatingTime.stub!(:new).and_return(mock_operating_time(:save => false)) + post :create, :operating_time => {} + response.should render_template('new') + end + end + + end + + describe "PUT update" do + + describe "with valid params" do + it "updates the requested operating_time" do + OperatingTime.should_receive(:find).with("37").and_return(mock_operating_time) + mock_operating_time.should_receive(:update_attributes).with({'these' => 'params'}) + put :update, :id => "37", :operating_time => {:these => 'params'} + end + + it "assigns the requested operating_time as @operating_time" do + OperatingTime.stub!(:find).and_return(mock_operating_time(:update_attributes => true)) + put :update, :id => "1" + assigns[:operating_time].should equal(mock_operating_time) + end + + it "redirects to the operating_time" do + OperatingTime.stub!(:find).and_return(mock_operating_time(:update_attributes => true)) + put :update, :id => "1" + response.should redirect_to(operating_time_url(mock_operating_time)) + end + end + + describe "with invalid params" do + it "updates the requested operating_time" do + OperatingTime.should_receive(:find).with("37").and_return(mock_operating_time) + mock_operating_time.should_receive(:update_attributes).with({'these' => 'params'}) + put :update, :id => "37", :operating_time => {:these => 'params'} + end + + it "assigns the operating_time as @operating_time" do + OperatingTime.stub!(:find).and_return(mock_operating_time(:update_attributes => false)) + put :update, :id => "1" + assigns[:operating_time].should equal(mock_operating_time) + end + + it "re-renders the 'edit' template" do + OperatingTime.stub!(:find).and_return(mock_operating_time(:update_attributes => false)) + put :update, :id => "1" + response.should render_template('edit') + end + end + + end + + describe "DELETE destroy" do + it "destroys the requested operating_time" do + OperatingTime.should_receive(:find).with("37").and_return(mock_operating_time) + mock_operating_time.should_receive(:destroy) + delete :destroy, :id => "37" + end + + it "redirects to the operating_times list" do + OperatingTime.stub!(:find).and_return(mock_operating_time(:destroy => true)) + delete :destroy, :id => "1" + response.should redirect_to(operating_times_url) + end + end + +end diff --git a/spec/controllers/places_controller_spec.rb b/spec/controllers/places_controller_spec.rb new file mode 100644 index 0000000..70655f5 --- /dev/null +++ b/spec/controllers/places_controller_spec.rb @@ -0,0 +1,131 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') + +describe PlacesController do + + def mock_place(stubs={}) + @mock_place ||= mock_model(Place, stubs) + end + + describe "GET index" do + it "assigns all places as @places" do + Place.stub!(:find).with(:all).and_return([mock_place]) + get :index + assigns[:places].should == [mock_place] + end + end + + describe "GET show" do + it "assigns the requested place as @place" do + Place.stub!(:find).with("37").and_return(mock_place) + get :show, :id => "37" + assigns[:place].should equal(mock_place) + end + end + + describe "GET new" do + it "assigns a new place as @place" do + Place.stub!(:new).and_return(mock_place) + get :new + assigns[:place].should equal(mock_place) + end + end + + describe "GET edit" do + it "assigns the requested place as @place" do + Place.stub!(:find).with("37").and_return(mock_place) + get :edit, :id => "37" + assigns[:place].should equal(mock_place) + end + end + + describe "POST create" do + + describe "with valid params" do + it "assigns a newly created place as @place" do + Place.stub!(:new).with({'these' => 'params'}).and_return(mock_place(:save => true)) + post :create, :place => {:these => 'params'} + assigns[:place].should equal(mock_place) + end + + it "redirects to the created place" do + Place.stub!(:new).and_return(mock_place(:save => true)) + post :create, :place => {} + response.should redirect_to(place_url(mock_place)) + end + end + + describe "with invalid params" do + it "assigns a newly created but unsaved place as @place" do + Place.stub!(:new).with({'these' => 'params'}).and_return(mock_place(:save => false)) + post :create, :place => {:these => 'params'} + assigns[:place].should equal(mock_place) + end + + it "re-renders the 'new' template" do + Place.stub!(:new).and_return(mock_place(:save => false)) + post :create, :place => {} + response.should render_template('new') + end + end + + end + + describe "PUT update" do + + describe "with valid params" do + it "updates the requested place" do + Place.should_receive(:find).with("37").and_return(mock_place) + mock_place.should_receive(:update_attributes).with({'these' => 'params'}) + put :update, :id => "37", :place => {:these => 'params'} + end + + it "assigns the requested place as @place" do + Place.stub!(:find).and_return(mock_place(:update_attributes => true)) + put :update, :id => "1" + assigns[:place].should equal(mock_place) + end + + it "redirects to the place" do + Place.stub!(:find).and_return(mock_place(:update_attributes => true)) + put :update, :id => "1" + response.should redirect_to(place_url(mock_place)) + end + end + + describe "with invalid params" do + it "updates the requested place" do + Place.should_receive(:find).with("37").and_return(mock_place) + mock_place.should_receive(:update_attributes).with({'these' => 'params'}) + put :update, :id => "37", :place => {:these => 'params'} + end + + it "assigns the place as @place" do + Place.stub!(:find).and_return(mock_place(:update_attributes => false)) + put :update, :id => "1" + assigns[:place].should equal(mock_place) + end + + it "re-renders the 'edit' template" do + Place.stub!(:find).and_return(mock_place(:update_attributes => false)) + put :update, :id => "1" + response.should render_template('edit') + end + end + + end + + describe "DELETE destroy" do + it "destroys the requested place" do + Place.should_receive(:find).with("37").and_return(mock_place) + mock_place.should_receive(:destroy) + delete :destroy, :id => "37" + end + + it "redirects to the places list" do + Place.stub!(:find).and_return(mock_place(:destroy => true)) + delete :destroy, :id => "1" + response.should redirect_to(places_url) + end + end + +end diff --git a/spec/fixtures/operating_times.yml b/spec/fixtures/operating_times.yml new file mode 100644 index 0000000..5bf0293 --- /dev/null +++ b/spec/fixtures/operating_times.yml @@ -0,0 +1,7 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +# one: +# column: value +# +# two: +# column: value diff --git a/spec/fixtures/places.yml b/spec/fixtures/places.yml new file mode 100644 index 0000000..5bf0293 --- /dev/null +++ b/spec/fixtures/places.yml @@ -0,0 +1,7 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +# one: +# column: value +# +# two: +# column: value diff --git a/spec/helpers/operating_times_helper_spec.rb b/spec/helpers/operating_times_helper_spec.rb new file mode 100644 index 0000000..9077653 --- /dev/null +++ b/spec/helpers/operating_times_helper_spec.rb @@ -0,0 +1,11 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') + +describe OperatingTimesHelper do + + #Delete this example and add some real ones or delete this file + it "is included in the helper object" do + included_modules = (class << helper; self; end).send :included_modules + included_modules.should include(OperatingTimesHelper) + end + +end diff --git a/spec/helpers/places_helper_spec.rb b/spec/helpers/places_helper_spec.rb new file mode 100644 index 0000000..c5aa022 --- /dev/null +++ b/spec/helpers/places_helper_spec.rb @@ -0,0 +1,11 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') + +describe PlacesHelper do + + #Delete this example and add some real ones or delete this file + it "is included in the helper object" do + included_modules = (class << helper; self; end).send :included_modules + included_modules.should include(PlacesHelper) + end + +end diff --git a/spec/models/operating_time_spec.rb b/spec/models/operating_time_spec.rb new file mode 100644 index 0000000..f1227da --- /dev/null +++ b/spec/models/operating_time_spec.rb @@ -0,0 +1,12 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') + +describe OperatingTime do + before(:each) do + @valid_attributes = { + } + end + + it "should create a new instance given valid attributes" do + OperatingTime.create!(@valid_attributes) + end +end diff --git a/spec/models/place_spec.rb b/spec/models/place_spec.rb new file mode 100644 index 0000000..646bbe8 --- /dev/null +++ b/spec/models/place_spec.rb @@ -0,0 +1,12 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') + +describe Place do + before(:each) do + @valid_attributes = { + } + end + + it "should create a new instance given valid attributes" do + Place.create!(@valid_attributes) + end +end diff --git a/spec/rcov.opts b/spec/rcov.opts new file mode 100644 index 0000000..baf694c --- /dev/null +++ b/spec/rcov.opts @@ -0,0 +1,2 @@ +--exclude "spec/*,gems/*" +--rails \ No newline at end of file diff --git a/spec/routing/operating_times_routing_spec.rb b/spec/routing/operating_times_routing_spec.rb new file mode 100644 index 0000000..d81485b --- /dev/null +++ b/spec/routing/operating_times_routing_spec.rb @@ -0,0 +1,63 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') + +describe OperatingTimesController do + describe "route generation" do + it "maps #index" do + route_for(:controller => "operating_times", :action => "index").should == "/operating_times" + end + + it "maps #new" do + route_for(:controller => "operating_times", :action => "new").should == "/operating_times/new" + end + + it "maps #show" do + route_for(:controller => "operating_times", :action => "show", :id => "1").should == "/operating_times/1" + end + + it "maps #edit" do + route_for(:controller => "operating_times", :action => "edit", :id => "1").should == "/operating_times/1/edit" + end + + it "maps #create" do + route_for(:controller => "operating_times", :action => "create").should == {:path => "/operating_times", :method => :post} + end + + it "maps #update" do + route_for(:controller => "operating_times", :action => "update", :id => "1").should == {:path =>"/operating_times/1", :method => :put} + end + + it "maps #destroy" do + route_for(:controller => "operating_times", :action => "destroy", :id => "1").should == {:path =>"/operating_times/1", :method => :delete} + end + end + + describe "route recognition" do + it "generates params for #index" do + params_from(:get, "/operating_times").should == {:controller => "operating_times", :action => "index"} + end + + it "generates params for #new" do + params_from(:get, "/operating_times/new").should == {:controller => "operating_times", :action => "new"} + end + + it "generates params for #create" do + params_from(:post, "/operating_times").should == {:controller => "operating_times", :action => "create"} + end + + it "generates params for #show" do + params_from(:get, "/operating_times/1").should == {:controller => "operating_times", :action => "show", :id => "1"} + end + + it "generates params for #edit" do + params_from(:get, "/operating_times/1/edit").should == {:controller => "operating_times", :action => "edit", :id => "1"} + end + + it "generates params for #update" do + params_from(:put, "/operating_times/1").should == {:controller => "operating_times", :action => "update", :id => "1"} + end + + it "generates params for #destroy" do + params_from(:delete, "/operating_times/1").should == {:controller => "operating_times", :action => "destroy", :id => "1"} + end + end +end diff --git a/spec/routing/places_routing_spec.rb b/spec/routing/places_routing_spec.rb new file mode 100644 index 0000000..90e27cb --- /dev/null +++ b/spec/routing/places_routing_spec.rb @@ -0,0 +1,63 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') + +describe PlacesController do + describe "route generation" do + it "maps #index" do + route_for(:controller => "places", :action => "index").should == "/places" + end + + it "maps #new" do + route_for(:controller => "places", :action => "new").should == "/places/new" + end + + it "maps #show" do + route_for(:controller => "places", :action => "show", :id => "1").should == "/places/1" + end + + it "maps #edit" do + route_for(:controller => "places", :action => "edit", :id => "1").should == "/places/1/edit" + end + + it "maps #create" do + route_for(:controller => "places", :action => "create").should == {:path => "/places", :method => :post} + end + + it "maps #update" do + route_for(:controller => "places", :action => "update", :id => "1").should == {:path =>"/places/1", :method => :put} + end + + it "maps #destroy" do + route_for(:controller => "places", :action => "destroy", :id => "1").should == {:path =>"/places/1", :method => :delete} + end + end + + describe "route recognition" do + it "generates params for #index" do + params_from(:get, "/places").should == {:controller => "places", :action => "index"} + end + + it "generates params for #new" do + params_from(:get, "/places/new").should == {:controller => "places", :action => "new"} + end + + it "generates params for #create" do + params_from(:post, "/places").should == {:controller => "places", :action => "create"} + end + + it "generates params for #show" do + params_from(:get, "/places/1").should == {:controller => "places", :action => "show", :id => "1"} + end + + it "generates params for #edit" do + params_from(:get, "/places/1/edit").should == {:controller => "places", :action => "edit", :id => "1"} + end + + it "generates params for #update" do + params_from(:put, "/places/1").should == {:controller => "places", :action => "update", :id => "1"} + end + + it "generates params for #destroy" do + params_from(:delete, "/places/1").should == {:controller => "places", :action => "destroy", :id => "1"} + end + end +end diff --git a/spec/spec.opts b/spec/spec.opts new file mode 100644 index 0000000..391705b --- /dev/null +++ b/spec/spec.opts @@ -0,0 +1,4 @@ +--colour +--format progress +--loadby mtime +--reverse diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..0d10446 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,47 @@ +# This file is copied to ~/spec when you run 'ruby script/generate rspec' +# from the project root directory. +ENV["RAILS_ENV"] ||= 'test' +require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT) +require 'spec/autorun' +require 'spec/rails' + +Spec::Runner.configure do |config| + # If you're not using ActiveRecord you should remove these + # lines, delete config/database.yml and disable :active_record + # in your config/boot.rb + config.use_transactional_fixtures = true + config.use_instantiated_fixtures = false + config.fixture_path = RAILS_ROOT + '/spec/fixtures/' + + # == Fixtures + # + # You can declare fixtures for each example_group like this: + # describe "...." do + # fixtures :table_a, :table_b + # + # Alternatively, if you prefer to declare them only once, you can + # do so right here. Just uncomment the next line and replace the fixture + # names with your fixtures. + # + # config.global_fixtures = :table_a, :table_b + # + # If you declare global fixtures, be aware that they will be declared + # for all of your examples, even those that don't use them. + # + # You can also declare which fixtures to use (for example fixtures for test/fixtures): + # + # config.fixture_path = RAILS_ROOT + '/spec/fixtures/' + # + # == Mock Framework + # + # RSpec uses it's own mocking framework by default. If you prefer to + # use mocha, flexmock or RR, uncomment the appropriate line: + # + # config.mock_with :mocha + # config.mock_with :flexmock + # config.mock_with :rr + # + # == Notes + # + # For more information take a look at Spec::Runner::Configuration and Spec::Runner +end diff --git a/spec/views/operating_times/edit.html.erb_spec.rb b/spec/views/operating_times/edit.html.erb_spec.rb new file mode 100644 index 0000000..2064e9d --- /dev/null +++ b/spec/views/operating_times/edit.html.erb_spec.rb @@ -0,0 +1,20 @@ +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') + +describe "/operating_times/edit.html.erb" do + include OperatingTimesHelper + + before(:each) do + assigns[:operating_time] = @operating_time = stub_model(OperatingTime, + :new_record? => false + ) + end + + it "renders the edit operating_time form" do + render + + response.should have_tag("form[action=#{operating_time_path(@operating_time)}][method=post]") do + end + end +end + + diff --git a/spec/views/operating_times/index.html.erb_spec.rb b/spec/views/operating_times/index.html.erb_spec.rb new file mode 100644 index 0000000..d29de81 --- /dev/null +++ b/spec/views/operating_times/index.html.erb_spec.rb @@ -0,0 +1,17 @@ +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') + +describe "/operating_times/index.html.erb" do + include OperatingTimesHelper + + before(:each) do + assigns[:operating_times] = [ + stub_model(OperatingTime), + stub_model(OperatingTime) + ] + end + + it "renders a list of operating_times" do + render + end +end + diff --git a/spec/views/operating_times/new.html.erb_spec.rb b/spec/views/operating_times/new.html.erb_spec.rb new file mode 100644 index 0000000..4abe237 --- /dev/null +++ b/spec/views/operating_times/new.html.erb_spec.rb @@ -0,0 +1,20 @@ +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') + +describe "/operating_times/new.html.erb" do + include OperatingTimesHelper + + before(:each) do + assigns[:operating_time] = stub_model(OperatingTime, + :new_record? => true + ) + end + + it "renders new operating_time form" do + render + + response.should have_tag("form[action=?][method=post]", operating_times_path) do + end + end +end + + diff --git a/spec/views/operating_times/show.html.erb_spec.rb b/spec/views/operating_times/show.html.erb_spec.rb new file mode 100644 index 0000000..239a2fb --- /dev/null +++ b/spec/views/operating_times/show.html.erb_spec.rb @@ -0,0 +1,13 @@ +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') + +describe "/operating_times/show.html.erb" do + include OperatingTimesHelper + before(:each) do + assigns[:operating_time] = @operating_time = stub_model(OperatingTime) + end + + it "renders attributes in <p>" do + render + end +end + diff --git a/spec/views/places/edit.html.erb_spec.rb b/spec/views/places/edit.html.erb_spec.rb new file mode 100644 index 0000000..2b8f62b --- /dev/null +++ b/spec/views/places/edit.html.erb_spec.rb @@ -0,0 +1,20 @@ +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') + +describe "/places/edit.html.erb" do + include PlacesHelper + + before(:each) do + assigns[:place] = @place = stub_model(Place, + :new_record? => false + ) + end + + it "renders the edit place form" do + render + + response.should have_tag("form[action=#{place_path(@place)}][method=post]") do + end + end +end + + diff --git a/spec/views/places/index.html.erb_spec.rb b/spec/views/places/index.html.erb_spec.rb new file mode 100644 index 0000000..f327ad3 --- /dev/null +++ b/spec/views/places/index.html.erb_spec.rb @@ -0,0 +1,17 @@ +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') + +describe "/places/index.html.erb" do + include PlacesHelper + + before(:each) do + assigns[:places] = [ + stub_model(Place), + stub_model(Place) + ] + end + + it "renders a list of places" do + render + end +end + diff --git a/spec/views/places/new.html.erb_spec.rb b/spec/views/places/new.html.erb_spec.rb new file mode 100644 index 0000000..ec489df --- /dev/null +++ b/spec/views/places/new.html.erb_spec.rb @@ -0,0 +1,20 @@ +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') + +describe "/places/new.html.erb" do + include PlacesHelper + + before(:each) do + assigns[:place] = stub_model(Place, + :new_record? => true + ) + end + + it "renders new place form" do + render + + response.should have_tag("form[action=?][method=post]", places_path) do + end + end +end + + diff --git a/spec/views/places/show.html.erb_spec.rb b/spec/views/places/show.html.erb_spec.rb new file mode 100644 index 0000000..c9a1097 --- /dev/null +++ b/spec/views/places/show.html.erb_spec.rb @@ -0,0 +1,13 @@ +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') + +describe "/places/show.html.erb" do + include PlacesHelper + before(:each) do + assigns[:place] = @place = stub_model(Place) + end + + it "renders attributes in <p>" do + render + end +end +
michaelansel/dukenow
8b3bcc11cd492b62d4739b88de801195bfa25218
Manipulate OperatingTimes as Time objects everywhere possible instead of using midnight offsets; Fix unit tests to run between 11PM and 1AM
diff --git a/app/helpers/places_helper.rb b/app/helpers/places_helper.rb index b3d39f6..cf09357 100644 --- a/app/helpers/places_helper.rb +++ b/app/helpers/places_helper.rb @@ -1,139 +1,147 @@ module PlacesHelper # TODO: clean and remove def settimes - @startTime = 0 # hard coded midnight start time for window (for dev/testing only) - @length = 24.hours - 1 # 24 hour window - @endTime = @startTime + @length + length + end + def startTime + @startTime ||= Date.today.midnight + end + def endTime + @endTime ||= (Date.today + 1).midnight + end + def length + @length ||= endTime - startTime end def time_block_style(time_block_or_start_offset,end_offset = nil, opts = {}) - settimes - # Accept "time_block_style(time_block,:direction => :vertical)" if end_offset.class == Hash and opts == {} opts = end_offset end_offset = nil end - # TODO: There has GOT to be a more DRY way to code this! - direction = :horizontal - if opts[:direction] - case opts[:direction] - when :vertical - direction = :vertical - when :horizontal - direction = :horizontal - end + direction = :vertical if opts[:direction] == :vertical + direction = :horizontal if opts[:direction] == :horizontal + direction ||= :horizontal + + if opts[:day] != nil + @startTime = opts[:day].midnight + @endTime = startTime + 1.days end + settimes if end_offset.nil? if time_block_or_start_offset.class == OperatingTime - open = time_block_or_start_offset.opensAt.offset - close = time_block_or_start_offset.closesAt.offset + # Generate style for OperatingTime object + open = time_block_or_start_offset.opensAt + close = time_block_or_start_offset.closesAt else return time_label_style(time_block_or_start_offset) end else - open = time_block_or_start_offset - close = end_offset + # Generate style for block spanning given time range + open = startTime.midnight + time_block_or_start_offset + close = startTime.midnight + end_offset end - offset = (open - @startTime) * 100.0 / @length - size = (close - open) * 100.0 / @length + if open >= startTime and close <= endTime + offset = (open - startTime) * 100.0 / length + size = (close - open) * 100.0 / length + + elsif open >= startTime and close >= endTime + offset = (open - startTime) * 100.0 / length + size = (endTime - open) * 100.0 / length + end case direction when :horizontal "left: #{offset.to_s}%; width: #{size.to_s}%;" when :vertical "top: #{offset.to_s}%; height: #{size.to_s}%;" else "" end end # TODO: clean and remove def time_label_style(at) settimes case at when Time time = at.hour.hours + at.min.minutes when Integer,Fixnum,Float time = at.to_i.hours end - left = (time - @startTime) * 100.0 / @length + left = (time - startTime) * 100.0 / length "left: #{left.to_s}%;" end # TODO: clean and remove def vertical_now_indicator(at=Time.now) settimes offset = 48; # offset to beginning of dayGraph == width of data cells - start = (at.hour.hours + at.min.minutes) * 100.0 / @length + start = (at.hour.hours + at.min.minutes) * 100.0 / length start = (100.0 - offset) * start/100.0 + offset # incorporate offset "<div class=\"verticalNowIndicator\" style=\"left:#{start.to_s}%;\"></div>" end # TODO: clean and remove def now_indicator(at=Time.now, opts={}) settimes - start = (at.hour.hours + at.min.minutes) * 100.0 / @length + start = (at.hour.hours + at.min.minutes) * 100.0 / length "<div class=\"nowIndicator\" style=\"top:#{start.to_s}%;\"></div>" end def placeClasses(place) classes = ["place"] if place.open? classes << "open" else classes << "closed" end classes += place.tag_list.split(/,/) classes.join(' ') end def short_time_string(time) if time.min == 0 # time has no minutes - time.strftime('%I%p') + time.strftime('%I%p').sub(/^0+/,'') else # time has minutes - time.strftime('%I:%M%p') + time.strftime('%I:%M%p').sub(/^0+/,'') end end # Returns [words,time] -- both are strings def next_time(place, at=Time.now) - place.daySchedule.each do |schedule| + place.daySchedule(at).each do |schedule| # If the whole time period has already passed - next if schedule.opensAt.time(at) < at and - schedule.closesAt.time(at) < at + next if schedule.opensAt < at and + schedule.closesAt < at - if schedule.opensAt.time(at) <= at # Open now + if schedule.opensAt <= at # Open now # TODO: Handle late-night rollovers - time_string = short_time_string(schedule.closesAt.time(at)) - time_string = time_string.sub(/^0+/,'') - return ["Open until", time_string] + return ["Open until", short_time_string(schedule.closesAt)] end - if schedule.closesAt.time(at) >= at # Closed now - time_string = short_time_string(schedule.opensAt.time(at)) - time_string = time_string.sub(/^0+/,'') - return ["Opens at", time_string] + if schedule.closesAt >= at # Closed now + return ["Opens at", short_time_string(schedule.opensAt)] end return "ERROR in next_time" # TODO: How could we possibly get here? end return "","Closed" # No more state time changes for today end end diff --git a/app/models/operating_time.rb b/app/models/operating_time.rb index 09e69d3..54d3ea2 100644 --- a/app/models/operating_time.rb +++ b/app/models/operating_time.rb @@ -1,134 +1,153 @@ class OperatingTime < ActiveRecord::Base - #require RAILS_ROOT + '/lib/relative_time.rb' - belongs_to :place validates_presence_of :place_id validates_associated :place # Base flags SUNDAY_FLAG = 0b00000000001 MONDAY_FLAG = 0b00000000010 TUESDAY_FLAG = 0b00000000100 WEDNESDAY_FLAG = 0b00000001000 THURSDAY_FLAG = 0b00000010000 FRIDAY_FLAG = 0b00000100000 SATURDAY_FLAG = 0b00001000000 SPECIAL_FLAG = 0b00010000000 DINE_IN_FLAG = 0b00100000000 DELIVERY_FLAG = 0b01000000000 # Combinations ALLDAYS_FLAG = 0b00001111111 WEEKDAYS_FLAG = 0b00000111110 WEEKENDS_FLAG = 0b00001000001 ALL_FLAGS = 0b01111111111 def initialize(params = nil) super # Default values self.flags = 0 unless self.flags self.startDate = Time.now unless self.startDate self.endDate = Time.now unless self.endDate + @at = Time.now end def length - closesAt.offset - opensAt.offset + closesAt - opensAt + end + + + def at + @at ||= Time.now + end + def at=(time) + @at = time end def special (self.flags & SPECIAL_FLAG) == SPECIAL_FLAG end # Input: isSpecial = true/false def special=(isSpecial) if isSpecial == true or isSpecial == "true" or isSpecial == 1 self.flags = self.flags | SPECIAL_FLAG elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 self.flags = self.flags & ~SPECIAL_FLAG end end + # Returns a Time object representing the beginning of this OperatingTime def opensAt - @relativeOpensAt = RelativeTime.new(self,:opensAt) if @relativeOpensAt.nil? - @relativeOpensAt + relativeOpensAt.time(at) end + # Returns a RelativeTime object representing the beginning of this OperatingTime + def relativeOpensAt + @relativeOpensAt ||= RelativeTime.new(self,:opensAt) if @relativeOpensAt.nil? + @relativeOpensAt + end; protected :relativeOpensAt + # Sets the beginning of this OperatingTime # Input: params = { :hour => 12, :minute => 45 } def opensAt=(params = {}) params[:hour] = 0 if params[:hour].nil? params[:minute] = 0 if params[:minute].nil? - opensAt.offset = params[:hour].to_i.hours + params[:minute].to_i.minutes + relativeOpensAt.offset = params[:hour].to_i.hours + params[:minute].to_i.minutes end + # Returns a Time object representing the end of this OperatingTime def closesAt - @relativeClosesAt = RelativeTime.new(self,:closesAt) if @relativeClosesAt.nil? - @relativeClosesAt + relativeClosesAt.time(at) end + # Returns a RelativeTime object representing the beginning of this OperatingTime + def relativeClosesAt + @relativeClosesAt ||= RelativeTime.new(self,:closesAt) if @relativeClosesAt.nil? + @relativeClosesAt + end; protected :relativeClosesAt + # Sets the end of this OperatingTime # Input: params = { :hour => 12, :minute => 45 } def closesAt=(params = {}) - closesAt.offset = params[:hour].to_i.hours + params[:minute].to_i.minutes + relativeClosesAt.offset = params[:hour].to_i.hours + params[:minute].to_i.minutes end # Hash mapping day of week (Symbol) to valid(true)/invalid(false) def daysOfWeekHash a=daysOfWeek daysOfWeek = 127 if a.nil? daysOfWeek = a { :sunday => (daysOfWeek & 1) > 0, # Sunday :monday => (daysOfWeek & 2) > 0, # Monday :tuesday => (daysOfWeek & 4) > 0, # Tuesday :wednesday => (daysOfWeek & 8) > 0, # Wednesday :thursday => (daysOfWeek & 16) > 0, # Thursday :friday => (daysOfWeek & 32) > 0, # Friday :saturday => (daysOfWeek & 64) > 0} # Saturday end # Array beginning with Sunday of valid(true)/inactive(false) values def daysOfWeekArray a=daysOfWeek daysOfWeek = 127 if a.nil? daysOfWeek = a [ daysOfWeek & 1 > 0, # Sunday daysOfWeek & 2 > 0, # Monday daysOfWeek & 4 > 0, # Tuesday daysOfWeek & 8 > 0, # Wednesday daysOfWeek & 16 > 0, # Thursday daysOfWeek & 32 > 0, # Friday daysOfWeek & 64 > 0] # Saturday end # Days of week valid (sum of flags) def daysOfWeek sum = 0 7.times do |i| sum += ( (flags & ALLDAYS_FLAG) & (1 << i) ) end sum end # Human-readable string of days of week valid def daysOfWeekString str = "" str += "Su" if flags & SUNDAY_FLAG > 0 str += "M" if flags & MONDAY_FLAG > 0 str += "Tu" if flags & TUESDAY_FLAG > 0 str += "W" if flags & WEDNESDAY_FLAG > 0 str += "Th" if flags & THURSDAY_FLAG > 0 str += "F" if flags & FRIDAY_FLAG > 0 str += "Sa" if flags & SATURDAY_FLAG > 0 str end def to_xml(params) super(params.merge({:only => [:id, :place_id, :flags], :methods => [ :opensAt, :closesAt, :startDate, :endDate ]})) end end diff --git a/app/models/place.rb b/app/models/place.rb index 3f1b3de..bfc585e 100644 --- a/app/models/place.rb +++ b/app/models/place.rb @@ -1,64 +1,91 @@ class Place < ActiveRecord::Base has_many :operating_times acts_as_taggable_on :tags def special_operating_times - OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0", id] ) + OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0", id], :order => "startDate ASC, opensAt ASC" ) end def regular_operating_times - OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0", id] ) + OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0", id], :order => "startDate ASC, opensAt ASC" ) end - def window_schedule(startAt,endAt) - #TODO Returns the schedule for a specified time window + # Returns an array of OperatingTimes + def schedule(startAt,endAt) + # TODO Returns the schedule for a specified time window + # TODO Handle events starting within the range but ending outside of it? + regular_times = regular_operating_times.select do |ot| + ot.at = startAt + ot.startDate ||= startAt.to_date + ot.endDate ||= endAt.to_date + (ot.startDate <= startAt.to_date and ot.endDate >= endAt.to_date) and + ((ot.opensAt >= startAt and ot.opensAt <= endAt) or (ot.closesAt >= startAt and ot.closesAt <= endAt)) + end + special_times = special_operating_times.select do |ot| + ot.at = startAt + ot.startDate ||= startAt.to_date + ot.endDate ||= endAt.to_date + (ot.startDate <= startAt.to_date and ot.endDate >= endAt.to_date) and + ((ot.opensAt >= startAt and ot.opensAt <= endAt) or (ot.closesAt >= startAt and ot.closesAt <= endAt)) + end + + # TODO Handle combinations (i.e. part special, part regular) + special_times == [] ? regular_times : special_times end def daySchedule(at = Date.today) + at = at.to_date if at.class == Time or at.class == DateTime + + schedule = schedule(at.midnight,(at+1).midnight) + schedule = schedule.select {|ot| (ot.flags & 1<<at.wday) > 0 } + schedule.each {|t| t.at = at } + +=begin # Find all operating times for this place that are: # - Special # - Are effective on date "at" (between startDate and endDate) # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) > 0 and (flags & ?) > 0 and startDate <= ? and endDate >= ?", id, 1 << at.wday, at.to_s, at.to_s] ) # If we don't have any special operating times if schedule == [] # Find all operating times for this place that are: # - NOT Special # - Are effective on weekday "at.wday" schedule = OperatingTime.find( :all, :conditions => ["place_id = ? and (flags & #{OperatingTime::SPECIAL_FLAG}) == 0 and (flags & ?) > 0", id, 1 << at.wday] ) end - schedule.sort{|a,b|a.opensAt.offset <=> b.opensAt.offset} + schedule.sort{|a,b|a.opensAt <=> b.opensAt} +=end end def currentSchedule(at = Time.now) current_schedule = nil - daySchedule.each do |optime| - if optime.opensAt.time(at) < at and - optime.closesAt.time(at) > at + daySchedule(at).each do |optime| + if optime.opensAt <= at and + optime.closesAt >= at #RAILS_DEFAULT_LOGGER.debug "Opens At: #{optime.opensAt.time(at).to_s}" #RAILS_DEFAULT_LOGGER.debug "Closes At: #{optime.closesAt.time(at).to_s}" current_schedule = optime end end current_schedule end def open?(at = Time.now) a = currentSchedule(at) return a ? true : false end # Alias for <tt>open?</tt> def open(at = Time.now); open? at ; end def to_json(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end def to_xml(params) super(params.merge({:only => [:id, :name, :location, :phone], :methods => [ :open ]})) end end diff --git a/app/views/operating_times/_entryform.html.erb b/app/views/operating_times/_entryform.html.erb index a2c8d46..2f06e22 100644 --- a/app/views/operating_times/_entryform.html.erb +++ b/app/views/operating_times/_entryform.html.erb @@ -1,74 +1,74 @@ <p> <%= f.label :place %><br /> <%= f.collection_select :place_id, @places, :id, :name %> </p> <p> <%= f.label :details %><br /> <%= f.text_field :details %><br /> </p> <p> <%= f.label :opensAt %><br /> - <%= select_time f.object.opensAt.time, :prefix => "#{f.object_name}[opensAt]" %> + <%= select_time f.object.opensAt, :prefix => "#{f.object_name}[opensAt]" %> </p> <p> <%= f.label :closesAt %><br /> - <%= select_time f.object.closesAt.time, :prefix => "#{f.object_name}[closesAt]" %> + <%= select_time f.object.closesAt, :prefix => "#{f.object_name}[closesAt]" %> </p> <p> <%= f.label :daysOfWeek %><br /> <table style="height:+3em;"><tr> <% Date::DAYNAMES.each_index do |i| %> <td onclick="toggleCheckbox('daysOfWeek_<%=h Date::DAYNAMES[i].to_s.capitalize %>')"> <label id="daysOfWeek_<%=h Date::DAYNAMES[i].to_s.capitalize%>" style="font-weight:<%= f.object.daysOfWeekArray[i] ? "bold" : "normal" %>;font-size:<%= f.object.daysOfWeekArray[i] ? "+2em" : "+1em" %>;"> <%=h Date::DAYNAMES[i].to_s.capitalize %> <%= check_box_tag "#{f.object_name}[daysOfWeekHash][]", Date::DAYNAMES[i].downcase.to_sym, f.object.daysOfWeekArray[i], :style => 'display:none;' %> </label> </span> <% end %> </tr></table> </p> <script> function toggleCheckbox(element_id) { a=document.getElementById(element_id); b=document.getElementById(element_id).getElementsByTagName('input')[0]; if(b.checked) { a.style['fontWeight']='bold'; a.style['fontSize']='+2em'; } else { a.style['fontWeight']='normal'; a.style['fontSize']='+1em'; } } function updateSpecialForm() { if(document.getElementById("operating_time_special").checked) { <%= visual_effect(:appear, "specialForm", :duration => 0) %> } else { <%= visual_effect(:fade, "specialForm", :duration => 0) %> } } </script> <p> <label>Special? <%= f.check_box :special, {:onchange => 'updateSpecialForm()'}, "true", "false" %> </label> </p> <span id="specialForm" style="display:<%= f.object.special ? "" : "none" %>;"> <p> <%= f.label :start %><br /> <%= f.date_select :startDate %> </p> <p> <%= f.label :end %><br /> <%= f.date_select :endDate %> </p> </span> diff --git a/app/views/places/index.html.erb b/app/views/places/index.html.erb index 90cbd0d..c26ca09 100644 --- a/app/views/places/index.html.erb +++ b/app/views/places/index.html.erb @@ -1,128 +1,110 @@ <% @places.each do |place| %> <% if RAILS_ENV == 'development' %> <!-- TODO: Remove the following comment (for debugging only) --> <!-- <%= place.inspect %> --> <% end %> - <div class="<%=h placeClasses place %>" id="place<%=h place.id %>"> + <div class="<%=h placeClasses(place) %>" id="place<%=h place.id %>"> <div class="place_short"> <a class="place_name" title="<%=h place.name %>" onclick="toggle_drawer('place<%=h place.id %>',event);return false;" href="<%=h url_for(place) %>"> <span class="bubble-left"></span> <span class="name"><%=h place.name %></span> <span class="bubble-right"></span> </a> <div class="next_time"> <% next_time_words,next_time_time = next_time place %> <div class="next_time_words"><%=h next_time_words %></div> <div class="next_time_time"><%=h next_time_time %></div> </div> </div> <div class="place_long" style="display:none;"> <div class="details"> <div class="location">Location: <span><%=h place.location %></span></div> <div class="phone">Phone: <span><%=h place.phone %></span></div> <%= link_to 'More Info', place, :class => "more_info" %> <a class="weekly_schedule" href="#weekly_schedule">Weekly Schedule</a> <div class="tags"> <span>Tags</span> <% if place.tags != [] %> <% place.tags[0..-2].each do |tag| %> <a class="tag" href="#tag=<%=h tag.name %>"><%=h tag.name %></a>, <% end %> <a class="tag" href="#tag=<%=h place.tags[-1].name %>"><%=h place.tags[-1].name %></a> <% end # if place.tags != [] %> </div> </div> <!-- TODO: Load schedule info to generate timeblocks --> <div class="schedule"><div class="inner-schedule"> <div class="nowindicator"></div> <!-- // Test timeblock <div class="timeblock" id="timeblock_<%=h place.id %>_0" style="left: 0%; width: 100%;"> <div class="bubble-left"></div> <div class="bubble-middle"></div> <div class="bubble-right"></div> </div> --> <% place.daySchedule.each do |schedule| %> <div class="timeblock" id="timeblock_<%=h place.id %>_<%=h schedule.id %>" style="<%=h time_block_style(schedule) %>"> <div class="bubble-left"></div> <div class="bubble-middle"></div> <div class="bubble-right"></div> </div> <% end # place.daySchedule.each %> </div></div> <!-- div.schedule, div.inner-schedule --> </div> </div> <% end # @places.each %> <% =begin %> <!-- TODO: Reimplement under new design --> <div class="tagCloud"> <div style="font-size:2em;font-weight:bold;text-align:center;line-height:1.5em;">Tags</div> <div id="selectedTags" style="border-top: 1px solid black; padding-top:5px;"> <% @selected_tags.each do |tag_name| %> <%= link_to tag_name, { :action => :tag, :id => tag_name }, :id => "selected_tag_#{tag_name}", :class => "selectedTag", :onclick => "handleTagClick('#{h tag_name}',event);return false;" %> <% end %> </div> <script> // <%= @selected_tags.inspect %> <% if not @selected_tags.nil? %> document.lockedTags = <%= @selected_tags.join(", ").inspect %>; <% else %> document.lockedTags = ""; <% end %> </script> <div style="border-top: 1px solid black;padding-top:5px;"> <% tag_cloud @tag_counts, %w(size1 size2 size3 size4 size5 size6) do |tag, css_class| %> <%= link_to tag.name, { :action => :tag, :id => tag.name }, :id => "tag_#{tag.name}", :class => css_class, :onclick => "handleTagClick('#{h tag.name}',event);return false;" %> <% end %> </div> </div> <!-- TODO: Reimplement under new design --> <div style="position:absolute; right:0; top:0;"> <%= link_to "Yesterday", :at => Date.today - 1.day %><br/> <%= link_to "Today", :at => Date.today %><br/> <%= link_to "Tomorrow", :at => Date.today + 1.day %><br/> <%= link_to Date::DAYNAMES[(Date.today + 2.day).wday], :at => Date.today + 2.day %><br/> </div> -<!-- TODO: Reimplement under new design --> -<%= vertical_now_indicator(Time.now) %> - - - - -<!-- TODO: Reimplement under new design --> -<% for place in @places %> - <div class="dayGraph"><div class="data"> - <% place.daySchedule(@at).each do |time_block| -%> - <div class="timeblock" style="<%= time_block_style(time_block) %>"></div> - <% end -%> - </div></div> -<% end %> - - - - <% =end %> diff --git a/app/views/places/show.html.erb b/app/views/places/show.html.erb index 643da51..fe60f2e 100644 --- a/app/views/places/show.html.erb +++ b/app/views/places/show.html.erb @@ -1,76 +1,76 @@ <%= stylesheet_link_tag 'places' %> <p> <b>Name:</b> <%=h @place.name %> </p> <p> <b>Location:</b> <%=h @place.location %> </p> <p> <b>Phone:</b> <%=h @place.phone %> </p> <p> <b>Tags:</b> <%=h @place.tag_list %> </p> <p> <b>Open Now?</b> <%=h (@place.open?(@at) ? "Yes" : "No") %> </p> <p> <b><%= link_to 'All Operating Times', '/operating_times/place/'[email protected]_s %></b> </p> <p> <b>Schedule for this week:</b><br/> <div class="weekSchedule"> <div class="header"> <div class="labelColumn"></div> <% 7.times do |i| %> <div class="dayColumn"> <%= Date::DAYNAMES[(@at + i.days).wday] %> </div> <% end %> </div> <div class="data"> <div class="labelColumn"> <% 24.times do |hour| -%> <div class="color<%= hour % 2 + 1 %>" class="timeblock" style="<%= time_block_style(hour.hours,(hour+1).hours, :direction => :vertical) %> z-index: 2;"><%= hour.to_s %></div> <% end -%> <%= now_indicator %> </div> <% 7.times do |i| %> <div class="dayColumn"> <%= now_indicator if i == 0 %> <% @place.daySchedule(@at + i.days).each do |schedule| %> - <div class="timeblock" style="<%= time_block_style(schedule, :direction => :vertical) %>"> - <div class="opensat"><%=h schedule.opensAt %></div> + <div class="timeblock" style="<%= time_block_style(schedule, :day => (@at+i.days), :direction => :vertical) %>"> + <div class="opensat"><%=h short_time_string(schedule.opensAt) %></div> <div class="details"><%=h schedule.details if schedule.length >= 2.hours %></div> - <div class="closesat"><%=h schedule.closesAt %></div> - <% link_to "#{schedule.opensAt.to_s} - #{schedule.closesAt.to_s}", schedule %> + <div class="closesat"><%=h short_time_string(schedule.closesAt) %></div> + <%#= link_to "#{short_time_string(schedule.opensAt)} - #{short_time_string(schedule.closesAt)}", schedule %> </div> <% end %> </div> <% end %> </div> </div> </p> <%= link_to 'Edit', edit_place_path(@place) %> | <%= link_to 'Back', places_path %> diff --git a/test/fixtures/operating_times.yml b/test/fixtures/operating_times.yml index ef32c4b..b38bdad 100644 --- a/test/fixtures/operating_times.yml +++ b/test/fixtures/operating_times.yml @@ -1,28 +1,25 @@ # Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html -<% nowSeconds = Time.now.hour.hours + Time.now.min.minutes %> - - openNow: place: greathall - opensAt: <%= nowSeconds - 1.hours %> - closesAt: <%= nowSeconds + 1.hours %> + opensAt: <%= RelativeTime._getMidnightOffset(Time.now - 1.hours) %> + closesAt: <%= RelativeTime._getMidnightOffset(Time.now + 1.hours) %> details: Open right now for dine-in (not special) flags: <%= OperatingTime::ALLDAYS_FLAG | OperatingTime::DINE_IN_FLAG %> openNowDifferentWeekday: place: greathall - opensAt: <%= nowSeconds - 1.hours %> - closesAt: <%= nowSeconds + 1.hours %> + opensAt: <%= RelativeTime._getMidnightOffset(Time.now - 1.hours) %> + closesAt: <%= RelativeTime._getMidnightOffset(Time.now + 1.hours) %> details: Open right now for dine-in, but on a different day of the week (not special) flags: <%= OperatingTime::DINE_IN_FLAG %> openNowSpecial: place: greathall - opensAt: <%= nowSeconds - 1.hours %> - closesAt: <%= nowSeconds + 1.hours %> + opensAt: <%= RelativeTime._getMidnightOffset(Time.now - 1.hours) %> + closesAt: <%= RelativeTime._getMidnightOffset(Time.now + 1.hours) %> startDate: <%= Date.today - 1.day %> endDate: <%= Date.today + 1.day %> details: Open right now for dine-in (not special) flags: <%= OperatingTime::ALLDAYS_FLAG | OperatingTime::DINE_IN_FLAG | OperatingTime::SPECIAL_FLAG %>
michaelansel/dukenow
75b4afaa6c38c0270b84a0eced3fef79c984e857
Break up RelativeTimes module because it is not reusable code; Monkey patch in "midnight" method for Date, Time, and DateTime
diff --git a/app/controllers/operating_times_controller.rb b/app/controllers/operating_times_controller.rb index 53a24a2..638b231 100644 --- a/app/controllers/operating_times_controller.rb +++ b/app/controllers/operating_times_controller.rb @@ -1,105 +1,137 @@ class OperatingTimesController < ApplicationController - include RelativeTimes::ControllerMethods # GET /operating_times # GET /operating_times.xml def index if params[:place_id] @operating_times = OperatingTime.find(:all, :conditions => ['place_id = ?',params[:place_id]]) else @operating_times = OperatingTime.find(:all) end request.format = :html if request.format == :iphone respond_to do |format| format.html # index.html.erb format.xml { render :xml => @operating_times } end end # GET /operating_times/1 # GET /operating_times/1.xml def show @operating_time = OperatingTime.find(params[:id]) request.format = :html if request.format == :iphone respond_to do |format| format.html # show.html.erb format.xml { render :xml => @operating_time } end end # GET /operating_times/new # GET /operating_times/new.xml def new @operating_time = OperatingTime.new @places = Place.find(:all, :order => "name ASC") request.format = :html if request.format == :iphone respond_to do |format| format.html # new.html.erb format.xml { render :xml => @operating_time } end end # GET /operating_times/1/edit def edit @operating_time = OperatingTime.find(params[:id]) @places = Place.find(:all, :order => "name ASC") request.format = :html if request.format == :iphone end # POST /operating_times # POST /operating_times.xml def create params[:operating_time] = operatingTimesFormHandler(params[:operating_time]) @operating_time = OperatingTime.new(params[:operating_time]) request.format = :html if request.format == :iphone respond_to do |format| if @operating_time.save flash[:notice] = 'OperatingTime was successfully created.' format.html { redirect_to(@operating_time) } format.xml { render :xml => @operating_time, :status => :created, :location => @operating_time } else format.html { render :action => "new" } format.xml { render :xml => @operating_time.errors, :status => :unprocessable_entity } end end end # PUT /operating_times/1 # PUT /operating_times/1.xml def update @operating_time = OperatingTime.find(params[:id]) params[:operating_time] = operatingTimesFormHandler(params[:operating_time]) request.format = :html if request.format == :iphone respond_to do |format| if @operating_time.update_attributes(params[:operating_time]) flash[:notice] = 'OperatingTime was successfully updated.' format.html { redirect_to(@operating_time) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @operating_time.errors, :status => :unprocessable_entity } end end end # DELETE /operating_times/1 # DELETE /operating_times/1.xml def destroy @operating_time = OperatingTime.find(params[:id]) @operating_time.destroy request.format = :html if request.format == :iphone respond_to do |format| format.html { redirect_to(operating_times_url) } format.xml { head :ok } end end + + + +## Helpers ## + def operatingTimesFormHandler(operatingTimesParams) +=begin + params[:regular_operating_time][:opensAtOffset] = + params[:regular_operating_time].delete('opensAtHour') * 3600 + + params[:regular_operating_time].delete('opensAtMinute') * 60 + + params[:regular_operating_time][:closesAtOffset] = + params[:regular_operating_time].delete('closesAtHour') * 3600 + + params[:regular_operating_time].delete('closesAtMinute') * 60 +=end + + if operatingTimesParams[:daysOfWeekHash] != nil + daysOfWeek = 0 + + operatingTimesParams[:daysOfWeekHash].each do |dayOfWeek| + daysOfWeek += 1 << Date::DAYNAMES.index(dayOfWeek.capitalize) + end + operatingTimesParams.delete('daysOfWeekHash') + + operatingTimesParams[:flags] = 0 if operatingTimesParams[:flags].nil? + operatingTimesParams[:flags] = operatingTimesParams[:flags] & ~OperatingTime::ALLDAYS_FLAG + operatingTimesParams[:flags] = operatingTimesParams[:flags] | daysOfWeek + end + + + + + return operatingTimesParams + end end diff --git a/app/models/operating_time.rb b/app/models/operating_time.rb index c2d2a9b..09e69d3 100644 --- a/app/models/operating_time.rb +++ b/app/models/operating_time.rb @@ -1,79 +1,134 @@ class OperatingTime < ActiveRecord::Base - require RAILS_ROOT + '/lib/relative_times.rb' - include RelativeTimes::InstanceMethods + #require RAILS_ROOT + '/lib/relative_time.rb' belongs_to :place validates_presence_of :place_id validates_associated :place # Base flags SUNDAY_FLAG = 0b00000000001 MONDAY_FLAG = 0b00000000010 TUESDAY_FLAG = 0b00000000100 WEDNESDAY_FLAG = 0b00000001000 THURSDAY_FLAG = 0b00000010000 FRIDAY_FLAG = 0b00000100000 SATURDAY_FLAG = 0b00001000000 SPECIAL_FLAG = 0b00010000000 DINE_IN_FLAG = 0b00100000000 DELIVERY_FLAG = 0b01000000000 # Combinations ALLDAYS_FLAG = 0b00001111111 WEEKDAYS_FLAG = 0b00000111110 WEEKENDS_FLAG = 0b00001000001 ALL_FLAGS = 0b01111111111 def initialize(params = nil) super # Default values self.flags = 0 unless self.flags self.startDate = Time.now unless self.startDate self.endDate = Time.now unless self.endDate end def length closesAt.offset - opensAt.offset end + def special (self.flags & SPECIAL_FLAG) == SPECIAL_FLAG end - + # Input: isSpecial = true/false def special=(isSpecial) if isSpecial == true or isSpecial == "true" or isSpecial == 1 self.flags = self.flags | SPECIAL_FLAG elsif isSpecial == false or isSpecial == "false" or isSpecial == 0 self.flags = self.flags & ~SPECIAL_FLAG end end + + def opensAt + @relativeOpensAt = RelativeTime.new(self,:opensAt) if @relativeOpensAt.nil? + @relativeOpensAt + end + # Input: params = { :hour => 12, :minute => 45 } + def opensAt=(params = {}) + params[:hour] = 0 if params[:hour].nil? + params[:minute] = 0 if params[:minute].nil? + opensAt.offset = params[:hour].to_i.hours + params[:minute].to_i.minutes + end + + + def closesAt + @relativeClosesAt = RelativeTime.new(self,:closesAt) if @relativeClosesAt.nil? + @relativeClosesAt + end + # Input: params = { :hour => 12, :minute => 45 } + def closesAt=(params = {}) + closesAt.offset = params[:hour].to_i.hours + params[:minute].to_i.minutes + end + + + # Hash mapping day of week (Symbol) to valid(true)/invalid(false) + def daysOfWeekHash + a=daysOfWeek + daysOfWeek = 127 if a.nil? + daysOfWeek = a + + { :sunday => (daysOfWeek & 1) > 0, # Sunday + :monday => (daysOfWeek & 2) > 0, # Monday + :tuesday => (daysOfWeek & 4) > 0, # Tuesday + :wednesday => (daysOfWeek & 8) > 0, # Wednesday + :thursday => (daysOfWeek & 16) > 0, # Thursday + :friday => (daysOfWeek & 32) > 0, # Friday + :saturday => (daysOfWeek & 64) > 0} # Saturday + end + + # Array beginning with Sunday of valid(true)/inactive(false) values + def daysOfWeekArray + a=daysOfWeek + daysOfWeek = 127 if a.nil? + daysOfWeek = a + + [ daysOfWeek & 1 > 0, # Sunday + daysOfWeek & 2 > 0, # Monday + daysOfWeek & 4 > 0, # Tuesday + daysOfWeek & 8 > 0, # Wednesday + daysOfWeek & 16 > 0, # Thursday + daysOfWeek & 32 > 0, # Friday + daysOfWeek & 64 > 0] # Saturday + end + + # Days of week valid (sum of flags) def daysOfWeek sum = 0 7.times do |i| sum += ( (flags & ALLDAYS_FLAG) & (1 << i) ) end sum end + # Human-readable string of days of week valid def daysOfWeekString str = "" str += "Su" if flags & SUNDAY_FLAG > 0 str += "M" if flags & MONDAY_FLAG > 0 str += "Tu" if flags & TUESDAY_FLAG > 0 str += "W" if flags & WEDNESDAY_FLAG > 0 str += "Th" if flags & THURSDAY_FLAG > 0 str += "F" if flags & FRIDAY_FLAG > 0 str += "Sa" if flags & SATURDAY_FLAG > 0 str end def to_xml(params) super(params.merge({:only => [:id, :place_id, :flags], :methods => [ :opensAt, :closesAt, :startDate, :endDate ]})) end end diff --git a/lib/date_time.rb b/lib/date_time.rb new file mode 100644 index 0000000..cda7fd0 --- /dev/null +++ b/lib/date_time.rb @@ -0,0 +1,23 @@ + + +module Midnight + def midnight + Time.mktime(year, month, day, 0, 0, 0); + end +end + + + +require 'date' +class Date + include Midnight +end + +require 'time' +class Time + include Midnight +end + +class DateTime + include Midnight +end diff --git a/lib/relative_time.rb b/lib/relative_time.rb new file mode 100644 index 0000000..7b9c465 --- /dev/null +++ b/lib/relative_time.rb @@ -0,0 +1,61 @@ +class RelativeTime + require 'time' + + def self._relativeTime(offset, baseTime = Time.now) + offset = 0 if offset.nil? + #offset = 86399 if offset >= 86400 + Time.local(baseTime.year, baseTime.month, baseTime.day, (offset/3600).to_i, ((offset % 3600)/60).to_i) + end + + def self._getMidnightOffset(time) + time = Time.now if time.nil? + time.hour * 3600 + time.min * 60 + end + + + def initialize(object,attribute) + @object = object + @attribute = attribute + end + + + def hour + (offset / 3600).to_i + end + def hour=(hour) + # hour_seconds + remainder_seconds + offset = (hour * 3600) + (offset % 3600) + end + + + def minute + ( (offset % 3600) / 60 ).to_i + end + def minute=(minute) + # hour_seconds + minute_seconds + remainder_seconds + offset = (hour * 3600) + (minute * 60) + (offset % 60) + end + + + def offset + @object.send(:read_attribute,@attribute) + end + def offset=(newOffset) + @object.send(:write_attribute,@attribute,newOffset) + end + + + def time(baseTime = Time.now) + RelativeTime._relativeTime(offset, baseTime) + end + def time=(newTime = Time.now) + RAILS_DEFAULT_LOGGER.debug "Updating offset using Time object: #{newTime.inspect} ; offset = #{RelativeTime._getMidnightOffset(newTime)}" + offset = RelativeTime._getMidnightOffset(newTime) + end + + + def to_s + '%02d:%02d' % [hour,minute] + time.to_s + end +end diff --git a/lib/relative_times.rb b/lib/relative_times.rb deleted file mode 100644 index 73cf6d2..0000000 --- a/lib/relative_times.rb +++ /dev/null @@ -1,148 +0,0 @@ -module RelativeTimes - module ClassMethods - require 'time' - - def _relativeTime(offset, baseTime = Time.now) - offset = 0 if offset.nil? - #offset = 86399 if offset >= 86400 - Time.local(baseTime.year, baseTime.month, baseTime.day, (offset/3600).to_i, ((offset % 3600)/60).to_i) - end - - def _getMidnightOffset(time) - time = Time.now if time.nil? - time.hour * 3600 + time.min * 60 - end - end - - module InstanceMethods - def opensAt - @relativeOpensAt = RelativeTime.new(self,:opensAt) if @relativeOpensAt.nil? - @relativeOpensAt - end - # Input: params = { :hour => 12, :minute => 45 } - def opensAt=(params = {}) - params[:hour] = 0 if params[:hour].nil? - params[:minute] = 0 if params[:minute].nil? - opensAt.offset = params[:hour].to_i.hours + params[:minute].to_i.minutes - end - - - def closesAt - @relativeClosesAt = RelativeTime.new(self,:closesAt) if @relativeClosesAt.nil? - @relativeClosesAt - end - def closesAt=(params = {}) - closesAt.offset = params[:hour].to_i.hours + params[:minute].to_i.minutes - end - - - - def daysOfWeekHash - a=daysOfWeek - daysOfWeek = 127 if a.nil? - daysOfWeek = a - - { :sunday => (daysOfWeek & 1) > 0, # Sunday - :monday => (daysOfWeek & 2) > 0, # Monday - :tuesday => (daysOfWeek & 4) > 0, # Tuesday - :wednesday => (daysOfWeek & 8) > 0, # Wednesday - :thursday => (daysOfWeek & 16) > 0, # Thursday - :friday => (daysOfWeek & 32) > 0, # Friday - :saturday => (daysOfWeek & 64) > 0} # Saturday - end - - def daysOfWeekArray - a=daysOfWeek - daysOfWeek = 127 if a.nil? - daysOfWeek = a - - [ daysOfWeek & 1 > 0, # Sunday - daysOfWeek & 2 > 0, # Monday - daysOfWeek & 4 > 0, # Tuesday - daysOfWeek & 8 > 0, # Wednesday - daysOfWeek & 16 > 0, # Thursday - daysOfWeek & 32 > 0, # Friday - daysOfWeek & 64 > 0] # Saturday - end - end - - module ControllerMethods - def operatingTimesFormHandler(operatingTimesParams) -=begin - params[:regular_operating_time][:opensAtOffset] = - params[:regular_operating_time].delete('opensAtHour') * 3600 + - params[:regular_operating_time].delete('opensAtMinute') * 60 - - params[:regular_operating_time][:closesAtOffset] = - params[:regular_operating_time].delete('closesAtHour') * 3600 + - params[:regular_operating_time].delete('closesAtMinute') * 60 -=end - - if operatingTimesParams[:daysOfWeekHash] != nil - daysOfWeek = 0 - - operatingTimesParams[:daysOfWeekHash].each do |dayOfWeek| - daysOfWeek += 1 << Date::DAYNAMES.index(dayOfWeek.capitalize) - end - operatingTimesParams.delete('daysOfWeekHash') - - operatingTimesParams[:flags] = 0 if operatingTimesParams[:flags].nil? - operatingTimesParams[:flags] = operatingTimesParams[:flags] & ~OperatingTime::ALLDAYS_FLAG - operatingTimesParams[:flags] = operatingTimesParams[:flags] | daysOfWeek - end - - - - - return operatingTimesParams - end - end -end - -class RelativeTime - include RelativeTimes::ClassMethods - - def initialize(object,attribute) - @object = object - @attribute = attribute - end - - def offset - @object.send(:read_attribute,@attribute) - end - def offset=(newOffset) - @object.send(:write_attribute,@attribute,newOffset) - end - - - def time(baseTime = Time.now) - _relativeTime(offset, baseTime) - end - def time=(newTime = Time.now) - RAILS_DEFAULT_LOGGER.debug "Updating offset using Time object: #{newTime.inspect} ; offset = #{_getMidnightOffset(newTime)}" - offset = _getMidnightOffset(newTime) - end - - - def hour - (offset / 3600).to_i - end - def hour=(hour) - # hour_seconds + remainder_seconds - offset = (hour * 3600) + (offset % 3600) - end - - - def minute - ( (offset % 3600) / 60 ).to_i - end - def minute=(minute) - # hour_seconds + minute_seconds + remainder_seconds - offset = (hour * 3600) + (minute * 60) + (offset % 60) - end - - - def to_s - '%02d:%02d' % [hour,minute] - end -end
trek/red-sample-apps
f85cad97d006b3de18e8f4cf1c32cf41bd4cb72e
Sample ribbons app (ruby style)
diff --git a/ribbon_notes/NOTES b/ribbon_notes/NOTES new file mode 100644 index 0000000..249263d --- /dev/null +++ b/ribbon_notes/NOTES @@ -0,0 +1,14 @@ +We'll include and always load a reset.sass + +Generators + model + controller + view + directory with behavior.red, style.sass, structure.haml + + +Build Process: + run all .rb files in app through Red and expose as build.js + run all .sass files in all through sass and expose as build.css + run all layouts through haml and expose as index.html + \ No newline at end of file diff --git a/ribbon_notes/README.md b/ribbon_notes/README.md new file mode 100644 index 0000000..7611bf0 --- /dev/null +++ b/ribbon_notes/README.md @@ -0,0 +1,3 @@ +# Hey + +nothing to see here. move along. \ No newline at end of file diff --git a/ribbon_notes/app/controllers/application.rb b/ribbon_notes/app/controllers/application.rb new file mode 100644 index 0000000..fec26f8 --- /dev/null +++ b/ribbon_notes/app/controllers/application.rb @@ -0,0 +1,7 @@ +class ApplicationController + def notes + will_change_value_for(:notes) + @notes ||= Note.all + did_change_value_for(:notes) + end +end \ No newline at end of file diff --git a/ribbon_notes/app/controllers/notes_controller.rb b/ribbon_notes/app/controllers/notes_controller.rb new file mode 100644 index 0000000..e20f0a5 --- /dev/null +++ b/ribbon_notes/app/controllers/notes_controller.rb @@ -0,0 +1,5 @@ +class NotesController < ArrayController + shared_instance + bind 'arranged_objects', 'Note.all' + outlet :note_list +end \ No newline at end of file diff --git a/ribbon_notes/app/layouts/application.haml b/ribbon_notes/app/layouts/application.haml new file mode 100644 index 0000000..bef830f --- /dev/null +++ b/ribbon_notes/app/layouts/application.haml @@ -0,0 +1,11 @@ +!!!strict +%html{:style => 'height:100%;'} + %head + %script{:src => '/public/build/behavior.js', :type => "text/javascript"} + %link{:href => '/public/build/style.css', :rel => 'stylesheet', :type =>"text/css"} + + %body{:style => 'height:100%; margin:0; padding:0;'} + = workspace_view 'main' do + = split_view do + = list_view('notes_list', {:bind => {:data_source => 'NotesController.arranged_objects'}}) do + hi \ No newline at end of file diff --git a/ribbon_notes/app/models/note.rb b/ribbon_notes/app/models/note.rb new file mode 100644 index 0000000..314b8d4 --- /dev/null +++ b/ribbon_notes/app/models/note.rb @@ -0,0 +1,15 @@ +class Note < Model + # data_source 'http://stikkies.local/notes' + # data_format 'json' + kvc_accessor :name, :body + + @data = ArrangedObjects.new([Note.new,Note.new,Note.new]) + def self.all + @data + end + + def self.all=(ary) + @data = ary + self.did_change_value_for('all') + end +end \ No newline at end of file diff --git a/ribbon_notes/config.ru b/ribbon_notes/config.ru new file mode 100644 index 0000000..52337c6 --- /dev/null +++ b/ribbon_notes/config.ru @@ -0,0 +1,5 @@ +require 'ribbons' + +use Rack::Static, :urls => ["/public"] +use Rack::ShowExceptions +run Ribbon.new diff --git a/ribbon_notes/lib/arranged_objects.rb b/ribbon_notes/lib/arranged_objects.rb new file mode 100644 index 0000000..a3e0bf8 --- /dev/null +++ b/ribbon_notes/lib/arranged_objects.rb @@ -0,0 +1,4 @@ +class ArrangedObjects < Array + include Bindable + include KeyValueObserving +end \ No newline at end of file diff --git a/ribbon_notes/lib/assets/reset.sass b/ribbon_notes/lib/assets/reset.sass new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/ribbon_notes/lib/assets/reset.sass @@ -0,0 +1 @@ + diff --git a/ribbon_notes/lib/bindable.rb b/ribbon_notes/lib/bindable.rb new file mode 100644 index 0000000..5425dee --- /dev/null +++ b/ribbon_notes/lib/bindable.rb @@ -0,0 +1,43 @@ +# Bindable module gives classes and instances a public interface for adding bindings via the +# Ribbons class. A Ribbon connects an attribute of the Bindable object to a a path. +# +# Foo # extends Bindable +# f = Foo.new +# f.bind(:bar, 'BazesController.qux.quux') +# +# creates a new Ribbon connecting f's :bar attribute to the value of BazesController.qux.quux +# when the value of BazesController.qux.quux changes, it will notify bound objects (including f). +# f will then follow the path again and set it's :bar attribute to the new value. +# +# Objects that are Bindable must also be KVO-compliant either by including module KeyValueObserving or +# implementing the equivalent methods. +# +module Bindable + def self.included(base) + base.extend(SharedMethods) + end + attr_accessor :bindings + + module SharedMethods + def bind(attribute,path) + binding = ::Ribbon.new(self,attribute,path) + self.send((attribute.to_s + "="), binding.key_path.target_property) + return binding + end + + def bindings + @bindings + end + + def bindings_for(attribute) + @bindings ||= {} + @bindings[attribute] || [] + end + + def add_binding_for_attribute(binding,attribute) + @bindings ||= {} + @bindings[attribute] ? @bindings[attribute] << binding : @bindings[attribute] = [binding] + end + end + include SharedMethods +end \ No newline at end of file diff --git a/ribbon_notes/lib/controllers/array_controller.rb b/ribbon_notes/lib/controllers/array_controller.rb new file mode 100644 index 0000000..4cb067e --- /dev/null +++ b/ribbon_notes/lib/controllers/array_controller.rb @@ -0,0 +1,3 @@ +class ArrayController < Controller + self.kvc_accessor(:arranged_objects, :selection) +end \ No newline at end of file diff --git a/ribbon_notes/lib/controllers/controller.rb b/ribbon_notes/lib/controllers/controller.rb new file mode 100644 index 0000000..8f07185 --- /dev/null +++ b/ribbon_notes/lib/controllers/controller.rb @@ -0,0 +1,60 @@ +class Controller + include KeyValueObserving + include Bindable + def self.kvc_accessor(*accessors) + accessors.each do |accessor| + self.define_method(accessor) do + self.instance_variable_get(("@" + accessor.to_s)) + end + self.define_method((accessor.to_s + "=").to_sym) do |value| + self.instance_variable_set(("@" + accessor.to_s), value) + self.did_change_value_for(accessor.to_s) + end + m = Module.new((accessor.to_s + "ControllerAttributeModule")) + m.instance_eval do + self.define_method(accessor) do + self.shared_instance.send(accessor) + end + + self.define_method((accessor.to_s + "=").to_sym) do |value| + self.shared_instance.send((accessor + "="), value) + self.did_change_value_for(accessor.to_s) + end + end + self.extend(m) + end + end + + def self.outlet(*accessors) + @outlets ? @outlets + accessors : @outlets = accessors + accessors.each do |accessor| + self.define_method(accessor) do + self.instance_variable_get(("@" + accessor.to_s)) + end + self.define_method((accessor.to_s + "=").to_sym) do |value| + self.instance_variable_set(("@" + accessor.to_s), value) + end + m = Module.new((accessor.to_s + "ControllerOutletModule")) + + m.instance_eval do + self.define_method(accessor) do + self.shared_instance.send(accessor) + end + + self.define_method((accessor.to_s + "=").to_sym) do |value| + self.shared_instance.send((accessor + "="), value) + end + end + self.extend(m) + end + end + + def self.outlets + @outlets + end + + def self.shared_instance + @arranged_objects = ArrangedObjects.new + @shared_instance ||= self.new + end +end \ No newline at end of file diff --git a/ribbon_notes/lib/key_path.rb b/ribbon_notes/lib/key_path.rb new file mode 100644 index 0000000..e0abcf2 --- /dev/null +++ b/ribbon_notes/lib/key_path.rb @@ -0,0 +1,34 @@ +class KeyPath + def initialize(path) + @path = path + end + + def self.step_through(path) + callee = Object.module_eval_with_string_not_block(path.shift) + while caller = path.shift + callee = callee.send(caller) + end + return callee + end + + def self.step_through_with_assignment(path,set_value) + set_method = path.pop + callee = Object.module_eval_with_string_not_block(path.shift) + while caller = path.shift + callee = callee.send(caller) + end + return callee.send((accessor + "="), set_value) + end + + def target_object + KeyPath.step_through(@path.split('.')[0..-2]) + end + + def target_property_name + @path.split('.').last + end + + def target_property + KeyPath.step_through(@path.split('.')) + end +end diff --git a/ribbon_notes/lib/kvo.rb b/ribbon_notes/lib/kvo.rb new file mode 100644 index 0000000..02f778b --- /dev/null +++ b/ribbon_notes/lib/kvo.rb @@ -0,0 +1,38 @@ +# KeyValueObserving (KVO) is a module that enables classes and instances to adhere to key-value-observing. +# key-value-observing means that objects +# * implement did_change_value_for(:attr) which notifies each object bound to :attr that an update occured +# * implement attribute getters as Object#foo +# * implement attribute setters as Object#foo=(value) +# * calls to Object#foo=(value) trigger did_change_value_for(:foo) +module KeyValueObserving + attr_accessor :bindings + + def self.included(base) + base.extend(ClassMethods) + base.extend(SharedMethods) + end + + module SharedMethods + def did_change_value_for(attribute) + bindings_for(attribute).each do |binding| + binding.object.send((binding.attribute + "="), binding.key_path.target_property) + # binding.object.send((binding.attribute + "="), binding.key_path.follow) + end + end + end + include SharedMethods + + module ClassMethods + def kvc_accessor(*accessors) + accessors.each do |accessor| + self.define_method(accessor) do + self.instance_variable_get(("@" + accessor)) + end + self.define_method((accessor.to_s + "=").to_sym) do |value| + self.instance_variable_set(("@" + accessor), value) + self.did_change_value_for(accessor.to_s) + end + end + end + end +end \ No newline at end of file diff --git a/ribbon_notes/lib/model.rb b/ribbon_notes/lib/model.rb new file mode 100644 index 0000000..8029c36 --- /dev/null +++ b/ribbon_notes/lib/model.rb @@ -0,0 +1,4 @@ +class Model + include Bindable + include KeyValueObserving +end \ No newline at end of file diff --git a/ribbon_notes/lib/red_extensions.rb b/ribbon_notes/lib/red_extensions.rb new file mode 100644 index 0000000..1befde3 --- /dev/null +++ b/ribbon_notes/lib/red_extensions.rb @@ -0,0 +1,14 @@ +# Red's current Object.module_eval is only the block form of eval +# this provides a version that will take a string. +# Works like Ruby's Object.module_eval(str) +# and will return the object represented by +# the the string. +# +# e.g. Object.module_eval_with_string_not_block("Note") +# will return the object <tt>Note</tt> by calling +# window['c$Note'] +def Object.module_eval_with_string_not_block(str) + str = `str.__value__` + str = `'c$' + str` + `window[str]` +end \ No newline at end of file diff --git a/ribbon_notes/lib/ribbon.rb b/ribbon_notes/lib/ribbon.rb new file mode 100644 index 0000000..89739ee --- /dev/null +++ b/ribbon_notes/lib/ribbon.rb @@ -0,0 +1,19 @@ +# Ribbons connect Bindable objects to the attrbiute values of other objects. +# When a bound objects's attribute value is updated, the ribbon notifies the Bindable +# Bound objects must adhere to the KVO interface. +class Ribbon + attr_reader :key_path, :object, :attribute + def initialize(object, attribute, key_path) + @object = object + @attribute = attribute + @key_path = KeyPath.new(key_path) + @bound_object = @key_path.target_object + @bound_property = @key_path.target_property_name + self.connect + end + + def connect + puts @bound_object.inspect + @bound_object.add_binding_for_attribute(self,@bound_property) + end +end diff --git a/ribbon_notes/lib/ribbons.rb b/ribbon_notes/lib/ribbons.rb new file mode 100644 index 0000000..a9bb5bf --- /dev/null +++ b/ribbon_notes/lib/ribbons.rb @@ -0,0 +1,10 @@ +require 'lib/red_extensions' +require 'lib/bindable' +require 'lib/kvo' +require 'lib/key_path' +require 'lib/ribbon' +require 'lib/arranged_objects' +require 'lib/controllers/controller' +require 'lib/controllers/array_controller' +require 'lib/model' +require 'lib/view' \ No newline at end of file diff --git a/ribbon_notes/lib/view.rb b/ribbon_notes/lib/view.rb new file mode 100644 index 0000000..b1c6e46 --- /dev/null +++ b/ribbon_notes/lib/view.rb @@ -0,0 +1,21 @@ +class View + include KeyValueObserving + include Bindable + self.kvc_accessor(:data_source) + + def initialize(name,options={:bind => {}}) + options[:bind].each do |property,path| + self.bind(property, path) + end + + KeyPath.step_through_with_assignment(options[:outlet].split('.'),self) if options[:outlet] + end + + def did_change_value_for(attribute) + redraw + end + + def redraw + + end +end \ No newline at end of file diff --git a/ribbon_notes/lib/views/list_item_view/behavior.red b/ribbon_notes/lib/views/list_item_view/behavior.red new file mode 100644 index 0000000..e69de29 diff --git a/ribbon_notes/lib/views/list_item_view/structure.haml b/ribbon_notes/lib/views/list_item_view/structure.haml new file mode 100644 index 0000000..48f66fd --- /dev/null +++ b/ribbon_notes/lib/views/list_item_view/structure.haml @@ -0,0 +1 @@ +%li \ No newline at end of file diff --git a/ribbon_notes/lib/views/list_item_view/style.sass b/ribbon_notes/lib/views/list_item_view/style.sass new file mode 100644 index 0000000..e69de29 diff --git a/ribbon_notes/lib/views/list_view/behavior.red b/ribbon_notes/lib/views/list_view/behavior.red new file mode 100644 index 0000000..e287149 --- /dev/null +++ b/ribbon_notes/lib/views/list_view/behavior.red @@ -0,0 +1,2 @@ +class ListView < View +end \ No newline at end of file diff --git a/ribbon_notes/lib/views/list_view/structure.haml b/ribbon_notes/lib/views/list_view/structure.haml new file mode 100644 index 0000000..f83ba76 --- /dev/null +++ b/ribbon_notes/lib/views/list_view/structure.haml @@ -0,0 +1,2 @@ +%div{:class => 'view list_view', :id => identify} + = yield \ No newline at end of file diff --git a/ribbon_notes/lib/views/list_view/style.sass b/ribbon_notes/lib/views/list_view/style.sass new file mode 100644 index 0000000..470f325 --- /dev/null +++ b/ribbon_notes/lib/views/list_view/style.sass @@ -0,0 +1,2 @@ +p + :text_decoration none \ No newline at end of file diff --git a/ribbon_notes/lib/views/split_view/behavior.red b/ribbon_notes/lib/views/split_view/behavior.red new file mode 100644 index 0000000..a9b4efd --- /dev/null +++ b/ribbon_notes/lib/views/split_view/behavior.red @@ -0,0 +1,2 @@ +class SplitView < View +end \ No newline at end of file diff --git a/ribbon_notes/lib/views/split_view/structure.haml b/ribbon_notes/lib/views/split_view/structure.haml new file mode 100644 index 0000000..0a1ef1a --- /dev/null +++ b/ribbon_notes/lib/views/split_view/structure.haml @@ -0,0 +1,2 @@ +%div{:class => 'view split_view', :id => identify } + = yield \ No newline at end of file diff --git a/ribbon_notes/lib/views/split_view/style.sass b/ribbon_notes/lib/views/split_view/style.sass new file mode 100644 index 0000000..7537f19 --- /dev/null +++ b/ribbon_notes/lib/views/split_view/style.sass @@ -0,0 +1,5 @@ +.view + :height 100% + :float left + .split_view + :height 100% diff --git a/ribbon_notes/lib/views/splitter_view/behavior.red b/ribbon_notes/lib/views/splitter_view/behavior.red new file mode 100644 index 0000000..e69de29 diff --git a/ribbon_notes/lib/views/splitter_view/structure.haml b/ribbon_notes/lib/views/splitter_view/structure.haml new file mode 100644 index 0000000..e552c76 --- /dev/null +++ b/ribbon_notes/lib/views/splitter_view/structure.haml @@ -0,0 +1 @@ +%div{:class => 'view splitter_view'} \ No newline at end of file diff --git a/ribbon_notes/lib/views/splitter_view/style.sass b/ribbon_notes/lib/views/splitter_view/style.sass new file mode 100644 index 0000000..eb8e6ef --- /dev/null +++ b/ribbon_notes/lib/views/splitter_view/style.sass @@ -0,0 +1,6 @@ +.view.splitter_view + :height 100% + :width 4px + :background + :color black + :cursor col-resize \ No newline at end of file diff --git a/ribbon_notes/lib/views/text_view/behavior.red b/ribbon_notes/lib/views/text_view/behavior.red new file mode 100644 index 0000000..e69de29 diff --git a/ribbon_notes/lib/views/text_view/structure.haml b/ribbon_notes/lib/views/text_view/structure.haml new file mode 100644 index 0000000..ab6d729 --- /dev/null +++ b/ribbon_notes/lib/views/text_view/structure.haml @@ -0,0 +1,2 @@ +%div{:class => 'view text_view'} + %textarea \ No newline at end of file diff --git a/ribbon_notes/lib/views/text_view/style.sass b/ribbon_notes/lib/views/text_view/style.sass new file mode 100644 index 0000000..e69de29 diff --git a/ribbon_notes/lib/views/workspace_view/behavior.red b/ribbon_notes/lib/views/workspace_view/behavior.red new file mode 100644 index 0000000..e69de29 diff --git a/ribbon_notes/lib/views/workspace_view/structure.haml b/ribbon_notes/lib/views/workspace_view/structure.haml new file mode 100644 index 0000000..a70e52b --- /dev/null +++ b/ribbon_notes/lib/views/workspace_view/structure.haml @@ -0,0 +1,2 @@ +%div{:class => 'view workspace_view', :id => identify} + = yield \ No newline at end of file diff --git a/ribbon_notes/lib/views/workspace_view/style.sass b/ribbon_notes/lib/views/workspace_view/style.sass new file mode 100644 index 0000000..2d7a231 --- /dev/null +++ b/ribbon_notes/lib/views/workspace_view/style.sass @@ -0,0 +1,2 @@ +.workspace_view + :height 100% \ No newline at end of file diff --git a/ribbon_notes/main.red b/ribbon_notes/main.red new file mode 100644 index 0000000..8116343 --- /dev/null +++ b/ribbon_notes/main.red @@ -0,0 +1,2 @@ +# go ahead and load all the notes +Note.all \ No newline at end of file diff --git a/ribbon_notes/public/build/behavior.js b/ribbon_notes/public/build/behavior.js new file mode 100644 index 0000000..57188d3 --- /dev/null +++ b/ribbon_notes/public/build/behavior.js @@ -0,0 +1,1541 @@ +Red = { + id: 100, + + conferInheritance: function(newClass,superclass) { + newClass.__superclass__=superclass; + Red.donateMethodsToSingleton(superclass,newClass,true); + Red.donateMethodsToClass(superclass.prototype,newClass.prototype,true); + if(newClass==c$Module){delete(newClass.prototype.m$initialize);}; + if(newClass!==Number&&newClass!==Array){newClass.prototype.toString=superclass.prototype.toString;}; + }, + + donateMethodsToSingleton: function(donor,recipient,overwrite) { + for(var x in donor) { + if(x.slice(0,2)==='m$' && (overwrite || recipient[x]===undefined)) { + var f = function() { var m=arguments.callee;return m.__methodSource__[m.__methodName__].apply(m.__methodReceiver__,arguments); }; + f.__methodName__=x;f.__methodSource__=donor;f.__methodReceiver__=recipient; + recipient[x]=f; + }; + }; + }, + + donateMethodsToClass: function(donor,recipient,overwrite) { + for(var x in donor) { + if(x.slice(0,2)==='m$' && (overwrite || recipient[x]===undefined)) { + var f = function() { var m=arguments.callee;return m.__methodSource__[m.__methodName__].apply(this,arguments); }; + f.__methodName__=x;f.__methodSource__=donor; + recipient[x]=f; + }; + }; + }, + + donateConstantsToClass: function(donor,recipient,overwrite) { + for(var x in donor) { + if(x.slice(0,2)==='c$' && (overwrite || recipient[x]===undefined)) { + recipient[x]=donor[x]; + }; + }; + }, + + updateChildren: function(parentClass) { + for(var x in parentClass.__children__) { + var childClass=Red.inferConstantFromString(x); + Red.donateMethodsToSingleton(parentClass,childClass,false); + Red.donateMethodsToClass(parentClass.prototype,childClass.prototype,false); + Red.updateChildren(childClass); + }; + }, + + updateIncluders: function(module) { + for(var x in module.__includers__) { + var includer=Red.inferConstantFromString(x); + Red.donateMethodsToSingleton(module,includer,false); + Red.donateMethodsToClass(module.prototype,includer.prototype,false); + if(includer == window){return nil;}; + switch(includer.m$class().__name__){case 'Module':Red.updateIncluders(includer);break;case 'Class':Red.updateChildren(includer);break;}; + }; + }, + + initializeClass: function(longName,newClass) { + newClass.__name__ = longName; + newClass.__id__ = Red.id++; + newClass.__modules__ = {}; + newClass.__children__ = {}; + newClass.__class__ = c$Class; + newClass.prototype.__class__=newClass; + Red.donateMethodsToSingleton(c$Class.prototype,newClass,true); + }, + + interpretNamespace: function(longName) { + var ary=longName.split('.'),name=ary.pop(),namespace=window; + while(ary.length>0){namespace=namespace['c$'+ary.shift()];}; + return [namespace,name]; + }, + + inferConstantFromString: function(longName) { + if(longName=='window'){return window;} + var context=Red.interpretNamespace(longName); + return context[0]['c$'+context[1]]; + }, + + _module: function(longName,block){ + var newModule,context=Red.interpretNamespace(longName),namespace=context[0],name=context[1],c$name='c$'+name; + if(namespace[c$name]) { + if(namespace[c$name].m$class&&namespace[c$name].m$class()!==c$Module){m$raise(c$TypeError,$q(longName+' is not a Module'));}; + newModule = namespace[c$name]; + } else { + newModule = c$Module.m$new(longName); + namespace[c$name] = newModule; + newModule.__includers__={}; + }; + if(typeof(block)=='function') { block.call(newModule); }; + Red.updateIncluders(newModule); + }, + + _class: function(longName,superclass,block){ + var newClass,context=Red.interpretNamespace(longName),namespace=context[0],name=context[1],c$name='c$'+name; + if(namespace[c$name]) { + if(namespace[c$name].m$class&&namespace[c$name].m$class()!==c$Class){m$raise(c$TypeError,$q(longName+' is not a Class'));}; + if(name!=='Object'&&superclass!==namespace[c$name].__superclass__){m$raise(c$TypeError,$q('superclass mismatch for class '+longName));}; + newClass = namespace[c$name]; + if(name=='Module'&&!(newClass.__superclass__.__children__[name])){Red.conferInheritance(c$Module,c$Object);} + if(name=='Class'&&!(newClass.__superclass__.__children__[name])){Red.conferInheritance(c$Class,c$Module);} + } else { + switch(name){case 'Array':newClass=Array;break;case 'Numeric':newClass=Number;break;default:newClass=function(){this.__id__=Red.id++;};}; + if(superclass.m$class&&superclass.m$class()!==c$Class){m$raise(c$TypeError,$q('superclass must be a Class ('+superclass.m$class().__name__+' given)'))} + Red.conferInheritance(newClass,superclass); + Red.initializeClass(longName,newClass); + superclass.__children__[newClass.__name__]=true; + superclass.m$inherited && superclass.m$inherited(newClass); + namespace[c$name]=newClass; + }; + if(name=='Object'||superclass==c$Object){newClass.cvset=function(v,o){return newClass['v$'+v]=o;};newClass.cvget=function(v){return newClass['v$'+v];};}else{newClass.cvset=function(v,o){return superclass.cvset(v,o);};newClass.cvget=function(v){return superclass.cvget(v);};}; + if(typeof(block)=='function'){block.call(newClass);}; + Red.updateChildren(newClass); + if((typeof(c$TrueClass)!='undefined'&&newClass==c$TrueClass)||(typeof(c$FalseClass)!='undefined'&&newClass==c$FalseClass)){Red.donateMethodsToClass(newClass.prototype,Boolean.prototype,true);}; + }, + + LoopError: { + _break:function(returnValue){var e=new(Error);e.__keyword__='break';e.__return__=returnValue==null?nil:returnValue;throw(e);}, + _next:function(returnValue){var e=new(Error);e.__keyword__='next';e.__return__=returnValue==null?nil:returnValue;throw(e);}, + _redo:function(){var e=new(Error);e.__keyword__='redo';throw(e);}, + } +} +; + +var $u=undefined,nil=null,$={}; + +c$Class = function(){this.__id__=Red.id++};c$Class.__name__='Class';c$Class.__children__={}; +c$Module = function(){this.__id__=Red.id++};c$Module.__name__='Module';c$Module.__children__={};c$Class.__superclass__=c$Module; +c$Object = function(){this.__id__=Red.id++};c$Object.__name__='Object';c$Object.__children__={};c$Module.__superclass__=c$Object; + +c$Object.prototype.toString=function(){return '#<'+this.m$class().__name__.replace(/\./g,'::')+':0x'+(this.__id__*999^4000000).toString(16)+'>'}; +Function.prototype.m$=function(o){var f=this;var p=function(){return f.apply(o,arguments);};p.__unbound__=f;p.__arity__=f.arity;p.__id__=Red.id++;return p;}; +window.__name__='window'; +window.prototype=window; +window.__children__={'Object':true}; +window.m$include=function(){for(var i=0,modules=arguments,l=modules.length;i<l;++i){var mp=modules[i].prototype;for(var x in mp){if(x.slice(0,2)=='m$'){var f=function(){return arguments.callee._source[arguments.callee._name].apply(window,arguments) };f._source=mp;f._name=x;window[x]=f;};};modules[i].m$included(window);modules[i].__includers__['window']=true;};if(modules[0]!=c$Kernel){Red.donateMethodsToClass(window,c$Object.prototype);Red.updateChildren(c$Object);};return window;}; +window.m$block_given_bool=function(){typeof(arguments[0])=='function'} + +function $a(min,max,args,bg){var a=args.length-bg;if(a<min){n=min;}else{if(max!=-1&&a>max){n=max;}else{return;};};m$raise(c$ArgumentError, $q('wrong number of arguments ('+a+' for '+n+')'));} +function $e(e,ary){if(e.m$is_a_bool){for(var i=0,l=ary.length;i<l;++i){if(e.m$is_a_bool(ary[i])){return true;};};};return false;}; +function $m(obj,name){var str=obj.m$inspect().__value__;str=str[0]=='#'?str:str+':'+obj.m$class().__name__;m$raise(c$NoMethodError, $q('undefined method "'+name+'" for '+str));} +function $n(obj,name){var str=obj.m$inspect().__value__;str=str[0]=='#'?str:str+':'+obj.m$class().__name__;m$raise(c$NameError, $q('undefined local variable or method "'+name+'" for '+str));} +function $Q(){for(var i=1,s=arguments[0],l=arguments.length;i<l;++i){s+=$q(arguments[i]).m$to_s().__value__;};return $q(s);}; +function $q(obj){if(typeof obj!=='string'){return obj;};return c$String.m$new(obj);}; +function $r(value,options){return c$Regexp.m$new(value,options);}; +function $s(value){return(c$Symbol.__table__[value]||c$Symbol.m$new(value));}; +function $T(x){return x!==false&&x!==nil&&x!=undefined;}; + +; + +Red._class('Object',c$Object,function(){ var _=c$Object.prototype; + _.m$initialize=function(){nil;}; + _.m$_eql2=function(other){return this.__id__===other.__id__;}; + _.m$_eql3=function(other){return this.__id__===other.__id__;}; + _.m$class=function(){return this.__class__;}; + _.m$extend=function(){for(var l=arguments.length,i=0,modules=[];i<l;++i){modules.push(arguments[i]);};for(var i=0,l=modules.length;i<l;++i){modules[i].m$extend_object(this);modules[i].m$extended(this);};return(this);}; + _.m$hash=function(){return 'o_'+this.__id__;}; + _.m$inspect=function(){return this.m$to_s();}; + _.m$instance_eval=function(block){var z=arguments[arguments.length-1],bg=m$block_given_bool(z),block=bg?c$Proc.m$new(z):nil;return block.__block__.m$(this)();}; + _.m$instance_of_bool=function(klass){return this.m$class()==klass;}; + _.m$instance_variable_get=function(name){var v=this[name.__value__.replace('@','i$')];return v==null?nil:v;}; + _.m$instance_variable_set=function(name,obj){return this[name.__value__.replace('@','i$')]=obj;}; + _.m$is_a_bool=function(klass){if(this.m$class()==klass||c$Object==klass){return true;};if(this.m$class().__modules__[klass]){return true;};if(this.m$class()==c$Object){return false;};var bubble=this.m$class(),result=false;while(bubble!=c$Object){if(klass==bubble||bubble.__modules__[klass]!=null){result=true;};if(result){break;};bubble=bubble.__superclass__;};return(result);}; + _.m$nil_bool=function(){return false;}; + _.m$send=function(sym){for(var l=arguments.length,i=1,args=[];i<l;++i){args.push(arguments[i]);};var str=sym.__value__.replace('=','_eql').replace('!','_bang').replace('?','_bool');sub={'==':'_eql2','===':'_eql3','=~':'_etld','[]':'_brac','[]=':'_breq','<=':'_lteq','>=':'_gteq','<<':'_ltlt','>>':'_gtgt','<':'_lthn','>':'_gthn','<=>':'_ltgt','|':'_pipe','&':'_ampe','+':'_plus','+@':'_posi','-@':'_nega','*':'_star','**':'_str2','/':'_slsh','%':'_perc','^':'_care','~':'_tild'};var method=this['m$'+(sub[str]||str)];if(!method){m$raise(c$NoMethodError,$q('undefined method "'+sym.__value__+'" for '+this));};return method.apply(this,args);}; + _.m$to_s=function(){return $q('#<'+this.m$class().__name__.replace(/\./g,'::')+':0x'+(this.__id__*999^4000000).toString(16)+'>');}; +}); + +Red._class('Module',c$Object,function(){ var _=c$Module.prototype; + var writer=$u; + _.m$initialize=function(module_name,block){var z=arguments[arguments.length-1],bg=m$block_given_bool(z),block=bg?c$Proc.m$new(z):nil;this.__name__=module_name.__value__||module_name;this.prototype={};}; + _.m$_ltgt=function(other_module){return nil;}; + _.m$_eql3=function(obj){return obj.m$is_a_bool(this);}; + _.m$append_features=function(mod){Red.donateMethodsToSingleton(this,mod);Red.donateMethodsToClass(this.prototype,mod.prototype);Red.donateConstantsToClass(this,mod);return(mod);}; + _.m$attr=function(attribute,writer){writer=$T($.fd=writer)?$.fd:false;var a=attribute.__value__;f1=this.prototype['m$'+a]=function(){return this['i$'+arguments.callee._name];};f1._name=a;if(writer){f2=this.prototype['m$'+a.__value__+'_eql']=function(x){return this['i$'+arguments.callee._name]=x;};f2._name=a;};return(nil);}; + _.m$attr_accessor=function(){for(var l=arguments.length,i=0,symbols=[];i<l;++i){symbols.push(arguments[i]);};for(var i=0,l=symbols.length;i<l;++i){ + var a=symbols[i].__value__; + f1=this.prototype['m$'+a]=function(){return this['i$'+arguments.callee._name];};f1._name=a; + f2=this.prototype['m$'+a+'_eql']=function(x){return this['i$'+arguments.callee._name]=x;};f2._name=a; + };return(nil);}; + _.m$attr_reader=function(){for(var l=arguments.length,i=0,symbols=[];i<l;++i){symbols.push(arguments[i]);};for(var i=0,l=symbols.length;i<l;++i){ + var a=symbols[i].__value__; + f=this.prototype['m$'+a]=function(){return this['i$'+arguments.callee._name];};f._name=a; + };return(nil);}; + _.m$define_method=function(sym,block){var z=arguments[arguments.length-1],bg=m$block_given_bool(z),block=bg?c$Proc.m$new(z):nil;return nil;}; + _.m$extend_object=function(obj){var tp=this.prototype;for(var x in tp){ + if(x.slice(0,2)=='m$'){ + var f=function(){var m=arguments.callee;return m.__methodSource__[m.__methodName__].apply(m.__methodReceiver__,arguments) }; + f.__methodName__=x;f.__methodSource__=tp;f.__methodReceiver__=obj; + obj[x]=f; + }; + };return(obj);}; + _.m$extended=function(object){return nil;}; + _.m$hash=function(){return 'c_'+this.m$to_s();}; + _.m$include=function(){for(var l=arguments.length,i=0,modules=[];i<l;++i){modules.push(arguments[i]);};for(var i=0,l=modules.length;i<l;++i){var mod=modules[i];mod.m$append_features(this);mod.m$included(this);mod.__includers__[this.__name__]=true;};return(this);}; + _.m$include_bool=function(other_module){return nil;}; + _.m$included=function(other_module){return nil;}; + _.m$to_s=function(){return $q(this.__name__.replace(/\./g,'::'));}; +}); + +Red._class('Class',c$Module,function(){ var _=c$Class.prototype; + var superclass=$u; + c$Class.m$new=function(class_name,superclass){$a(1,2,arguments,0);superclass=$T($.fe=superclass)?$.fe:c$Object;Red._class(class_name.__value__,superclass,function(){});return(window['c$'+class_name.__value__]);}; + _.m$allocate=function(){return new(this)();}; + _.m$inherited=function(subclass){return nil;}; + _.m$new=function(){var result=this.m$allocate();this.prototype.m$initialize.apply(result,arguments);return(result);}; + _.m$superclass=function(){return this.__superclass__;}; +}); +Red.initializeClass('Object',c$Object);c$Object.__children__={'Module':true}; +Red.initializeClass('Module',c$Module);c$Module.__children__={'Class':true}; +Red.initializeClass('Class',c$Class) +; + +Red._module('Comparable',function(){ var _=c$Comparable.prototype; + _.m$_eql2=function(obj){return (this.__id__&&obj.__id__&&this.__id__==obj.__id__)||this.m$_ltgt(obj)==0;}; +}); + +Red._module('Enumerable',function(){ var _=c$Enumerable.prototype; + var block=$u; + ; +}); + +Red._module('Kernel',function(){ var _=c$Kernel.prototype; + var num=$u; + _.m$block_given_bool=function(x){return typeof(x)=='function';}; + _.m$lambda=function(func){var result=new(c$Proc)();result.__block__=func;result.__block__.__id__=Red.id++;return(result);}; + _.m$proc=function(func){var result=new(c$Proc)();result.__block__=func;result.__block__.__id__=Red.id++;return(result);}; + _.m$puts=function(obj){var string=obj.m$to_s&&obj.m$to_s()||$q(''+obj);console.log(string.__value__.replace(/\\/g,'\\\\'));return(nil);}; + _.m$raise=function(){for(var l=arguments.length,i=0,args=[];i<l;++i){args.push(arguments[i]);};var exception_class=c$RuntimeError,msg=$q('');if(arguments[0]&&arguments[0].m$is_a_bool(c$Exception)){ + var e=arguments[0]; + }else{ + if(arguments[0]&&arguments[0].m$class()==c$String){ + msg=arguments[0]; + }else{ + if(arguments[0]!=null){ + exception_class=arguments[0],msg=arguments[1]||msg; + }; + } + };var e=e||exception_class.m$new(msg);e.__stack__=new Error().stack;throw(e);return(nil);}; + _.m$sprintf=function(string){var i=1,source=string.__value__,result=[],m=$u,arg=$u,val=$u,str=$u,dL=$u,chr=$u,pad=$u; + while(source){ + if(m=source.match(/^[^%]+/)){result.push(m[0]);source=source.slice(m[0].length);continue;}; + if(m=source.match(/^%%/)) {result.push('%'); source=source.slice(m[0].length);continue;}; + // 1(0)2(wdth) 3(prec) 4(field-type ) + if(m=source.match(/^%(0)?(\d+)?(?:\.(\d+))?([bcdEefGgiopsuXx])/)){ + arg = arguments[i].__value__||arguments[i]; + switch(m[4]){ + case'b':str=parseFloat(arg).toString(2);break; + case'c':str=String.fromCharCode(arg);break; + case'd':val=parseInt(arg);str=''+val;break; + case'E':val=parseFloat(arg);str=''+(m[3]?val.toExponential(m[3]):val.toExponential()).toUpperCase();break; + case'e':val=parseFloat(arg);str=''+(m[3]?val.toExponential(m[3]):val.toExponential());break; + case'f':val=parseFloat(arg);str=''+(m[3]?val.toFixed(m[3]):val);break; + case'G':str='-FIX-';break; + case'g':str='-FIX-';break; + case'i':val=parseInt(arg);str=''+val;break; + case'o':str=parseFloat(arg).toString(8);break; + case'p':str=$q(arg).m$inspect().__value__;break; + case's':val=arg.m$to_s&&arg.m$to_s().__value__||arg;str=(m[3]?val.slice(0,m[2]):val);break; + case'u':val=parseInt(arg);str=''+(val<0?'..'+(Math.pow(2,32)+val):val);break; + case'X':str=parseInt(arg).toString(16).toUpperCase();break; + case'x':str=parseInt(arg).toString(16);break; + }; + if((dL=m[2]-str.length)!=0){for(chr=m[1]||' ',pad=[];dL>0;pad[--dL]=chr);}else{pad=[]}; + result.push(pad.join('')+str); + source=source.slice(m[0].length); + i+=1; + continue; + }; + throw('ArgumentError: malformed format string') + };return($q(result.join('')));}; +});(this.m$include||window.m$include).call(this,c$Kernel); + +Red._module('Math',function(){ var _=c$Math.prototype; + c$Math.c$E=2.71828182845905; + c$Math.c$PI=3.14159265358979; +}); + +Red._class('Array',c$Object,function(){ var _=c$Array.prototype; + var length=$u,index=$u,str=$u; + _.m$_plus=function(ary){return this.concat(ary);}; + _.m$_subt=function(ary){for(var i=0,l=ary.length,result=[],seen=[];i<l;++i){var a=ary[i],k=a.m$hash();if(!seen[k]){seen[k]=true;};};;for(var i=0,l=this.length;i<l;++i){var a=this[i],k=a.m$hash();if(!seen[k]){result.push(a);};};return(result);}; + _.m$_ltlt=function(object){this[this.length]=object;return(this);}; + _.m$_ltgt=function(ary){for(var i=0,l=this.length;i<l;++i){if(ary[i]==null){break;};var x=this[i].m$_ltgt(ary[i]);if(x!==0){return x;};};return(this.length.m$_ltgt(ary.length));}; + _.m$_eql2=function(ary){if(ary.m$class()!==c$Array||ary.length!==this.length){return false;};for(var i=0,l=this.length;i<l;++i){if(!(this[i].m$_eql2(ary[i]))){return false;};};return(true);}; + _.m$_brac=function(index,length){length=$T($.ff=length)?$.ff:nil;var l=this.length;if(index.m$class()==c$Range){ + var start=index.__start__,end=index.__exclusive__?index.__end__-1:index.__end__; + index=start<0?start+l:start; + length=(end<0?end+l:end)-index+1; + if(length<0){length=0}; + }else{ + if(index<0){index+=l;}; + };if(index>=l||index<0){return nil;};if($T(length)){ + if(length<=0){return [];}; + result=this.slice(index,index+length); + }else{ + result=this[index]; + };return(result);}; + _.m$_breq=function(index,length,object){var l=this.length;if(object==null){object=length;length=$u;};if(index.m$class()==c$Range){var start=index.__start__,end=index.__exclusive__?index.__end__-1:index.__end__;index=start<0?start+l:start;length=(end<0?end+l:end)-index+1;if(length<0){length=0};}else{if(index<0){index+=l;};if(length<0){throw('IndexError: negative length')}};if(index<0){throw('RangeError: out of range');};while(this.length<index){this.push(nil);};if($T(length)){var l=this.length,final=(index+length>l)?l:index+length;this._replace(this.slice(0,index).concat(object===nil?[]:(object.m$class()==c$Array?object:[object])).concat(this.slice(final,l)))}else{this[index]=object};return(object);}; + _.m$clear=function(){this.length=0;return(this);}; + _.m$compact=function(){for(var i=0,l=this.length,result=[];i<l;++i){if(!(this[i]===nil)){result.push(this[i]);};};return(result);}; + _.m$delete=function(obj,_block){var z=arguments[arguments.length-1],bg=m$block_given_bool(z),_block=bg?c$Proc.m$new(z):nil;for(var i=0,l=this.length,temp=[];i<l;++i){if(!(this[i].m$_eql2(obj))){temp.push(this[i]);};};this._replace(temp);return(l===this.length?(m$block_given_bool(_block.__block__)?_block.m$call():nil):obj);}; + _.m$each=function(_block){var z=arguments[arguments.length-1],bg=m$block_given_bool(z),_block=bg?c$Proc.m$new(z):nil;for(var i=0,l=this.length;i<l;++i){try{_block.m$call(this[i]);}catch(e){switch(e.__keyword__){case 'next':break;case 'break':return e.__return__;break;case 'redo':--i;break;default:throw(e);};};};return(this);}; + _.m$empty_bool=function(){return this.length==0;}; + _.m$flatten=function(){for(var i=0,l=this.length,result=[];i<l;++i){if(this[i].m$class()==c$Array){result=result.concat(this[i].m$flatten());}else{result.push(this[i]);};};return(result);}; + _.m$hash=function(){return nil;}; + _.m$include_bool=function(obj){for(var i=0,l=this.length;i<l;++i){if(this[i].m$_eql2(obj)){return true;};};return(false);}; + _.m$inspect=function(){for(var i=1,l=this.length,result='['+(this[0]!=null?this[0].m$inspect().__value__:'');i<l;++i){result+=', '+this[i].m$inspect().__value__;};return($q(result+']'));}; + _.m$join=function(str){str=$T($.fg=str)?$.fg:$q("");var result=this[0]!=null?this[0].m$join?this[0].m$join(str.__value__).__value__:this[0].m$to_s().__value__:'';for(var i=1,l=this.length;i<l;++i){result+=(str.__value__||'')+(this[i].m$join?this[i].m$join(str).__value__:this[i].m$to_s().__value__);};return($q(result));}; + _.m$last=function(n){var l=this.length;if(n!=null){for(var result=[],i=n>l?0:l-n;i<l;++i){result.push(this[i]);};return result;};return(l==0?nil:this[l-1]);}; + _.m$length=function(){return this.length;}; + _.m$map=function(_block){var z=arguments[arguments.length-1],bg=m$block_given_bool(z),_block=bg?c$Proc.m$new(z):nil;for(var i=0,l=this.length,result=[];i<l;++i){try{result[i]=_block.m$call(this[i]);}catch(e){switch(e.__keyword__){case 'next':result[i]=e.__return__;break;case 'break':return e.__return__;break;case 'redo':--i;break;default:throw(e);};};};return(result);}; + _.m$pop=function(){if(this.length==0){return nil;};return this.pop();}; + _.m$push=function(){for(var l=arguments.length,i=0,args=[];i<l;++i){args.push(arguments[i]);};for(var i=0,l=args.length;i<l;++i){this.push(args[i]);};return(this);}; + _.m$shift=function(){if(this.length==0){return nil;};return this.shift();}; + _.m$size=function(){return this.length;}; + _.m$to_s=function(){return(this.m$join());}; + _._partition=function(first,last,pivot,block){var value=this[pivot],store=first;this._swap(pivot,last);for(var i=0,l=this.length;i<l;++i){if(i<first||i>=last){continue;};var cmp=block?block(this[i],value):this[i].m$_ltgt(value);if(cmp==-1||cmp==0){this._swap(store++,i);};};this._swap(last,store);return(store);}; + _._quick_sort=function(start,finish,block){if(finish-1>start){var pivot=start+Math.floor(Math.random()*(finish-start));pivot=this._partition(start,(finish-1),pivot,block);this._quick_sort(start,pivot,block);this._quick_sort((pivot+1),finish,block);};return(this);}; + _._replace=function(ary){this.length=0;for(var i=0,l=ary.length;i<l;++i){this.push(ary[i])};return this;}; + _._swap=function(x,y){var z=this[x];this[x]=this[y];this[y]=z;return this;}; +}); + +Red._class('Exception',c$Object,function(){ var _=c$Exception.prototype; + _.m$initialize=function(msg){if(msg!=null){this.__message__=msg.__value__;};}; + _.m$backtrace=function(){if(this.__stack__==null){return [];};for(var i=0,lines=this.__stack__.match(/@[^\n]+:\d+/g),l=lines.length,result=[];i<l;++i){result.push($q(lines[i].match(/@\w+:\/*(\/[^\n]+:\d+)/)[1]));};return(result);}; + _.m$inspect=function(){var class_name=this.m$class().__name__.replace(/\./g,'::');return this.__message__==''?$q(class_name):$q('#<'+class_name+': '+(this.__message__||class_name)+'>');}; + _.m$to_s=function(){return this.__message__==null?$q(this.m$class().__name__.replace(/\./g,'::')):$q(this.__message__);}; + _.m$to_str=function(){return this.__message__==null?$q(this.m$class().__name__.replace(/\./g,'::')):$q(this.__message__);}; +}); +c$Exception.prototype.toString=function(){var class_name=this.m$class().__name__.replace(/\./g,'::'),str=class_name+': '+(this.__message__||class_name);console.log(str+(this.__stack__!=null?'\n from '+this.m$backtrace().join('\n from '):''));return '#<'+str+'>';} +; + +Red._class('StandardError',c$Exception,function(){ var _=c$StandardError.prototype; + ; +}); + +Red._class('ArgumentError',c$StandardError,function(){ var _=c$ArgumentError.prototype; + ; +}); + +Red._class('IndexError',c$StandardError,function(){ var _=c$IndexError.prototype; + ; +}); + +Red._class('RangeError',c$StandardError,function(){ var _=c$RangeError.prototype; + ; +}); + +Red._class('RuntimeError',c$StandardError,function(){ var _=c$RuntimeError.prototype; + ; +}); + +Red._class('NameError',c$StandardError,function(){ var _=c$NameError.prototype; + ; +}); + +Red._class('NoMethodError',c$NameError,function(){ var _=c$NoMethodError.prototype; + ; +}); + +Red._class('TypeError',c$StandardError,function(){ var _=c$TypeError.prototype; + ; +}); + +Red._class('FalseClass',c$Object,function(){ var _=c$FalseClass.prototype; + _.m$hash=function(){return nil;}; + _.m$to_s=function(){return nil;}; +}); + +Red._class('Hash',c$Object,function(){ var _=c$Hash.prototype; + var key=$u; + c$Hash.m$_brac=function(){for(var l=arguments.length,i=0,args=[];i<l;++i){args.push(arguments[i]);};$a(0,-1,arguments,0);if(args.length==1&&args[0].m$class()==c$Hash){return args[0];};for(var i=0,l=args.length,result=c$Hash.m$new(),c=result.__contents__;i<l;i+=2){var k=args[i],v=args[i+1],h=k.m$hash();c[h]=[k,v]};return(result);}; + _.m$initialize=function(block){for(var l=arguments.length,bg=m$block_given_bool(arguments[l-1]),l=bg?l-1:l,i=0,args=[];i<l;++i){args.push(arguments[i]);};var block=(bg?c$Proc.m$new(arguments[arguments.length-1]):nil);this.__default__=(args[0]==null?block==null?nil:block:args[0]);this.__contents__={};}; + _.m$_eql2=function(other){var c=this.__contents__,o=other.__contents__;for(var x in o){if(x.slice(1,2)=='_'&&c[x]==null){return false;};};for(var x in c){if(x.slice(1,2)=='_'&&!c[x][1].m$_eql2(o[x][1])){return false;};};return(true);}; + _.m$_brac=function(k){var kv=this.__contents__[k.m$hash()];if(!kv){var d=this.__default__;return(typeof(d)=='function'?d(this,kv[0]):d);};return(kv[1]);}; + _.m$_breq=function(k,v){this.__contents__[k.m$hash()]=[k,v];return(v);}; + _.m$clear=function(){this.__contents__={};return(this);}; + _.m$delete=function(k,_block){var z=arguments[arguments.length-1],bg=m$block_given_bool(z),_block=bg?c$Proc.m$new(z):nil;var c=this.__contents__,d=this.__default__,x=k.m$hash(),kv=c[x];if(kv!=null){var result=kv[1];delete(c[x]);return result;};return(typeof(_block)=='function'?_block.m$call(k):(typeof(d)=='function'?d(this,k):d));}; + _.m$each=function(_block){var z=arguments[arguments.length-1],bg=m$block_given_bool(z),_block=bg?c$Proc.m$new(z):nil;var c=this.__contents__;for(var x in c){try{if(x.slice(1,2)=='_'){var kv=c[x];_block.__arity__==1?_block.m$call([kv[0],kv[1]]):_block.m$call(kv[0],kv[1])};}catch(e){switch(e.__keyword__){case 'next':;break;case 'break':return e.__return__;break;default:throw(e);};};};return(this);}; + _.m$each_key=function(_block){var z=arguments[arguments.length-1],bg=m$block_given_bool(z),_block=bg?c$Proc.m$new(z):nil;var c=this.__contents__;for(var x in c){try{if(x.slice(1,2)=='_'){_block.m$call(c[x][0])};}catch(e){switch(e.__keyword__){case 'next':;break;case 'break':return e.__return__;break;default:throw(e);};};};return(this);}; + _.m$empty_bool=function(){for(var x in this.__contents__){if(x.slice(1,2)=='_'){return false;};};return(true);}; + _.m$hash=function(){return nil;}; + _.m$include_bool=function(k){return !!this.__contents__[k.m$hash()];}; + _.m$inspect=function(){var contents=[],c=this.__contents__;for(var x in c){if(x.slice(1,2)=='_'){var kv=c[x];contents.push(kv[0].m$inspect().__value__+' => '+kv[1].m$inspect().__value__);};};return($q('{'+contents.join(', ')+'}'));}; + _.m$length=function(){var c=this.__contents__,result=0;for(var x in c){if(x.slice(1,2)=='_'){result++;};};return(result);}; + _.m$merge=function(other,_block){var z=arguments[arguments.length-1],bg=m$block_given_bool(z),_block=bg?c$Proc.m$new(z):nil;var c=this.__contents__,o=other.__contents__,result=c$Hash.m$new(),r=result.__contents__;for(var x in c){if(x.slice(1,2)=='_'){r[x]=c[x];};};for(var x in o){var ckv=c[x],okv=o[x];if(x.slice(1,2)=='_'){typeof(_block)=='function'&&ckv!=null?r[x]=[ckv[0],_block.m$call(ckv[0],ckv[1],okv[1])]:r[x]=okv;};};return(result);}; + _.m$shift=function(){var c=this.__contents__,d=this.__default__,result=typeof(d)=='function'?d(nil):d;for(var x in c){if(x.slice(1,2)=='_'){result=[c[x][0],c[x][1]];delete(c[x]);break;};};return(result);}; + _.m$size=function(){var c=this.__contents__,result=0;for(var x in c){if(x.slice(1,2)=='_'){result++;};};return(result);}; + _.m$store=function(k,v){this.__contents__[k.m$hash()]=[k,v];return(v);}; + _.m$to_s=function(){var c=this.__contents__,result=[];for(var x in c){if(x.slice(1,2)=='_'){result.push(c[x]);};};return(c$Array.prototype.m$join.call(result));}; + _.m$update=function(other,_block){var z=arguments[arguments.length-1],bg=m$block_given_bool(z),_block=bg?c$Proc.m$new(z):nil;var c=this.__contents__,o=other.__contents__;for(var x in o){var ckv=c[x],okv=o[x];if(x.slice(1,2)=='_'){typeof(_block)=='function'&&ckv!=null?ckv[1]=_block.m$call(ckv[0],ckv[1],okv[1]):c[x]=okv;};};return(this);}; +}); + +Red._class('MatchData',c$Object,function(){ var _=c$MatchData.prototype; + _.m$initialize=function(){this.__captures__=[];}; + _.m$_brac=function(){for(var l=arguments.length,i=0,args=[];i<l;++i){args.push(arguments[i]);};return c$Array.prototype.m$_brac.apply(this.__captures__,args);}; + _.m$length=function(){return this.__captures__.length;}; + _.m$inspect=function(){return c$Object.prototype.m$to_s.apply(this);}; + _.m$size=function(){return this.__captures__.length;}; + _.m$to_s=function(){return this.__captures__[0];}; +}); + +Red._class('NilClass',c$Object,function(){ var _=c$NilClass.prototype; + _.m$initialize=function(){this.__id__=4;}; + _.m$inspect=function(){return $q("nil");}; + _.m$nil_bool=function(){return true;}; + _.m$to_i=function(){return 0;}; + _.m$to_proc=function(){return nil;}; + _.m$to_s=function(){return $q("");}; + nil=c$NilClass.m$new(); + c$Object.__superclass__=nil; +}); + +Red._class('Numeric',c$Object,function(){ var _=c$Numeric.prototype; + var base=$u; + this.m$include(c$Comparable); + _.m$_perc=function(n){return this%n;}; + _.m$_plus=function(n){return this+n;}; + _.m$_subt=function(n){return this-n;}; + _.m$_ltlt=function(n){return Math.floor(parseInt(this)*Math.pow(2,parseInt(n)));}; + _.m$_ltgt=function(n){if(n.constructor!=Number){return nil;};if(this>n){return 1;};if(this<n){return -1;};return(0);}; + _.m$_eql2=function(n){return this.valueOf()===n.valueOf();}; + _.m$_eql3=function(n){return this.valueOf()===n.valueOf();}; + _.m$_brac=function(n){var str=parseInt(this).toString(2);if(n>=str.length){return 0;};return parseInt(str[(str.length-n-1)]);}; + _.m$hash=function(){return 'n_'+this;}; + _.m$times=function(_block){var z=arguments[arguments.length-1],bg=m$block_given_bool(z),_block=bg?c$Proc.m$new(z):nil;for(var i=0,l=this.valueOf();i<l;++i){try{_block.m$call(i);}catch(e){switch(e.__keyword__){case 'next':break;case 'break':return e.__return__;break;case 'redo':--i;break;default:throw(e);};}};return(this);}; + _.m$to_i=function(){return parseInt(this);}; + _.m$to_s=function(base){base=$T($.fh=base)?$.fh:10;return $q(this.toString(base));}; + _.m$to_sym=function(){return nil;}; +}); + +Red._class('Proc',c$Object,function(){ var _=c$Proc.prototype; + _.m$initialize=function(func){this.__block__=func;this.__block__.__id__=func.__id__||Red.id++;this.__id__=this.__block__.__id__;}; + _.m$_eql2=function(other){return this.__id__==other.__id__;}; + _.m$_brac=function(){return this.__block__.apply(this,arguments);}; + _.m$call=function(){return this.__block__.apply(this,arguments);}; + _.m$to_proc=function(){return(this);}; +}); + +Red._class('Range',c$Object,function(){ var _=c$Range.prototype; + var exclusive=$u; + _.m$initialize=function(start,finish,exclusive){exclusive=$T($.fi=exclusive)?$.fi:false;this.__start__=start;this.__end__=finish;this.__exclusive__=exclusive;}; + _.m$_eql2=function(object){if(object.constructor!==c$Range){return false;};return this.__start__.m$_eql2(object.__start__)&&this.__end__.m$_eql2(object.__end__)&&this.__exclusive__==object.__exclusive__;}; + _.m$_eql3=function(obj){var s=obj.m$_ltgt(this.__start__),e=obj.m$_ltgt(this.__end__);return s==0||s==1?(this.__exclusive__?e==-1:e==-1||e==0):false;}; + _.m$each=function(_block){var z=arguments[arguments.length-1],bg=m$block_given_bool(z),_block=bg?c$Proc.m$new(z):nil;var start=this.__start__,end=this.__end__;if(typeof(start)=='number'&&typeof(end)=='number'){if(!this.__exclusive__){end++;};for(var i=start;i<end;i++){try{_block.m$call(i);}catch(e){switch(e.__keyword__){case 'next':break;case 'break':return e.__return__;break;case 'redo':--i;break;default:throw(e);};};};};return(this);}; + _.m$hash=function(){return nil;}; + _.m$include_bool=function(obj){var s=obj.m$_ltgt(this.__start__),e=obj.m$_ltgt(this.__end__);return s==0||s==1?(this.__exclusive__?e==-1:e==-1||e==0):false;}; + _.m$inspect=function(){return $q(''+this.__start__.m$inspect()+(this.__exclusive__?'...':'..')+this.__end__.m$inspect());}; + _.m$last=function(){return this.__end__;}; + _.m$to_s=function(){return $q(''+this.__start__+(this.__exclusive__?'...':'..')+this.__end__);}; +}); + +Red._class('Regexp',c$Object,function(){ var _=c$Regexp.prototype; + c$Regexp.c$IGNORECASE=1; + c$Regexp.c$EXTENDED=2; + c$Regexp.c$MULTILINE=4; + c$Regexp.m$escape=function(str){$a(1,1,arguments,0);return $q(str.__value__.replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1'));}; + _.m$initialize=function(regexp,options){switch(options){case 0:this.__options__='';break;case 1:this.__options__='i';break;case 2:this.__options__='x';break;case 3:this.__options__='ix';break;case 4:this.__options__='s';break;case 5:this.__options__='si';break;case 6:this.__options__='sx';break;case 7:this.__options__='six';break;default:this.__options__=options?'i':'';};this.__source__=regexp.__value__||regexp;this.__value__=new(RegExp)(this.__source__,'m'+(/i/.test(this.__options__)?'i':''));}; + _.m$_eql2=function(rxp){return this.__source__===rxp.__source__&&this.__options__===rxp.__options__;}; + _.m$_eql3=function(string){var c=$u,result=c$MatchData.m$new();if(!$T(c=string.__value__.match(this.__value__))){return nil;};for(var i=0,l=c.length;i<l;++i){result.__captures__[i]=$q(c[i])};result.__string__=string.__value__;return(result);}; + _.m$hash=function(){return nil;}; + _.m$inspect=function(){return $q(''+this);}; + _.m$to_s=function(){var o=this.__options__.replace('s','m'),c=o.match(/(m)?(i)?(x)?/);return $q('(?'+o+(c[0]=='mix'?'':'-')+(c[1]?'':'m')+(c[2]?'':'i')+(c[3]?'':'x')+':'+this.__source__+')');}; +}); + +Red._class('String',c$Object,function(){ var _=c$String.prototype; + var string=$u,pattern=$u,limit=$u,base=$u; + _.m$initialize=function(string){string=$T($.fj=string)?$.fj:'';this.__value__=string.__value__||string;}; + _.m$_perc=function(arg){arg.m$class()==c$Array?arg.unshift(this):arg=[this,arg];return m$sprintf.apply(null,arg);}; + _.m$_plus=function(str){return $q(this.__value__ + str.__value__);}; + _.m$_ltlt=function(obj){this.__value__+=(typeof(obj)=='number'?String.fromCharCode(obj):obj.__value__);return(this);}; + _.m$_ltgt=function(str){if(str.m$class()!=c$String){return nil;};var tv=this.__value__,sv=str.__value__;if(tv>sv){return 1;};if(tv==sv){return 0;};if(tv<sv){return -1;};return(nil);}; + _.m$_eql2=function(str){if(str.m$class()!=c$String){return false;};return(this.m$_ltgt(str)==0);}; + _.m$_brac=function(){return nil;}; + _.m$_breq=function(){return nil;}; + _.m$delete=function(){return nil;}; + _.m$each=function(){return nil;}; + _.m$empty_bool=function(){return this.__value__=='';}; + _.m$hash=function(){return 'q_'+this.__value__;}; + _.m$include_bool=function(obj){return new(RegExp)(typeof(obj)=='number'?String.fromCharCode(obj):obj.__value__.replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1')).test(this.__value__);}; + _.m$inspect=function(){return $q('"'+this.__value__.replace(/\\/g,'\\\\').replace(/"/g,'\\"')+'"');}; + _.m$length=function(){return this.__value__.length;}; + _.m$size=function(){return this.__value__.length;}; + _.m$split=function(pattern,limit){pattern=$T($.fk=pattern)?$.fk:$r('\\s+',0);limit=$T($.fl=limit)?$.fl:nil;var a=this.__value__.split(pattern.__value__),result=[];for(var i=0,l=a.length;i<l;++i){result.push($q(a[i]));};return(result);}; + _.m$to_i=function(base){base=$T($.fm=base)?$.fm:10;var result=parseInt(this,base);return(result.toString()=='NaN'?0:result);}; + _.m$to_s=function(){return(this);}; + _.m$to_str=function(){return(this);}; + _.m$to_sym=function(){return $s(this.__value__);}; + _.m$upcase=function(){return $q(this.__value__.toUpperCase());}; +}); + +Red._class('Symbol',c$Object,function(){ var _=c$Symbol.prototype; + _.m$initialize=function(value){this.__value__=value;c$Symbol.__table__[value]=this;}; + _.m$hash=function(){return 's_'+this.__value__;}; + _.m$inspect=function(){return $q(''+this);}; + _.m$to_i=function(){return this.__id__;}; + _.m$to_s=function(){return $q(this.__value__);}; + _.m$to_sym=function(){return(this);}; + c$Symbol.__table__=new(Object); +}); + +Red._class('Time',c$Object,function(){ var _=c$Time.prototype; + _.m$initialize=function(){this.__value__=new(Date);}; + _.m$_plus=function(numeric){var t=c$Time.m$new();t.__value__=new(Date)(numeric*1000+this.__value__.valueOf());return(t);}; + _.m$_subt=function(time){return typeof(time)=='number'?new(Date)(this.__value__.valueOf()-(time*1000)):(this.__value__.valueOf()-time.__value__.valueOf())/1000;}; + _.m$_ltgt=function(time){var v=this.__value__.valueOf(),ms=typeof(time)=='number'?time*1000:time.__value__.valueOf();if(v<ms){return -1;};if(v==ms){return 0;};if(v>ms){return 1;};return(nil);}; + _.m$hash=function(){return 't_'+this.__value__.valueOf()/1000;}; + _.m$inspect=function(){return $q(''+this);}; + _.m$to_i=function(){return parseInt(this.__value__.valueOf()/1000);}; + _.m$to_s=function(){return $q(''+this.__value__);}; +}); + +Red._class('TrueClass',c$Object,function(){ var _=c$TrueClass.prototype; + _.m$_eql2=function(obj){return obj.valueOf&&obj.valueOf()===this.valueOf();}; + _.m$_eql3=function(obj){return obj.valueOf&&obj.valueOf()===this.valueOf();}; + _.m$hash=function(){return 'b_'+this.valueOf();}; + _.m$to_s=function(){return $q(''+this);}; +}); + +c$NilClass.prototype.toString=function(){return 'nil';}; +c$Range.prototype.toString=function(){return ''+this.__start__+(this.__exclusive__?'...':'..')+this.__end__;}; +c$Regexp.prototype.toString=function(){return '/'+this.__source__+'/'+(/s/.test(this.__options__)?'m':'')+(/i/.test(this.__options__)?'i':'')+(/x/.test(this.__options__)?'x':'');}; +c$String.prototype.toString=function(){return this.__value__;}; +c$Symbol.prototype.toString=function(){var v=this.__value__,str=/\s/.test(v)?'"'+v+'"':v;return ':'+str ;}; +c$Time.prototype.toString=function(){return ''+this.__value__;}; + + + +Red._module('Chainable',function(){ var _=c$Chainable.prototype; + _.m$call_chain=function(){for(var l=arguments.length,i=0,args=[];i<l;++i){args.push(arguments[i]);};this.i$chain=($T($.a=this.i$chain)?$.a:[]);if(!$T(this.i$chain.m$empty_bool())){return(this.i$chain.m$shift().__block__.apply(this,args));};return(false);}; + _.m$chain=function(block){var z=arguments[arguments.length-1],bg=m$block_given_bool(z),block=bg?c$Proc.m$new(z):nil;this.i$chain=($T($.b=this.i$chain)?$.b:[]);this.i$chain.m$_ltlt(block);return(this);}; + _.m$clear_chain=function(){this.i$chain=($T($.c=this.i$chain)?$.c:[]);this.i$chain.m$clear();return(this);}; +}); + +Red._module('Browser',function(){ var _=c$Browser.prototype; + c$Browser.c$Plugins=c$Hash.m$_brac(); + c$Browser.m$engine=function(){$a(0,0,arguments,0);return c$Hash.m$_brac($s("name"),c$Browser.c$Engine.m$instance_variable_get($q("@name")),$s("version"),c$Browser.c$Engine.m$instance_variable_get($q("@version")));}; + c$Browser.m$platform=function(){$a(0,0,arguments,0);return this.i$platform=($T($.d=this.i$platform)?$.d:$q(window.orientation==undefined?(navigator.platform.match(/mac|win|linux/i)||['other'])[0].toLowerCase():'ipod'));}; + + +Red._module('Browser.Features',function(){ var _=c$Browser.c$Features.prototype; + c$Browser.c$Features.__xpath__=!!(document.evaluate); + c$Browser.c$Features.__air__=!!(window.runtime); + c$Browser.c$Features.__query__=!!(document.querySelector); + _.m$xpath_bool=function(){return c$Browser.c$Features.__xpath__;}; + _.m$air_bool=function(){return c$Browser.c$Features.__air__;}; + _.m$query_bool=function(){return c$Browser.c$Features.__query__;}; +}); + + +Red._module('Browser.Engine',function(){ var _=c$Browser.c$Engine.prototype; + if($T(window.opera)){this.i$name=$q("presto");this.i$version=($T(document.getElementsByClassName)?950:925);}else{if($T(window.ActiveXObject)){this.i$name=$q("trident");this.i$version=($T(window.XMLHttpRequest)?5:4);}else{if($T(!navigator.taintEnabled)){this.i$name=$q("webkit");this.i$version=($T(c$Browser.c$Features.__xpath__)?($T(c$Browser.c$Features.__query__)?525:420):419);}else{if($T(document.getBoxObjectFor != null)){this.i$name=$q("gecko");this.i$version=($T(document.getElementsByClassName)?19:18);}else{this.i$name=$q("unknown");this.i$version=0;};};};}; + _.m$gecko_bool=function(version){return this.m$browser_bool($q("gecko"),version);}; + _.m$presto_bool=function(version){return this.m$browser_bool($q("presto"),version);}; + _.m$trident_bool=function(version){return this.m$browser_bool($q("trident"),version);}; + _.m$webkit_bool=function(version){return this.m$browser_bool($q("webkit"),version);}; + _.m$browser_bool=function(name,version){return (($.e=$T(c$Browser.c$Engine.m$instance_variable_get($q("@name")).m$_eql2(name)))?(($.g=$T($.f=($T(version)?c$Browser.c$Engine.m$instance_variable_get($q("@version")).m$_eql2(version):true)))?$.f:$.g):$.e);}; +}); +});(this.m$include||window.m$include).call(this,c$Browser.c$Engine);(this.m$include||window.m$include).call(this,c$Browser.c$Features); +Array.fromCollection = function(collection){ + for (var i = 0, a = [], j = collection.length; i < j; i++){ + a.push($E(collection[i])) + } + return a +}; +// used in several places where element/selector comparison is used +// tells whether an element matches another element or selector +Element.prototype.match = function(selector){ + if (!selector) return true; + var tagid = Selectors.Utils.parseTagAndID(selector); + var tag = tagid[0], id = tagid[1]; + if (!Selectors.Filters.byID(this, id) || !Selectors.Filters.byTag(this, tag)) return false; + var parsed = Selectors.Utils.parseSelector(selector); + return (parsed) ? Selectors.Utils.filter(this, parsed, {}) : true; +}; + +// Provides polymorphic access to getElementById to Elements as well as documents, both of which +// can be passed into Selectors.Utils.search as location for searching for subelements. +Element.prototype.getElementById = function(id, nocash){ + var el = this.ownerDocument.getElementById(id); + if (!el) return null; + for (var parent = el.parentNode; parent != this; parent = parent.parentNode){ + if (!parent) return null; + } + return $E(el); +}, + +Element.Attributes = { + Props: {'html': 'innerHTML', 'class': 'className', 'for': 'htmlFor', 'text': ((this.m$trident_bool||window.m$trident_bool).call(this)) ? 'innerText' : 'textContent'}, + Bools: ['compact', 'nowrap', 'ismap', 'declare', 'noshade', 'checked', 'disabled', 'readonly', 'multiple', 'selected', 'noresize', 'defer'], + Camels: ['value', 'accessKey', 'cellPadding', 'cellSpacing', 'colSpan', 'frameBorder', 'maxLength', 'readOnly', 'rowSpan', 'tabIndex', 'useMap'] +}; + +Element.prototype.getProperty = function(attribute){ + var EA = Element.Attributes, key = EA.Props[attribute]; + var value = (key) ? this[key] : this.getAttribute(attribute, 2); + return (EA.Bools[attribute]) ? !!value : (key) ? value : value || null; +}, + +String.prototype.contains = function(string, separator){ + return (separator) ? (separator + this + separator).indexOf(separator + string + separator) > -1 : this.indexOf(string) > -1; +}; + +String.prototype.trim = function(){ + return this.replace(/^ +| +$/g, ''); +}; + +var Selectors = {Cache: {nth: {}, parsed: {}}}; + +Selectors.RegExps = { + id: (/#([\w-]+)/), + tag: (/^(\w+|\*)/), + quick: (/^(\w+|\*)$/), + splitter: (/\s*([+>~\s])\s*([a-zA-Z#.*:\[])/g), + combined: (/\.([\w-]+)|\[(\w+)(?:([!*^$~|]?=)(["']?)([^\4]*?)\4)?\]|:([\w-]+)(?:\(["']?(.*?)?["']?\)|$)/g) +}; + +Selectors.Utils = { + // added to replace $uid + // uses internal Red.id + object_uid: function(item){ + return item.__id__||(item.__id__=Red.id++) + }, + + chk: function(item, uniques){ + if (!uniques) return true; + var uid = Selectors.Utils.object_uid(item); + if (!uniques[uid]) return uniques[uid] = true; + return false; + }, + + parseNthArgument: function(argument){ + if (Selectors.Cache.nth[argument]) return Selectors.Cache.nth[argument]; + var parsed = argument.match(/^([+-]?\d*)?([a-z]+)?([+-]?\d*)?$/); + if (!parsed) return false; + var inta = parseInt(parsed[1]); + var a = (inta || inta === 0) ? inta : 1; + var special = parsed[2] || false; + var b = parseInt(parsed[3]) || 0; + if (a != 0){ + b--; + while (b < 1) b += a; + while (b >= a) b -= a; + } else { + a = b; + special = 'index'; + } + switch (special){ + case 'n': parsed = {a: a, b: b, special: 'n'}; break; + case 'odd': parsed = {a: 2, b: 0, special: 'n'}; break; + case 'even': parsed = {a: 2, b: 1, special: 'n'}; break; + case 'first': parsed = {a: 0, special: 'index'}; break; + case 'last': parsed = {special: 'last-child'}; break; + case 'only': parsed = {special: 'only-child'}; break; + default: parsed = {a: (a - 1), special: 'index'}; + } + + return Selectors.Cache.nth[argument] = parsed; + }, + + parseSelector: function(selector){ + if (Selectors.Cache.parsed[selector]) return Selectors.Cache.parsed[selector]; + var m, parsed = {classes: [], pseudos: [], attributes: []}; + while ((m = Selectors.RegExps.combined.exec(selector))){ + var cn = m[1], an = m[2], ao = m[3], av = m[5], pn = m[6], pa = m[7]; + if (cn){ + parsed.classes.push(cn); + } else if (pn){ + var parser = Selectors.Pseudo[pn]; + + if (parser) parsed.pseudos.push({parser: parser, argument: pa}); + else parsed.attributes.push({name: pn, operator: '=', value: pa}); + } else if (an){ + parsed.attributes.push({name: an, operator: ao, value: av}); + } + } + if (!parsed.classes.length) delete parsed.classes; + if (!parsed.attributes.length) delete parsed.attributes; + if (!parsed.pseudos.length) delete parsed.pseudos; + if (!parsed.classes && !parsed.attributes && !parsed.pseudos) parsed = null; + return Selectors.Cache.parsed[selector] = parsed; + }, + + parseTagAndID: function(selector){ + var tag = selector.match(Selectors.RegExps.tag); + var id = selector.match(Selectors.RegExps.id); + return [(tag) ? tag[1] : '*', (id) ? id[1] : false]; + }, + + filter: function(item, parsed, local){ + var i; + if (parsed.classes){ + for (i = parsed.classes.length; i--; i){ + var cn = parsed.classes[i]; + if (!Selectors.Filters.byClass(item, cn)) return false; + } + } + if (parsed.attributes){ + for (i = parsed.attributes.length; i--; i){ + var att = parsed.attributes[i]; + if (!Selectors.Filters.byAttribute(item, att.name, att.operator, att.value)) return false; + } + } + if (parsed.pseudos){ + for (i = parsed.pseudos.length; i--; i){ + var psd = parsed.pseudos[i]; + if (!Selectors.Filters.byPseudo(item, psd.parser, psd.argument, local)) return false; + } + } + return true; + }, + + getByTagAndID: function(ctx, tag, id){ + if (id){ + var item = (ctx.getElementById) ? ctx.getElementById(id, true) : Element.getElementById(ctx, id, true); + return (item && Selectors.Filters.byTag(item, tag)) ? [item] : []; + } else { + return ctx.getElementsByTagName(tag); + } + }, + + search: function(self, expression, local){ + var splitters = []; + + var selectors = expression.trim().replace(Selectors.RegExps.splitter, function(m0, m1, m2){ + splitters.push(m1); + return ':)' + m2; + }).split(':)'); + + + var items, filtered, item; + for (var i = 0, l = selectors.length; i < l; i++){ + var selector = selectors[i]; + + if (i == 0 && Selectors.RegExps.quick.test(selector)){ + items = self.getElementsByTagName(selector); + continue; + } + + var splitter = splitters[i - 1]; + + var tagid = Selectors.Utils.parseTagAndID(selector); + var tag = tagid[0], id = tagid[1]; + if (i == 0){ + items = Selectors.Utils.getByTagAndID(self, tag, id); + } else { + var uniques = {}, found = []; + for (var j = 0, k = items.length; j < k; j++) found = Selectors.Getters[splitter](found, items[j], tag, id, uniques); + items = found; + } + + var parsed = Selectors.Utils.parseSelector(selector); + if (parsed){ + filtered = []; + for (var m = 0, n = items.length; m < n; m++){ + item = items[m]; + if (Selectors.Utils.filter(item, parsed, local)) filtered.push(item); + } + items = filtered; + } + + } + return items; + + } + +}; + +Selectors.Getters = { + + ' ': function(found, self, tag, id, uniques){ + var items = Selectors.Utils.getByTagAndID(self, tag, id); + for (var i = 0, l = items.length; i < l; i++){ + var item = items[i]; + if (Selectors.Utils.chk(item, uniques)) found.push(item); + } + return found; + }, + + '>': function(found, self, tag, id, uniques){ + var children = Selectors.Utils.getByTagAndID(self, tag, id); + for (var i = 0, l = children.length; i < l; i++){ + var child = children[i]; + if (child.parentNode == self && Selectors.Utils.chk(child, uniques)) found.push(child); + } + return found; + }, + + '+': function(found, self, tag, id, uniques){ + while ((self = self.nextSibling)){ + if (self.nodeType == 1){ + if (Selectors.Utils.chk(self, uniques) && Selectors.Filters.byTag(self, tag) && Selectors.Filters.byID(self, id)) found.push(self); + break; + } + } + return found; + }, + + '~': function(found, self, tag, id, uniques){ + + while ((self = self.nextSibling)){ + if (self.nodeType == 1){ + if (!Selectors.Utils.chk(self, uniques)) break; + if (Selectors.Filters.byTag(self, tag) && Selectors.Filters.byID(self, id)) found.push(self); + } + } + return found; + } + +}; + +Selectors.Filters = { + + byTag: function(self, tag){ + return (tag == '*' || (self.tagName && self.tagName.toLowerCase() == tag)); + }, + + byID: function(self, id){ + return (!id || (self.id && self.id == id)); + }, + + byClass: function(self, klass){ + return (self.className && self.className.contains(klass, ' ')); + }, + + byPseudo: function(self, parser, argument, local){ + return parser.call(self, argument, local); + }, + + byAttribute: function(self, name, operator, value){ + var result = Element.prototype.getProperty.call(self, name); + if (!result) return false; + if (!operator || value == undefined) return true; + switch (operator){ + case '=': return (result == value); + case '*=': return (result.contains(value)); + case '^=': return (result.substr(0, value.length) == value); + case '$=': return (result.substr(result.length - value.length) == value); + case '!=': return (result != value); + case '~=': return result.contains(value, ' '); + case '|=': return result.contains(value, '-'); + } + return false; + } + +}; + +Selectors.Pseudo = { + + // w3c pseudo selectors + + empty: function(){ + return !(this.innerText || this.textContent || '').length; + }, + + not: function(selector){ + return !Element.match(this, selector); + }, + + contains: function(text){ + return (this.innerText || this.textContent || '').contains(text); + }, + + 'first-child': function(){ + return Selectors.Pseudo.index.call(this, 0); + }, + + 'last-child': function(){ + var element = this; + while ((element = element.nextSibling)){ + if (element.nodeType == 1) return false; + } + return true; + }, + + 'only-child': function(){ + var prev = this; + while ((prev = prev.previousSibling)){ + if (prev.nodeType == 1) return false; + } + var next = this; + while ((next = next.nextSibling)){ + if (next.nodeType == 1) return false; + } + return true; + }, + + 'nth-child': function(argument, local){ + argument = (argument == undefined) ? 'n' : argument; + var parsed = Selectors.Utils.parseNthArgument(argument); + if (parsed.special != 'n') return Selectors.Pseudo[parsed.special].call(this, parsed.a, local); + var count = 0; + local.positions = local.positions || {}; + var uid = Selectors.Utils.object_uid(this); + if (!local.positions[uid]){ + var self = this; + while ((self = self.previousSibling)){ + if (self.nodeType != 1) continue; + count ++; + var position = local.positions[Selectors.Utils.object_uid(self)]; + if (position != undefined){ + count = position + count; + break; + } + } + local.positions[uid] = count; + } + return (local.positions[uid] % parsed.a == parsed.b); + }, + + // custom pseudo selectors + + index: function(index){ + var element = this, count = 0; + while ((element = element.previousSibling)){ + if (element.nodeType == 1 && ++count > index) return false; + } + return (count == index); + }, + + even: function(argument, local){ + return Selectors.Pseudo['nth-child'].call(this, '2n+1', local); + }, + + odd: function(argument, local){ + return Selectors.Pseudo['nth-child'].call(this, '2n', local); + } + +}; +;function $v(event){ + var doc=$u,result=$u,type=$u,target=$u,code=$u,key=$u,f_key=$u,wheel=$u,right_click=$u,page=$u,client=$u,related_target=$u; + event = event || window.event; + doc = document; + if(!event){return nil;}; + result=c$Event.m$new(null); + type = event.type; + target = event.target || event.srcElement; + while(target&&target.nodeType==3){target=event.parentNode;}; + if(/key/.test(type)){ + code=event.which || event.keyCode; + key=c$Event.c$KEYS.m$_brac(code); + if(type=='keydown'){f_key=code-111;if(f_key>0&&f_key<13){key=$s('f'+f_key);};}; + key=$T(key)?key:$s(String.fromCharCode(code).toLowerCase()); + }else{ + if(type.match(/(click|mouse|menu)/i)){ + doc=(!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body; + wheel=(type.match(/DOMMouseScroll|mousewheel/) ? (event.wheelDelta ? event.wheelDelta/40 : -(event.detail||0)) : nil); + right_click=event.which==3||event.button==2; + page={x:(event.pageX || event.clientX + doc.scrollLeft),y:(event.pageY || event.clientY + doc.scrollTop)}; + client={x:(event.pageX ? event.pageX - window.pageXOffset : event.clientX),y:(event.pageY ? event.pageY - window.pageYOffset : event.clientY)}; + if(type.match(/over|out/)){ + switch(type){ + case 'mouseover':related_target=event.relatedTarget || event.fromElement;break; + case 'mouseout':related_target=event.relatedTarget || event.toElement;break; + }; + if(window.m$gecko_bool()){ + try{while(related_target&&related_target.nodeType==3){related_target=related_target.parentNode;};}catch(e){related_target=false;}; + }else{while(related_target&&related_target.nodeType==3){related_target.parentNode;};}; + }; + }; + }; + result.__native__=event;result.__code__=code;result.__key__=key;result.__type__=type;result.__target__=target;result.__wheel__=wheel;result.__right_click__=right_click;result.__related_target__=related_target; + result.__page__=page||{x:nil,y:nil};result.__client__=client||{x:nil,y:nil}; + result.__shift__=event.shiftKey;result.__ctrl__=event.ctrlKey;result.__alt__=event.altKey;result.__meta__=event.metaKey; + return result; +}; + +Red._class('Event',c$Object,function(){ var _=c$Event.prototype; + c$Event.c$KEYS=c$Hash.m$_brac(8,$s("backspace"),9,$s("tab"),13,$s("enter"),27,$s("esc"),32,$s("space"),37,$s("left"),38,$s("up"),39,$s("right"),40,$s("down"),46,$s("delete")); + + +Red._class('Event.NewEventError',c$Exception,function(){ var _=c$Event.c$NewEventError.prototype; + ; +}); + _.m$initialize=function(raise_error){if(!$T(raise_error === null)){(this.m$raise||window.m$raise).call(this,c$Event.c$NewEventError,$q("Events can only be initialized by user interactions with the browser"));};}; + _.m$alt_bool=function(){return this.__alt__;}; + _.m$base_type=function(){return $s(this.__type__);}; + _.m$client=function(){return c$Hash.m$_brac($s("x"),this.__client__.x,$s("y"),this.__client__.y);}; + _.m$code=function(){return this.__code__ || nil;}; + _.m$ctrl_bool=function(){return this.__ctrl__;}; + _.m$key=function(){return this.__key__ || nil;}; + _.m$kill_bang=function(){return this.m$stop_propagation().m$prevent_default();}; + _.m$meta_bool=function(){return this.__meta__;}; + _.m$page=function(){return c$Hash.m$_brac($s("x"),this.__page__.x,$s("y"),this.__page__.y);}; + _.m$prevent_default=function(){var Native = this.__native__;Native.preventDefault?Native.preventDefault():Native.returnValue=false;return(this);}; + _.m$right_click_bool=function(){return this.__right_click__;}; + _.m$shift_bool=function(){return this.__shift__;}; + _.m$stop_propagation=function(){var Native = this.__native__;Native.stopPropagation?Native.stopPropagation():Native.cancelBubble=true;return(this);}; + _.m$target=function(){return $E(this.__target__);}; + _.m$wheel=function(){return this.__wheel__;}; +}); + +Red._module('UserEvents',function(){ var _=c$UserEvents.prototype; + var hash=$u,type=$u,events=$u,custom=$u,condition=$u,real_type=$u,listener=$u,native_event=$u; + c$UserEvents.mousecheck=function(element,event){ + var related=event.__related_target__,el=element.__native__; + if(related===nil||related==undefined){return true;}; + if(related===false){return false;}; + return((el!==document)&&(related!=el)&&(related.prefix!='xul')&&!(el.contains?el.contains(related):!!(el.compareDocumentPosition(el)&16))) + }; + c$UserEvents.c$NATIVE_EVENTS=c$Hash.m$_brac($s("click"),2,$s("dblclick"),2,$s("mouseup"),2,$s("mousedown"),2,$s("contextmenu"),2,$s("mousewheel"),2,$s("DOMMouseScroll"),2,$s("mouseover"),2,$s("mouseout"),2,$s("mousemove"),2,$s("selectstart"),2,$s("selectend"),2,$s("keydown"),2,$s("keypress"),2,$s("keyup"),2,$s("focus"),2,$s("blur"),2,$s("change"),2,$s("reset"),2,$s("select"),2,$s("submit"),2,$s("load"),1,$s("unload"),1,$s("beforeunload"),1,$s("resize"),1,$s("move"),1,$s("DOMContentLoaded"),1,$s("readystatechange"),1,$s("error"),1,$s("abort"),1,$s("scroll"),1); + c$UserEvents.c$DEFINED_EVENTS=c$Hash.m$_brac($s("mouse_enter"),c$Hash.m$_brac($s("base"),$q("mouseover"),$s("condition"),(this.m$proc||window.m$proc).call(this,c$UserEvents.mousecheck)),$s("mouse_leave"),c$Hash.m$_brac($s("base"),$q("mouseout"),$s("condition"),(this.m$proc||window.m$proc).call(this,c$UserEvents.mousecheck)),$s("mouse_wheel"),c$Hash.m$_brac($s("base"),($T((this.m$gecko_bool||window.m$gecko_bool).call(this))?$q("DOMMouseScroll"):$q("mousewheel")))); + c$UserEvents.m$define=function(sym,hash){$a(1,2,arguments,0);hash=$T($.h=hash)?$.h:c$Hash.m$_brac();c$UserEvents.c$DEFINED_EVENTS.m$_breq(sym.m$to_sym(),hash);return(true);}; + c$UserEvents.m$included=function(base){$a(1,1,arguments,0);return ($T(base.m$_eql2(c$Element))?nil:(this.m$raise||window.m$raise).call(this,c$TypeError,$q("only class Element and the singleton objects Window and Document may include UserEvents; use CodeEvents instead")));}; + c$UserEvents.m$extended=function(base){$a(1,1,arguments,0);return ($T([c$Document,c$Window].m$include_bool(base))?nil:(this.m$raise||window.m$raise).call(this,c$TypeError,$q("only Document and Window may be extended with UserEvents; use CodeEvents instead")));}; + _.m$listen=function(sym,block){var z=arguments[arguments.length-1],bg=m$block_given_bool(z),block=bg?c$Proc.m$new(z):nil;var type=$u,events=$u,custom=$u,condition=$u,real_type=$u,listener=$u,native_event=$u;type=sym.m$to_sym();events=this.i$events=($T($.j=this.i$events)?$.j:c$Hash.m$_brac());events.m$_breq(type,($T($.l=events.m$_brac(type))?$.l:c$Hash.m$_brac()));if($T(events.m$_brac(type).m$_brac(block))){return(this);};custom=c$UserEvents.c$DEFINED_EVENTS.m$_brac(type);condition=block;real_type=type;if($T(custom)){if($T(custom.m$_brac($s("on_listen")))){custom.m$_brac($s("on_listen")).m$call(this,block);};if($T(custom.m$_brac($s("condition")))){condition=(this.m$lambda||window.m$lambda).call(this,function(element,event){return ($T(custom.m$_brac($s("condition")).m$call(element,event))?block.m$call(element,event):true);}.m$(this));};real_type=($T($.q=custom.m$_brac($s("base")))?$.q:real_type).m$to_sym();};listener=(this.m$lambda||window.m$lambda).call(this,function(){return block.m$call(this,nil);}.m$(this));native_event=c$UserEvents.c$NATIVE_EVENTS.m$_brac(real_type);if($T(native_event)){if($T(native_event.m$_eql2(2))){listener=(this.m$lambda||window.m$lambda).call(this,function(native_event){event=$v(native_event);return ($T(condition.m$call(this,event).m$_eql2(false))?event.m$kill_bang():nil);}.m$(this));};this.m$add_listener(real_type,listener.m$to_proc().__block__);};events.m$_brac(type).m$_breq(block,listener);return(this);}; + _.m$add_listener=function(sym,block){var z=arguments[arguments.length-1],bg=m$block_given_bool(z),block=bg?c$Proc.m$new(z):nil;var el=this.__native__,type=sym.__value__,fn=block.__block__;if(type==='unload'){var old=fn,that=this;fn=function(){that.m$remove_listener($q('unload'),fn);old();};}else{var collected = {};collected[this.__id__]=this};if(el.addEventListener){el.addEventListener(type,fn,false);}else{el.attachEvent('on'+type,fn);};return(this);}; + _.m$unlisten=function(sym,block){var z=arguments[arguments.length-1],bg=m$block_given_bool(z),block=bg?c$Proc.m$new(z):nil;var type=$u,events=$u,listener=$u,custom=$u;type=sym.m$to_sym();events=this.i$events;if(!$T((($.ab=$T(events))?(($.ad=$T($.ac=(($.y=$T(events.m$_brac(type)))?(($.aa=$T($.z=events.m$_brac(type).m$_brac(block)))?$.z:$.aa):$.y)))?$.ac:$.ad):$.ab))){return(this);};listener=events.m$_brac(type).m$delete(block);custom=c$UserEvents.c$DEFINED_EVENTS.m$_brac(type);if($T(custom)){if($T(custom.m$_brac($s("on_unlisten")))){custom.m$_brac($s("on_unlisten")).m$call(this,block);};type=($T($.ag=custom.m$_brac($s("base")))?$.ag:type).m$to_sym();};if($T(c$UserEvents.c$NATIVE_EVENTS.m$_brac(type))){this.m$remove_listener(type,listener.m$to_proc().__block__);};return(this);}; + _.m$remove_listener=function(sym,block){var z=arguments[arguments.length-1],bg=m$block_given_bool(z),block=bg?c$Proc.m$new(z):nil;var el=this.__native__,type=sym.__value__,fn=block.__block__;if(this.removeEventListener){this.removeEventListener(type,fn,false);}else{this.detachEvent('on'+type,fn);};return(this);}; +}); + +Red._module('Window',function(){ var _=c$Window.prototype; + this.__native__ = window; + c$Window.m$window=function(){$a(0,0,arguments,0);return c$Window;}; + c$Window.m$document=function(){$a(0,0,arguments,0);return c$Document;}; +}); + +Red._module('Document',function(){ var _=c$Document.prototype; + document.head=document.getElementsByTagName('head')[0]; + document.html=document.getElementsByTagName('html')[0]; + document.window=(document.defaultView||document.parentWindow); + c$Document.__native__= document; + c$Document.m$_brac=function(){for(var l=arguments.length,i=0,args=[];i<l;++i){args.push(arguments[i]);};$a(0,-1,arguments,0);if($T(args.m$length().m$_eql2(1))){return(c$Document.m$find_by_string(args.m$_brac(0)));}else{args.m$map(function(str){return c$Document.m$_brac(str);}.m$(this)).m$compact();};}; + c$Document.m$body=function(){$a(0,0,arguments,0);return $E(document.body);}; + c$Document.m$execute_js=function(str){$a(1,1,arguments,0);if($T(str.m$_eql2($q("")))){return(str);};if($T(window.execScript)){window.execScript(str.__value__);}else{scriptElement = document.createElement('script');scriptElement.setAttribute('type','text/javascript');scriptElement.text = str;document.head.appendChild(scriptElement);document.head.removeChild(scriptElement);};return(str);}; + c$Document.m$head=function(){$a(0,0,arguments,0);return $E(document.head);}; + c$Document.m$html=function(){$a(0,0,arguments,0);return $E(document.html);}; + c$Document.m$ready_bool=function(block){var z=arguments[arguments.length-1],bg=m$block_given_bool(z),block=bg?c$Proc.m$new(z):nil;$a(0,0,arguments,bg?1:0);this.i$proc=block;document.addEventListener('DOMContentLoaded', function(){document.__loaded__=true;this.i$proc.m$call();}.m$(this), false);return(nil);}; + c$Document.m$title=function(){$a(0,0,arguments,0);return $q(document.title);}; + c$Document.m$find_all_by_selector=function(selector){$a(1,1,arguments,0);return Array.fromCollection(Selectors.Utils.search(document, selector.__value__, {}));;}; + c$Document.m$find_by_id=function(str){$a(1,1,arguments,0);return $E(document.getElementById(str.__value__));}; + c$Document.m$find_by_string=function(str){$a(1,1,arguments,0);return ($T(str.__value__.match(/^#[a-zA-z_]*$/))?c$Document.m$find_by_id($q(str.__value__.replace('#',''))):c$Document.m$find_all_by_selector(str));}; + c$Document.m$find_many_with_array=function(ary){$a(1,1,arguments,0);for(var i=0,l=ary.length,result=[];i<l;++i){var el=c$Document.m$_brac(ary[i]);if($T(el)){result.push(el);};};return(result.m$flatten());}; + c$Document.m$walk=function(element,path,startRelation,matchSelector,all){$a(5,5,arguments,0);if(startRelation){startRelation = startRelation.__value__;}; + var el = element.__native__[startRelation || path.__value__],elements = []; + while (el){ + if (el.nodeType == 1 && (!$T(matchSelector) || Element.match(el, matchSelector))){ + if (!all) {return $E(el);} + elements.push($E(el)); + } + el = el[path.__value__]; + };return((all) ? elements : nil);}; + c$Document.m$window=function(){$a(0,0,arguments,0);return c$Window;}; + c$Document.m$document=function(){$a(0,0,arguments,0);return c$Document;}; +}); + +Red._class('Cookie',c$Object,function(){ var _=c$Cookie.prototype; + var options=$u,value=$u; + c$Cookie.c$OPTIONS=c$Hash.m$_brac($s("duration"),nil,$s("domain"),nil,$s("path"),nil,$s("secure"),false,$s("document"),c$Document); + (this.m$attr_accessor||window.m$attr_accessor).call(this,$s("key"),$s("value"),$s("duration"),$s("domain"),$s("path"),$s("secure"),$s("document")); + _.m$initialize=function(key,value,options){options=$T($.ai=options)?$.ai:c$Hash.m$_brac();this.m$key_eql(key);this.m$update(value,c$Cookie.c$OPTIONS.m$merge(options));}; + c$Cookie.m$read=function(key){$a(1,1,arguments,0);var value=$u;value=c$Cookie.c$OPTIONS.m$_brac($s("document")).__native__.cookie.match('(?:^|;)\s*' + c$Regexp.m$escape(key).__value__ + '=([^;]*)');return(($T(value)?$q(decodeURIComponent(value[1])):nil));}; + c$Cookie.m$store=function(cookie){$a(1,1,arguments,0);var str = cookie.m$key().__value__ + '=' + encodeURIComponent(cookie.m$value().__value__);if($T(cookie.m$domain())){str += '; domain=' + cookie.m$domain().__value__;};if($T(cookie.m$path())){str += '; path=' + cookie.m$path().__value__;};if($T(cookie.m$duration())){date = new Date();date.setTime(date.getTime() + cookie.m$duration() * 86400000);str += '; expires=' + date.toGMTString();};if($T(cookie.m$secure())){str += '; secure';};cookie.m$document().__native__.cookie = str;return(cookie);}; + _.m$destroy=function(){return this.m$update($q(""),c$Hash.m$_brac($s("duration"),-1));}; + _.m$inspect=function(){return $Q("#<Cookie: @key=",this.m$key().m$inspect()," @value=",this.m$value().m$inspect(),">");}; + _.m$update=function(value,options){options=$T($.ak=options)?$.ak:c$Hash.m$_brac();this.m$value_eql(value);options.m$each(function(k,v){return this.m$send($Q("",k,"="),v);}.m$(this));return c$Cookie.m$store(this);}; +});false; + +Red._module('CodeEvents',function(){ var _=c$CodeEvents.prototype; + var name=$u,events_group=$u; + _.m$fire=function(sym,delay){for(var l=arguments.length,i=2,args=[];i<l;++i){args.push(arguments[i]);};var name=$u,events_group=$u;name=sym.m$to_sym();if(!$T((($.an=$T(this.i$code_events))?(($.ap=$T($.ao=events_group=this.i$code_events.m$_brac(name)))?$.ao:$.ap):$.an))){return(this);};events_group.m$each(function(proc){var f=function(){return proc.__block__.apply(null,args);};if(delay){return setTimeout(f,delay);};return f();}.m$(this));return(this);}; + _.m$ignore=function(sym,block){var z=arguments[arguments.length-1],bg=m$block_given_bool(z),block=bg?c$Proc.m$new(z):nil;var name=$u,events_group=$u;if($T(sym)){name=sym.m$to_sym();if(!$T((($.at=$T(this.i$code_events))?(($.av=$T($.au=events_group=this.i$code_events.m$_brac(name)))?$.au:$.av):$.at))){return(this);};if($T(block)){if(!$T(block.__block__.__unignorable__)){events_group.m$delete(block);};}else{events_group.m$each(function(proc){return this.m$disregard(name,proc.m$to_proc().__block__);}.m$(this));};}else{this.i$code_events.m$each_key(function(name){return this.m$disregard(name);}.m$(this));};return(this);}; + _.m$upon=function(sym_or_hash,unignorable,block){var z=arguments[arguments.length-1],bg=m$block_given_bool(z),block=bg?c$Proc.m$new(z):nil;var name=$u;if($T(sym_or_hash.m$instance_of_bool(c$Hash))){sym_or_hash.m$each(function(name,proc){return this.m$upon(name,proc.m$to_proc().__block__);}.m$(this));return(this);}else{name=sym_or_hash.m$to_sym();this.i$code_events=($T($.ax=this.i$code_events)?$.ax:c$Hash.m$_brac());this.i$code_events.m$_breq(name,($T($.ay=this.i$code_events.m$_brac(name))?$.ay:[]));this.i$code_events.m$_brac(name).m$_ltlt(block);block.__block__.__unignorable__=typeof(unignorable)=='function'?false:unignorable;return(this);};}; +}); + +Red._class('Request',c$Object,function(){ var _=c$Request.prototype; + var options=$u,method=$u,data=$u,url=$u,format=$u,_method=$u,encoding=$u,separator=$u,evaluate=$u,scripts=$u,result=$u,base=$u,query_string=$u; + (this.m$include||window.m$include).call(this,c$CodeEvents); + (this.m$include||window.m$include).call(this,c$Chainable); + c$Request.c$METHODS=[$q("GET"),$q("POST"),$q("PUT"),$q("DELETE")]; + c$Request.c$OPTIONS=c$Hash.m$_brac($s("url"),$q(""),$s("data"),c$Hash.m$_brac(),$s("link"),$q("ignore"),$s("async"),true,$s("format"),nil,$s("method"),$q("post"),$s("encoding"),$q("utf-8"),$s("is_success"),nil,$s("emulation"),true,$s("url_encoded"),true,$s("eval_scripts"),false,$s("eval_response"),false,$s("headers"),c$Hash.m$_brac($q("X-Requested-With"),$q("XMLHttpRequest"),$q("Accept"),$q("text/javascript, text/html, application/xml, text/xml, */*"))); + + +Red._class('Request.Response',c$Object,function(){ var _=c$Request.c$Response.prototype; + (this.m$attr||window.m$attr).call(this,$s("text"),$s("xml")); + _.m$initialize=function(text,xml){this.i$text=text;this.i$xml=xml;}; +}); + _.m$initialize=function(options){options=$T($.az=options)?$.az:c$Hash.m$_brac();this.__xhr__ = typeof(ActiveXObject)=='undefined' ? new XMLHttpRequest : new ActiveXObject('MSXML2.XMLHTTP');this.i$options=c$Request.c$OPTIONS.m$merge(options);this.i$options.m$_brac($s("headers")).__xhr__=this.__xhr__;}; + _.m$cancel=function(){if(!$T(this.i$running)){return(this);};this.i$running=false;this.__xhr__.abort;this.__xhr__.onreadystatechange=function(){;};this.__xhr__=typeof(ActiveXObject)=='undefined' ? new XMLHttpRequest : new ActiveXObject('MSXML2.XMLHTTP');this.m$fire($s("cancel"));return(this);}; + _.m$check=function(block){for(var l=arguments.length,bg=m$block_given_bool(arguments[l-1]),l=bg?l-1:l,i=0,args=[];i<l;++i){args.push(arguments[i]);};var block=(bg?c$Proc.m$new(arguments[arguments.length-1]):nil);if(!$T(this.i$running)){return(true);};var _switch=(this.i$options.m$_brac($s("link")));if($q("cancel").m$_eql3(_switch)){this.m$cancel();return(true);}else{if($q("chain").m$_eql3(_switch)){return(false);}else{;};};return(false);}; + _.m$execute=function(options){options=$T($.ba=options)?$.ba:c$Hash.m$_brac();var method=$u,data=$u,url=$u,format=$u,_method=$u,encoding=$u,separator=$u;this.i$options.m$update(options);if(!$T([c$String].m$include_bool(this.i$options.m$_brac($s("url")).m$class()))){(this.m$raise||window.m$raise).call(this,c$TypeError,$q("can't convert %s to a String").m$_perc(this.i$options.m$_brac($s("url")).m$inspect()));};if(!$T([c$String,c$Symbol].m$include_bool(this.i$options.m$_brac($s("method")).m$class()))){(this.m$raise||window.m$raise).call(this,c$TypeError,$q("can't convert %s to a String").m$_perc(this.i$options.m$_brac($s("method")).m$inspect()));};if(!$T([c$Hash].m$include_bool(this.i$options.m$_brac($s("data")).m$class()))){(this.m$raise||window.m$raise).call(this,c$TypeError,$q("can't convert %s to a Hash").m$_perc(this.i$options.m$_brac($s("data")).m$inspect()));};if(!$T(c$Request.c$METHODS.m$include_bool(method=this.i$options.m$_brac($s("method")).m$to_s().m$upcase()))){(this.m$raise||window.m$raise).call(this,c$Request.c$HttpMethodError,$q("invalid HTTP method \"%s\" for %s").m$_perc([this.i$options.m$_brac($s("method")),this]));};this.i$running=true;data=this.i$options.m$_brac($s("data")).m$to_query_string();url=this.i$options.m$_brac($s("url"));if($T(this.i$options.m$_brac($s("format")))){format=$q("format=%s").m$_perc(this.i$options.m$_brac($s("format")));data=($T(data.m$empty_bool())?format:[format,data].m$join($q("&")));};if($T((($.bg=$T(this.i$options.m$_brac($s("emulation"))))?(($.bi=$T($.bh=[$q("PUT"),$q("DELETE")].m$include_bool(method)))?$.bh:$.bi):$.bg))){_method=$q("_method=%s").m$_perc(method);data=($T(data.m$empty_bool())?_method:[_method,data].m$join($q("&")));method=$q("POST");};if($T((($.bm=$T(this.i$options.m$_brac($s("url_encoded"))))?(($.bo=$T($.bn=method.m$_eql2($q("POST"))))?$.bn:$.bo):$.bm))){encoding=($T(this.i$options.m$_brac($s("encoding")))?$q("; charset=%s").m$_perc(this.i$options.m$_brac($s("encoding"))):$q(""));this.m$headers().m$_breq($q("Content-type"),$q("application/x-www-form-urlencoded").m$_plus(encoding));};if($T((($.bq=$T(data))?(($.bs=$T($.br=method.m$_eql2($q("GET"))))?$.br:$.bs):$.bq))){separator=($T(url.m$include_bool($q("?")))?$q("&"):$q("?"));url=[url,data].m$join(separator);data=nil;};this.__xhr__.open(method.__value__, url.__value__, this.i$options.m$_brac($s("async")));this.__xhr__.onreadystatechange = this.m$on_state_change().__block__;this.i$options.m$_brac($s("headers")).m$each(function(k,v){return this.__xhr__.setRequestHeader(k.__value__,v.__value__);}.m$(this));this.m$fire($s("request"));this.__xhr__.send($T(data)?data.__value__:'');if(!$T(this.i$options.m$_brac($s("async")))){this.m$on_state_change().m$call();};return(this);}; + _.m$headers=function(){return this.i$options.m$_brac($s("headers"));}; + _.m$on_state_change=function(){return c$Proc.m$new(function(){var xhr=this.__xhr__;if(xhr.readyState!=4||!this.i$running){return nil;};this.i$running=false;this.i$status=0;try{this.i$status=xhr.status}catch(e){;};if($T(this.m$success_bool())){this.i$response=c$Request.c$Response.m$new(this.m$process_scripts($q(xhr.responseText)),xhr.responseXML);this.m$fire($s("response"),0,this.i$response).m$fire($s("success"),0,this.i$response).m$call_chain();}else{this.i$response=c$Request.c$Response.m$new(nil,nil);this.m$fire($s("response"),0,this.i$response).m$fire($s("failure"),0,this.i$xhr);};xhr.onreadystatechange=function(){;};return(nil);}.m$(this));}; + _.m$process_scripts=function(str){if($T(($T($.bw=this.i$options.m$_brac($s("eval_response")))?$.bw:/(ecma|java)script/.test(this.__xhr__.getResponseHeader('Content-Type'))))){return(c$Document.m$execute_js(str));};return(str.m$strip_scripts(this.i$options.m$_brac($s("eval_scripts"))));}; + _.m$success_bool=function(){return this.i$status>=200&&this.i$status<300;}; + + +Red._class('Request.HeaderError',c$StandardError,function(){ var _=c$Request.c$HeaderError.prototype; + ; +}); + + +Red._class('Request.HttpMethodError',c$StandardError,function(){ var _=c$Request.c$HttpMethodError.prototype; + ; +}); + + +Red._class('String',c$Object,function(){ var _=c$String.prototype; + var evaluate=$u,scripts=$u,result=$u; + _.m$strip_scripts=function(evaluate){evaluate=$T($.bx=evaluate)?$.bx:false;var scripts=$u,result=$u;scripts=$q("");result=$q(this.__value__.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi,function(){scripts.__value__+=arguments[1]+'\n';return '';}));if($T(evaluate)){c$Document.m$execute_js(scripts);};return(result);}; +}); + + +Red._class('Hash',c$Object,function(){ var _=c$Hash.prototype; + var base=$u,query_string=$u; + _.m$to_query_string=function(base){base=$T($.ca=base)?$.ca:$q("");var query_string=$u;query_string=[];this.m$each(function(k,v){if($T(v.m$nil_bool())){Red.LoopError._next();};k=($T(base.m$empty_bool())?k.m$to_s():$q("%s[%s]").m$_perc([base,k]));var _switch=(v);if(c$Hash.m$_eql3(_switch)){result=v.m$to_query_string(k);}else{if(c$Array.m$_eql3(_switch)){qs=c$Hash.m$_brac();for(var i=0,l=v.length;i<l;i++){qs.m$_breq((this.m$i||window.m$i).call(this),v.m$_brac((this.m$i||window.m$i).call(this)))};result=qs.m$to_query_string(k);}else{result=$q("%s=%s").m$_perc([k,$q(encodeURIComponent(v))]);};};return query_string.m$push(result);}.m$(this));return(query_string.m$join($q("&")));}; +}); + + +Red._class('Request.HTML',c$Object,function(){ var _=c$Request.c$HTML.prototype; + ; +}); + + +Red._class('Request.JSON',c$Object,function(){ var _=c$Request.c$JSON.prototype; + ; +}); +});false;false;false;false; + +Red._class('Element',c$Object,function(){ var _=c$Element.prototype; + c$Element.__keyed_attributes__={'class':'className','for':'htmlFor'}; + c$Element.__boolean_attributes__={checked:'checked',declare:'declare',defer:'defer',disabled:'disabled',ismap:'ismap',multiple:'multiple',noresize:'noresize',noshade:'noshade',readonly:'readonly',selected:'selected'}; + _.m$add_class=function(sym){if(!this.m$has_class_bool(sym)){var el=this.__native__,c=el.className,s=sym.__value__;el.className=(c.length>0)?c+' '+s:s;};return(this);}; + _.m$add_classes=function(){for(var l=arguments.length,i=0,args=[];i<l;++i){args.push(arguments[i]);};args.m$each(function(x){return this.m$add_class(x);}.m$(this));return(this);}; + _.m$class=function(){return $q(this.__native__.className);}; + _.m$class_eql=function(str){this.__native__.className=str.__value__;return(str);}; + _.m$classes=function(){return this.i$class_list=($T($.ch=this.i$class_list)?$.ch:c$Element.c$Classes.m$new(this));}; + _.m$classes_eql=function(ary){for(var result=[],i=0,l=ary.length;i<l;++i){result.push(ary[i].__value__);};this.__native__.className=result.join(' ');return(ary);}; + _.m$clear_styles=function(){this.__native__.style.cssText='';return(this);}; + _.m$get_property=function(attribute){var el=this.__native__,attr=attribute.__value__,key=c$Element.__keyed_attributes__[attr],bool=c$Element.__boolean_attributes__[attr];var value=key||bool?el[key||bool]:el.getAttribute(attr,2);return(bool ? !!value : (value==null) ? nil : $q(value));}; + _.m$get_style=function(attribute){var el=this.__native__,attr=attribute.__value__.replace(/[_-]\D/g, function(match){return match.charAt(1).toUpperCase();}),result=el.style[attr];return result===undefined?nil:$q(result);}; + _.m$has_class_bool=function(sym){var str=' '+this.__native__.className+' ',match=' '+sym.__value__+' ';return str.indexOf(match) > -1;}; + _.m$html=function(){return $q(this.__native__.innerHTML);}; + _.m$html_eql=function(str){this.__native__.innerHTML=str.__value__;return(str);}; + _.m$properties=function(){return this.i$properties=($T($.ci=this.i$properties)?$.ci:c$Element.c$Properties.m$new(this));}; + _.m$remove_class=function(sym){var el=this.__native__,klass=sym.__value__;el.className=el.className.replace(new(RegExp)('(^|\\s)'+klass+'(?:\\s|$)'),'$1');return(this);}; + _.m$remove_classes=function(){for(var l=arguments.length,i=0,args=[];i<l;++i){args.push(arguments[i]);};args.m$each(function(x){return this.m$remove_class(x);}.m$(this));return(this);}; + _.m$remove_property=function(attribute){var el=this.__native__,attr=attribute.__value__,bool=c$Element.__boolean_attributes__[attr],key=c$Element.__boolean_attributes__[attr]||bool;key ? el[key]=bool?false:'' : el.removeAttribute(attr);return(this);}; + _.m$remove_properties=function(){for(var l=arguments.length,i=0,args=[];i<l;++i){args.push(arguments[i]);};args.m$each(function(x){return this.m$remove_property(x);}.m$(this));return(this);}; + _.m$remove_style=function(attribute){var attr=attribute.__value__.replace(/[_-]\D/g, function(match){return match.charAt(1).toUpperCase();});this.__native__.style[attr]=null;return(this);}; + _.m$remove_styles=function(){for(var l=arguments.length,i=0,args=[];i<l;++i){args.push(arguments[i]);};args.m$each(function(x){return this.m$remove_style(x);}.m$(this));return(this);}; + _.m$set_property=function(attribute,value){var el=this.__native__,attr=attribute.__value__,bool=c$Element.__boolean_attributes__[attr],key=c$Element.__boolean_attributes__[attr]||bool;key ? el[key]=bool?$T(value):value : el.setAttribute(attr,''+value);return(this);}; + _.m$set_properties=function(hash){hash.m$each(function(k,v){return this.m$set_property(k,v);}.m$(this));return(this);}; + _.m$set_style=function(attribute,value){var attr=attribute.__value__.replace(/[_-]\D/g, function(match){return match.charAt(1).toUpperCase();}),val=value.__value__||value;if(attr==='float'){val=(this.m$trident_bool||window.m$trident_bool).call(this)?'styleFloat':'cssFloat'};if(attr==='opacity'){m$raise("nobody wrote the opacity setter yet!");};if(val===String(Number(val))){val=Math.round(val)};this.__native__.style[attr]=val;return(this);}; + _.m$set_styles=function(hash){hash.m$each(function(k,v){return this.m$set_style(k,v);}.m$(this));return(this);}; + _.m$style=function(){return $q(this.__native__.style.cssText);}; + _.m$style_eql=function(str){this.__native__.style.cssText=str.__value__;return(str);}; + _.m$styles=function(){return this.i$styles=($T($.cj=this.i$styles)?$.cj:c$Element.c$Styles.m$new(this));}; + _.m$text=function(){return $q((this.m$trident_bool||window.m$trident_bool).call(this) ? this.__native__.innerText : this.__native__.textContent);}; + _.m$text_eql=function(str){if($T((this.m$trident_bool||window.m$trident_bool).call(this))){this.__native__.innerText=str.__value__;}else{this.__native__.textContent=str.__value__;};return(str);}; + _.m$toggle_class=function(sym){if($T(this.m$has_class_bool(sym))){this.m$remove_class(sym);}else{this.m$add_class(sym);};return(this);}; + + +Red._class('Element.Classes',c$Object,function(){ var _=c$Element.c$Classes.prototype; + _.m$initialize=function(element){this.i$element=element;}; + _.m$_ltlt=function(sym){c$Element.prototype.m$add_class.call(this.i$element,sym);return(this);}; + _.m$include_bool=function(sym){return c$Element.prototype.m$has_class_bool.call(this.i$element,sym);}; + _.m$toggle=function(sym){c$Element.prototype.m$toggle_class.call(this.i$element,sym);return(this.i$element);}; +}); + + +Red._class('Element.Properties',c$Object,function(){ var _=c$Element.c$Properties.prototype; + _.m$initialize=function(element){this.i$element=element;}; + _.m$_brac=function(attribute){return c$Element.prototype.m$get_property.call(this.i$element,attribute);}; + _.m$_breq=function(attribute,value){return c$Element.prototype.m$set_property.call(this.i$element,attribute,value);}; + _.m$delete=function(attribute){return c$Element.prototype.m$remove_property.call(this.i$element,attribute);}; + _.m$set_bool=function(attribute){return $T(c$Element.prototype.m$get_property.call(this.i$element,attribute));}; + _.m$update=function(hash){c$Element.prototype.m$set_properties.call(this.i$element,hash);return(this);}; +}); + + +Red._class('Element.Styles',c$Object,function(){ var _=c$Element.c$Styles.prototype; + _.m$initialize=function(element){this.i$element=element;}; + _.m$_brac=function(attribute){return c$Element.prototype.m$get_style.call(this.i$element,attribute);}; + _.m$_breq=function(attribute,value){return c$Element.prototype.m$set_style.call(this.i$element,attribute,value);}; + _.m$clear=function(){return c$Element.prototype.m$clear_styles.call(this.i$element);}; + _.m$delete=function(attribute){return c$Element.prototype.m$remove_style.call(this.i$element,attribute);}; + _.m$set_bool=function(attribute){return $T(c$Element.prototype.m$get_style.call(this.i$element,attribute));}; + _.m$update=function(hash){c$Element.prototype.m$set_styles.call(this.i$element,hash);return(this);}; +}); +}); + +Red._class('Element',c$Object,function(){ var _=c$Element.prototype; + var attributes=$u,expression=$u,items=$u,match_selector=$u,where=$u; + window.$E=function(element){if(element==null){return nil;};var E=c$Element.m$new(null);E.__native__=element;return E;}; + (this.m$include||window.m$include).call(this,c$UserEvents); + (this.m$include||window.m$include).call(this,c$CodeEvents); + c$Element.m$destroy=function(elem){$a(1,1,arguments,0);var el = elem.__native__ || elem;c$Element.m$empty(el);c$Element.m$remove(el);return(true);}; + c$Element.m$empty=function(elem){$a(1,1,arguments,0);for (var c=(elem.__native__||elem).childNodes,i=c.length;i>0;){c$Element.m$destroy(c[--i]);};;return(true);}; + c$Element.m$remove=function(elem){$a(1,1,arguments,0);var el = elem.__native__ || elem;return (el.parentNode) ? el.parentNode.removeChild(el) : this;}; + _.m$initialize=function(tag,attributes){attributes=$T($.ck=attributes)?$.ck:c$Hash.m$_brac();if(!tag){return nil;};this.__native__ = document.createElement(tag.__value__);this.m$set_properties(attributes);}; + _.m$_eql2=function(elem){return this.__native__ === elem.__native__;}; + _.m$_eql3=function(elem){return this.__native__ === elem.__native__;}; + _.m$_brac=function(expression){for(var l=arguments.length,i=1,args=[];i<l;++i){args.push(arguments[i]);};var items=$u;if (expression.__value__.match(/^#[a-zA-z_]*$/) && args.m$empty_bool()){return this.__native__.getElementById(expression.__value__.replace('#',''));};expression=expression.m$split($q(","));items=[];for (var i = 0, l = expression.length, local = {}; i < l; i++){ + var selector = expression[i].__value__, elements = Selectors.Utils.search(this.__native__, selector, local); + elements = Array.fromCollection(elements); + items = (i == 0) ? elements : items.concat(elements); + };return(items);}; + _.m$children=function(match_selector){match_selector=$T($.cn=match_selector)?$.cn:nil;return c$Document.m$walk(this,$q("nextSibling"),$q("firstChild"),match_selector,true);}; + _.m$destroy_bang=function(){c$Element.m$destroy(this);return(true);}; + _.m$document=function(){return this.__native__.ownerDocument;}; + _.m$empty_bang=function(){c$Element.m$empty(this);return(this);}; + _.m$eql_bool=function(elem){return this.__native__ === elem.__native__;}; + _.m$first_child=function(match_selector){match_selector=$T($.co=match_selector)?$.co:nil;return c$Document.m$walk(this,$q("nextSibling"),$q("firstChild"),match_selector,false);}; + _.m$insert=function(element,where){where=$T($.cp=where)?$.cp:$s("bottom");this.m$send($Q("insert_",where.m$to_s()),element);return(this);}; + _.m$insert_after=function(element){if (!element.parentNode) return;next = this.__native__.nextSibling;(next) ? this.__native__.parentNode.insertBefore(element.__native__, next) : this__native__.parentNode.appendChild(element.__native__);return(true);}; + _.m$insert_before=function(element){if (this.__native__.parentNode) this.__native__.parentNode.insertBefore(element.__native__, this.__native__);return(true);}; + _.m$insert_bottom=function(element){this.__native__.appendChild(element.__native__);return(true);}; + _.m$insert_inside=_.m$insert_bottom; + _.m$insert_top=function(element){first = this.__native__.firstChild;(first) ? this.__native__.insertBefore(element.__native__, first) : this.__native__.appendChild(element.__native__);return(true);}; + _.m$inspect=function(){var attributes=$u;attributes=[$q(this.__native__.tagName.toUpperCase())];if($T(this.__native__.id!=='')){attributes.m$_ltlt($q('id="'+this.__native__.id+'"'));};if($T(this.__native__.className!=='')){attributes.m$_ltlt($q('class="'+this.__native__.className+'"'));};return $q("#<Element: %s>").m$_perc(attributes.m$join($q(" ")));}; + _.m$is_body_bool=function(){return (/^(?:body|html)$/i).test(this.__native__.tagName);}; + _.m$last_child=function(match_selector){match_selector=$T($.cr=match_selector)?$.cr:nil;return c$Document.m$walk(this,$q("previousSibling"),$q("lastChild"),match_selector,false);}; + _.m$next_element=function(match_selector){match_selector=$T($.cs=match_selector)?$.cs:nil;return c$Document.m$walk(this,$q("nextSibling"),nil,match_selector,false);}; + _.m$next_elements=function(match_selector){match_selector=$T($.ct=match_selector)?$.ct:nil;return c$Document.m$walk(this,$q("nextSibling"),nil,match_selector,true);}; + _.m$parent=function(match_selector){match_selector=$T($.cu=match_selector)?$.cu:nil;return c$Document.m$walk(this,$q("parentNode"),nil,match_selector,false);}; + _.m$parents=function(match_selector){match_selector=$T($.cv=match_selector)?$.cv:nil;return c$Document.m$walk(this,$q("parentNode"),nil,match_selector,true);}; + _.m$previous_element=function(match_selector){match_selector=$T($.cw=match_selector)?$.cw:nil;return c$Document.m$walk(this,$q("previousSibling"),nil,match_selector,false);}; + _.m$previous_elements=function(match_selector){match_selector=$T($.cx=match_selector)?$.cx:nil;return c$Document.m$walk(this,$q("previousSibling"),nil,match_selector,true);}; + _.m$remove_bang=function(){c$Element.m$remove(this);return(this);}; + _.m$to_s=function(){return nil;}; +});false; + +Red._module('Situated',function(){ var _=c$Situated.prototype; + var element=$u,h=$u,relative_to=$u,offset=$u,scroll=$u,position=$u,relative_position=$u,a=$u,win=$u,doc=$u,min=$u,size=$u; + window.styleString=function(el,prop){if(el.currentStyle){return el.currentStyle[prop.replace(/[_-]\D/g, function(match){return match.charAt(1).toUpperCase();})];};var computed=document.defaultView.getComputedStyle(el,null);return(computed?computed.getPropertyValue([prop.replace(/[A-Z]/g, function(match){return('-'+match.charAt(0).toLowerCase());})]):null);}; + + +Red._module('Situated.PositionAndSize',function(){ var _=c$Situated.c$PositionAndSize.prototype; + _.m$height=function(){return this.m$size().m$_brac($s("y"));}; + _.m$width=function(){return this.m$size().m$_brac($s("x"));}; + _.m$scroll_top=function(){return this.m$scroll().m$_brac($s("y"));}; + _.m$scroll_left=function(){return this.m$scroll().m$_brac($s("x"));}; + _.m$scroll_height=function(){return this.m$scroll_size().m$_brac($s("y"));}; + _.m$scroll_width=function(){return this.m$scroll_size().m$_brac($s("x"));}; + _.m$top=function(){return this.m$position().m$_brac($s("x"));}; + _.m$left=function(){return this.m$position().m$_brac($s("y"));}; +}); + + +Red._module('Situated.Element',function(){ var _=c$Situated.c$Element.prototype; + var element=$u,h=$u,relative_to=$u,offset=$u,scroll=$u,position=$u,relative_position=$u,a=$u; + (this.m$include||window.m$include).call(this,c$Situated.c$PositionAndSize); + _.m$size=function(){if($T(this.m$is_body_bool())){return(this.m$window().m$size());};return(c$Hash.m$_brac($s("x"),this.__native__.offsetWidth,$s("y"),this.__native__.offsetHeight));}; + _.m$scroll=function(){if($T(this.m$is_body_bool())){return(this.m$window().m$scroll());};return(c$Hash.m$_brac($s("x"),this.__native__.scrollLeft,$s("y"),this.__native__.scrollTop));}; + _.m$scrolls=function(){var element = this.__native__, position = {x : 0, y : 0}; + while (element && !c$Situated.c$Utilities.m$is_body_bool(element)){ + position.x += element.scrollLeft; + position.y += element.scrollTop; + element = element.parentNode; + };return(c$Hash.m$_brac($s("x"),position.x,$s("y"),position.y));}; + _.m$scroll_size=function(){if($T(this.m$is_body_bool())){return(this.m$window().m$scroll_size());};return(c$Hash.m$_brac($s("x"),this.__native__.scrollWidth,$s("y"),this.__native__.scrollHeight));}; + _.m$scroll_to=function(x,y){if($T(this.m$is_body_bool())){this.m$window().m$scroll_to(x,y);}else{this.__native__.scrollLeft = x;this.__native__.scrollTop = y;};return(this);}; + _.m$offset_parent=function(){var element=$u;element=this;if($T(element.m$is_body_bool())){return(nil);};var e = element.__native__.offsetParent;if(!$T((this.m$trident_bool||window.m$trident_bool).call(this))){return($E(element.__native__.offsetParent));};while($T((($.da=$T(element=$E(element.__native__.parentNode)))?(($.dc=$T($.db=!$T(element.m$is_body_bool())))?$.db:$.dc):$.da))){if(!$T(element.m$styles().m$_brac($s("position")).m$_eql2($q("static")))){return(element);};};return(nil);}; + _.m$offsets=function(){var Native = this.__native__;if($T((this.m$trident_bool||window.m$trident_bool).call(this))){var bound = Native.getBoundingClientRect();var html = this.m$document.__native__.documentElement;return(c$Hash.m$_brac($s("x"),bound.left + html.scrollLeft - html.clientLeft,$s("y"),bound.top + html.scrollTop - html.clientTop));};var position = {x: 0, y: 0};if($T(this.m$is_body_bool())){return(c$Hash.m$_brac($s("x"),position.x,$s("y"),position.y));}; + + element = Native + while (element && !c$Situated.c$Utilities.m$is_body_bool(element)){ + position.x += element.offsetLeft; + position.y += element.offsetTop; + + if ((this.m$gecko_bool||window.m$gecko_bool).call(this)){ + if (!c$Situated.c$Utilities.m$border_box(element)){ + position.x += c$Situated.c$Utilities.m$left_border(element); + position.y += c$Situated.c$Utilities.m$top_border(element); + } + var parent = element.parentNode; + if (parent && window.styleString(parent, 'overflow') != 'visible'){ + position.x += c$Situated.c$Utilities.m$left_border(parent); + position.y += c$Situated.c$Utilities.m$top_border(parent); + } + } else if (element != this && (this.m$webkit_bool||window.m$webkit_bool).call(this)){ + position.x += c$Situated.c$Utilities.m$left_border(element); + position.y += c$Situated.c$Utilities.m$top_border(element); + } + + element = element.offsetParent; + } + + if ((this.m$gecko_bool||window.m$gecko_bool).call(this) && !c$Situated.c$Utilities.m$border_box(Native)){ + position.x -= c$Situated.c$Utilities.m$left_border(Native); + position.y -= c$Situated.c$Utilities.m$top_border(Native); + } + ;return(c$Hash.m$_brac($s("x"),position.x,$s("y"),position.y));}; + _.m$position_at=function(x,y){var h=$u;var Native = this.__native__;h=c$Hash.m$_brac($s("left"),x.m$_subt(c$Situated.c$Utilities.m$styleNumber(Native,'margin-left')),$s("top"),y.m$_subt(c$Situated.c$Utilities.m$styleNumber(Native,'margin-top')),$s("position"),$q("absolute"));return this.m$set_styles(h);}; + _.m$position=function(relative_to){relative_to=$T($.de=relative_to)?$.de:nil;var offset=$u,scroll=$u,position=$u,relative_position=$u,a=$u;offset=this.m$offsets();scroll=this.m$scrolls();position=c$Hash.m$_brac($s("x"),offset.m$_brac($s("x")).m$_subt(scroll.m$_brac($s("x"))),$s("y"),offset.m$_brac($s("y")).m$_subt(scroll.m$_brac($s("y"))));relative_position=c$Hash.m$_brac($s("x"),0,$s("y"),0);return a=c$Hash.m$_brac($s("x"),position.m$_brac($s("x")).m$_subt(relative_position.m$_brac($s("x"))),$s("y"),position.m$_brac($s("y")).m$_subt(relative_position.m$_brac($s("y"))));}; +}); + + +Red._module('Situated.Viewport',function(){ var _=c$Situated.c$Viewport.prototype; + var win=$u,doc=$u,min=$u,size=$u; + (this.m$include||window.m$include).call(this,c$Situated.c$PositionAndSize); + _.m$size=function(){var win=$u,doc=$u;win=this.m$window();if($T(($T($.dl=(this.m$presto_bool||window.m$presto_bool).call(this))?$.dl:(this.m$webkit_bool||window.m$webkit_bool).call(this)))){return(c$Hash.m$_brac($s("x"),win.__native__.innerWidth,$s("y"),win.__native__.innerHeight));};doc=c$Situated.c$Utilities.m$native_compat_element(this);return(c$Hash.m$_brac($s("x"),doc.__native__.clientWidth,$s("y"),doc.__native__.clientHeight));}; + _.m$scroll=function(){var win=$u,doc=$u;win=this.m$window();doc=c$Situated.c$Utilities.m$native_compat_element(this);return(c$Hash.m$_brac($s("x"),($T($.dq=win.__native__.pageXOffset)?$.dq:doc.__native__.scrollLeft),$s("y"),($T($.dr=win.__native__pageYOffset)?$.dr:doc.__native__.scrollTop)));}; + _.m$scroll_size=function(){var doc=$u,min=$u;doc=c$Situated.c$Utilities.m$native_compat_element(this);min=this.m$size();return(c$Hash.m$_brac($s("x"),Math.max(doc.__native__.scrollWidth, min.m$_brac($s("x"))),$s("y"),Math.max(doc.__native__.scrollHeight,min.m$_brac($s("y")))));}; + _.m$position=function(){return(c$Hash.m$_brac($s("x"),0,$s("y"),0));}; + _.m$coordinates=function(){var size=$u;size=this.m$size();return(c$Hash.m$_brac($s("top"),0,$s("left"),0,$s("bottom"),size.m$_brac($s("y")),$s("right"),size.m$_brac($s("x")),$s("height"),size.m$_brac($s("y")),$s("width"),size.m$_brac($s("x"))));}; +}); + + +Red._module('Situated.Utilities',function(){ var _=c$Situated.c$Utilities.prototype; + c$Situated.c$Utilities.m$is_body_bool=function(element){$a(1,1,arguments,0);return (/^(?:body|html)$/i).test(element.tagName);}; + c$Situated.c$Utilities.m$styleNumber=function(native_element,style){$a(2,2,arguments,0);return parseInt(window.styleString(native_element, style)) || 0;}; + c$Situated.c$Utilities.m$border_box=function(element){$a(1,1,arguments,0);return window.styleString(element, '-moz-box-sizing') == 'border-box';}; + c$Situated.c$Utilities.m$top_border=function(element){$a(1,1,arguments,0);return c$Situated.c$Utilities.m$styleNumber(element, 'border-top-width');}; + c$Situated.c$Utilities.m$left_border=function(element){$a(1,1,arguments,0);return c$Situated.c$Utilities.m$styleNumber(element, 'border-left-width');}; + c$Situated.c$Utilities.m$native_compat_element=function(element){$a(1,1,arguments,0);var doc = element.m$document().__native__;return $E((!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body);}; +}); +}); + +Red._class('Element',c$Object,function(){ var _=c$Element.prototype; + (this.m$include||window.m$include).call(this,c$Situated.c$Element); +});c$Document.m$extend(c$Situated.c$Viewport);c$Window.m$extend(c$Situated.c$Viewport);false; + +Red._class('Transform',c$Object,function(){ var _=c$Transform.prototype; + var options=$u,wait=$u,rgb=$u; + (this.m$include||window.m$include).call(this,c$CodeEvents); + c$Transform.c$OPTIONS=c$Hash.m$_brac($s("fps"),50,$s("unit"),false,$s("duration"),500,$s("link"),$q("ignore")); + c$Transform.c$DURATIONS=c$Hash.m$_brac($s("short"),250,$s("normal"),500,$s("long"),1000); + c$Transform.c$ALGORITHMS=c$Hash.m$_brac($q("linear"),function(p){return -(Math.cos(Math.PI * p) - 1) / 2;}); + c$Transform.m$add_transition=function(name,func){$a(2,2,arguments,0);c$Transform.c$ALGORITHMS.m$_breq(name,func);c$Transform.c$ALGORITHMS.m$_breq($Q("",name,":in"),function(pos){return func(pos, params);});c$Transform.c$ALGORITHMS.m$_breq($Q("",name,":out"),function(pos){return 1 - func(1 - pos, params);});return c$Transform.c$ALGORITHMS.m$_breq($Q("",name,":in:out"),function(pos){return (pos <= 0.5) ? func(2 * pos, params) / 2 : (2 - func(2 * (1 - pos), params)) / 2;});}; + _.m$transition=function(transition){for(var l=arguments.length,i=1,args=[];i<l;++i){args.push(arguments[i]);};return c$Transform.c$ALGORITHMS.m$_brac(transition)(args);}; + $clear = function(timer){clearTimeout(timer);clearInterval(timer);return nil;};; + Function.prototype.create = function(options){ + var self = this; + options = options || {}; + return function(event){ + var args = options.arguments; + args = (args != undefined) ? $splat(args) : Array.slice(arguments, (options.event) ? 1 : 0); + if (options.event) args = [event || window.event].extend(args); + var returns = function(){ + return self.apply(options.bind || null, args); + }; + if (options.delay) return setTimeout(returns, options.delay); + if (options.periodical) return setInterval(returns, options.periodical); + return returns(); + }; + }; + Function.prototype.periodical = function(periodical, bind, args){ + return this.create({bind: bind, arguments: args, periodical: periodical})(); + };; + c$Transform.m$compute=function(from,to,delta){$a(3,3,arguments,0);return (to - from) * delta + from;}; + _.m$initialize=function(options){options=$T($.dv=options)?$.dv:c$Hash.m$_brac();var wait=$u;this.i$subject=($T($.dw=this.i$subject)?$.dw:this);this.i$options=c$Transform.c$OPTIONS.m$merge(options);this.i$options.m$_breq($s("duration"),($T($.dx=c$Transform.c$DURATIONS.m$_brac(this.i$options.m$_brac($s("duration"))))?$.dx:this.i$options.m$_brac($s("duration")).m$to_i()));wait=this.i$options.m$_brac($s("wait"));if($T(wait.m$_eql3(false))){this.i$options.m$_breq($s("link"),$q("cancel"));};}; + _.m$step=function(){ + var time = +new Date + if (time < this.__time__ + this.i$options.m$_brac($s("duration"))){ + var delta = this.__transition__((time - this.__time__) / this.i$options.m$_brac($s("duration"))); + this.m$set(this.m$compute(this.__from__, this.__to__, delta)); + } else { + this.m$set(this.m$compute(this.__from__, this.__to__, 1)); + this.m$complete(); + } + ;return(nil);}; + _.m$set_transition=function(){return this.__transition__ = c$Transform.c$ALGORITHMS.m$_brac(($T($.dz=this.i$options.m$_brac($s("transition")))?$.dz:$q("sine:in:out")));}; + _.m$set=function(now){return(now);}; + _.m$compute=function(from,to,delta){return(c$Transform.m$compute(from,to,delta));}; + _.m$check=function(caller){ + if (!this.__timer__) return true; + switch (this.i$options.m$_brac($s("link"))){ + case 'cancel': this.cancel(); return true; + case 'chain' : this.chain(caller.bind(this, Array.slice(arguments, 1))); return false; + };return(false);}; + _.m$start=function(from,to){if (!this.m$check(arguments.callee, from, to)) return this;this.__from__ = from;this.__to__ = to;this.__time__ = 0;this.__transition__ = function(p){ + return -(Math.cos(Math.PI * p) - 1) / 2; + };this.m$start_timer();this.m$fire($s("start"));return(this);}; + _.m$complete=function(){this.m$fire($s("completion"));this.m$stop_timer();return this;}; + _.m$cancel=function(){this.m$fire($s("cancellation"));this.m$stop_timer();return this;}; + _.m$pause=function(){this.m$stop_timer();return this;}; + _.m$resume=function(){this.m$start_timer();return this;}; + _.m$stop_timer=function(){if (!this.__timer__) return false;this.__time__ = (+new Date) - this.__time__;this.__timer__ = $clear(this.__timer__);return(true);}; + _.m$start_timer=function(){if (this.__timer__) return false;this.__time__ = (+new Date) - this.__time__;this.__timer__ = this.m$step.periodical(Math.round(1000 / this.i$options.m$_brac($s("fps"))), this);return(true);}; + x = {'pow' : function(p, x){return Math.pow(p, x[0] || 6);}, + 'expo' : function(p){return Math.pow(2, 8 * (p - 1));}, + 'circ' : function(p){return 1 - Math.sin(Math.acos(p));}, + 'sine' : function(p){return 1 - Math.sin((1 - p) * Math.PI / 2);}, + 'back' : function(p, x){x = x[0] || 1.618;return Math.pow(p, 2) * ((x + 1) * p - x);}, + 'bounce' : function(p){ var value; for (var a = 0, b = 1; 1; a += b, b /= 2){ if (p >= (7 - 4 * a) / 11){value = b * b - Math.pow((11 - 6 * a - 11 * p) / 4, 2);break;}}return value;}, + 'elastic' : function(p, x){return Math.pow(2, 10 * --p) * Math.cos(20 * p * Math.PI * (x[0] || 1) / 3);} + }; + for (prop in x) { + c$Transform.m$add_transition($q(prop), x.prop) + }; + x = ['quad', 'cubic', 'quart', 'quint']; + for (var i = 0, l = x.length; i < l; i ++) { + c$Transform.m$add_transition($q(x[i]), function(p){return Math.pow(p, [i + 2]);}) + };; + + +Red._module('Transform.Parser',function(){ var _=c$Transform.c$Parser.prototype; + var rgb=$u; + + +Red._class('Transform.Parser.Color',c$Object,function(){ var _=c$Transform.c$Parser.c$Color.prototype; + var rgb=$u; + c$Transform.c$Parser.c$Color.m$hex_to_array=function(color){$a(1,1,arguments,0);var hex = color.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/).slice(1);var rgb = [] + for(i = 0, l = hex.length; i < hex.length; i++){ + value = hex[i] + if (value.length == 1) value += value; + rgb[i] = parseInt(value,16); + };return rgb;}; + c$Transform.c$Parser.c$Color.m$compute=function(from,to,delta){$a(3,3,arguments,0);var rgb=$u;rgb=[];from.m$each(function(i){return rgb.m$_ltlt(Math.round(c$Transform.m$compute(from.m$_brac(i),to.m$_brac(i),delta)));}.m$(this));return 'rgb(' + rgb + ')';}; + c$Transform.c$Parser.c$Color.m$parse=function(value){$a(1,1,arguments,0);value = value.__value__ || String(value);if (value.match(/^#[0-9a-f]{3,6}$/i)) return c$Transform.c$Parser.c$Color.m$hex_to_array(value);return ((value = value.match(/(\d+),\s*(\d+),\s*(\d+)/))) ? [value.m$_brac(1),value.m$_brac(2),value.m$_brac(3)] : false;}; + c$Transform.c$Parser.c$Color.m$serve=function(value,unit){$a(2,2,arguments,0);return value;}; +}); + + +Red._class('Transform.Parser.Number',c$Object,function(){ var _=c$Transform.c$Parser.c$Number.prototype; + c$Transform.c$Parser.c$Number.m$compute=function(from,to,delta){$a(3,3,arguments,0);return c$Transform.m$compute(from,to,delta);}; + c$Transform.c$Parser.c$Number.m$parse=function(value){$a(1,1,arguments,0);value = value.__value__ || String(value);parsed = parseFloat(value);return (parsed || parsed == 0) ? parsed : false;}; + c$Transform.c$Parser.c$Number.m$serve=function(value,unit){$a(2,2,arguments,0);return(($T(unit)?value.m$_plus(unit):value));}; +}); + + +Red._class('Transform.Parser.String',c$Object,function(){ var _=c$Transform.c$Parser.c$String.prototype; + c$Transform.c$Parser.c$String.m$parse=function(value){$a(1,1,arguments,0);return false;}; + c$Transform.c$Parser.c$String.m$compute=function(from,to,delta){$a(3,3,arguments,0);return(to);}; + c$Transform.c$Parser.c$String.m$serve=function(value,unit){$a(2,2,arguments,0);return(value);}; +}); +}); + c$Transform.c$Parsers=[c$Transform.c$Parser.c$Color,c$Transform.c$Parser.c$Number,c$Transform.c$Parser.c$String]; +}); + +Red._class('Tween',c$Transform,function(){ var _=c$Tween.prototype; + var parsed=$u,to=$u,parsed_from_to=$u,value=$u,returns=$u,computed=$u; + _.m$initialize=function(element,options){this.i$element=this.i$subject=element;this.m$class().m$superclass().prototype.m$initialize.call(this,options);}; + _.m$start=function(property,from,to){var parsed=$u;this.i$property=property;parsed=this.m$prepare(this.i$element,property,[from,to]);return this.m$class().m$superclass().prototype.m$start.call(this,parsed.m$_brac($s("from")),parsed.m$_brac($s("to")));}; + _.m$prepare=function(element,property,from_to){var to=$u,parsed_from_to=$u;to=from_to.m$_brac(1);if(!$T(to)){from_to.m$_breq(1,from_to.m$_brac(0));from_to.m$_breq(0,element.m$styles().m$_brac(property));};parsed_from_to=[];from_to.m$each(function(val){return parsed_from_to.m$_ltlt(this.m$parse(val));}.m$(this));return(c$Hash.m$_brac($s("from"),parsed_from_to.m$_brac(0),$s("to"),parsed_from_to.m$_brac(1)));}; + _.m$parse=function(value){var returns=$u;value=value.m$to_s().m$split($q(" "));returns=[];value.m$each(function(val){c$Transform.c$Parsers.m$each(function(parser){parsed=parser.m$parse(val);return ($T(parsed)?found=c$Hash.m$_brac($s("value"),parsed,$s("parser"),parser):nil);}.m$(this));found=($T($.ei=found)?$.ei:c$Hash.m$_brac($s("value"),val,$s("parser"),c$Transform.c$Parser.c$String));return returns.m$_ltlt(found);}.m$(this));return(returns);}; + _.m$set=function(current_value){this.m$render(this.i$element,this.i$property,current_value.m$_brac(0),this.i$options.m$_brac($s("unit")));return(this);}; + _.m$render=function(element,property,current_value,unit){return element.m$set_style(property,this.m$serve(current_value,unit));}; + _.m$serve=function(value,unit){return value.m$_brac($s("parser")).m$serve(value.m$_brac($s("value")),unit);}; + _.m$compute=function(from,to,delta){var computed=$u;computed=[];Math.min(from.length, to.length).m$times(function(i){return computed.m$_ltlt(c$Hash.m$_brac($s("value"),from.m$_brac(i).m$_brac($s("parser")).m$compute(from.m$_brac(i).m$_brac($s("value")),to.m$_brac(i).m$_brac($s("value")),delta),$s("parser"),from.m$_brac(i).m$_brac($s("parser"))));}.m$(this));return(computed);}; +});c$Object.m$module_eval_with_string_not_block=function(str){$a(1,1,arguments,0);str=str.__value__;str='c$' + str;return window[str];}; + +Red._module('Bindable',function(){ var _=c$Bindable.prototype; + var binding=$u; + c$Bindable.m$included=function(base){$a(1,1,arguments,0);return base.m$extend(c$Bindable.c$SharedMethods);}; + (this.m$attr_accessor||window.m$attr_accessor).call(this,$s("bindings")); + + +Red._module('Bindable.SharedMethods',function(){ var _=c$Bindable.c$SharedMethods.prototype; + var binding=$u; + _.m$bind=function(attribute,path){var binding=$u;binding=c$Ribbon.m$new(this,attribute,path);(this.m$puts||window.m$puts).call(this,this.m$inspect());this.m$send(attribute.m$to_s().m$_plus($q("=")),binding.m$key_path().m$target_property());return(binding);}; + _.m$bindings=function(){return this.i$bindings;}; + _.m$bindings_for=function(attribute){this.i$bindings=($T($.ep=this.i$bindings)?$.ep:c$Hash.m$_brac());return ($T($.eo=this.i$bindings.m$_brac(attribute))?$.eo:[]);}; + _.m$add_binding_for_attribute=function(binding,attribute){this.i$bindings=($T($.eq=this.i$bindings)?$.eq:c$Hash.m$_brac());return ($T(this.i$bindings.m$_brac(attribute))?this.i$bindings.m$_brac(attribute).m$_ltlt(binding):this.i$bindings.m$_breq(attribute,[binding]));}; +}); + (this.m$include||window.m$include).call(this,c$Bindable.c$SharedMethods); +}); + +Red._module('KeyValueObserving',function(){ var _=c$KeyValueObserving.prototype; + (this.m$attr_accessor||window.m$attr_accessor).call(this,$s("bindings")); + c$KeyValueObserving.m$included=function(base){$a(1,1,arguments,0);base.m$extend(c$KeyValueObserving.c$ClassMethods);return base.m$extend(c$KeyValueObserving.c$SharedMethods);}; + + +Red._module('KeyValueObserving.SharedMethods',function(){ var _=c$KeyValueObserving.c$SharedMethods.prototype; + _.m$did_change_value_for=function(attribute){return (this.m$bindings_for||window.m$bindings_for).call(this,attribute).m$each(function(binding){return binding.m$object().m$send(binding.m$attribute().m$_plus($q("=")),binding.m$key_path().m$target_property());}.m$(this));}; +}); + (this.m$include||window.m$include).call(this,c$KeyValueObserving.c$SharedMethods); + + +Red._module('KeyValueObserving.ClassMethods',function(){ var _=c$KeyValueObserving.c$ClassMethods.prototype; + _.m$kvc_accessor=function(){for(var l=arguments.length,i=0,accessors=[];i<l;++i){accessors.push(arguments[i]);};return accessors.m$each(function(accessor){this.m$define_method(accessor,function(){return this.m$instance_variable_get($q("@").m$_plus(accessor));}.m$(this));return this.m$define_method(accessor.m$to_s().m$_plus($q("=")).m$to_sym(),function(value){this.m$instance_variable_set($q("@").m$_plus(accessor),value);return this.m$did_change_value_for(accessor.m$to_s());}.m$(this));}.m$(this));}; +}); +}); + +Red._class('KeyPath',c$Object,function(){ var _=c$KeyPath.prototype; + var callee=$u,caller=$u,set_method=$u; + _.m$initialize=function(path){this.i$path=path;}; + c$KeyPath.m$step_through=function(path){$a(1,1,arguments,0);var callee=$u,caller=$u;callee=c$Object.m$module_eval_with_string_not_block(path.m$shift());while($T(caller=path.m$shift())){callee=callee.m$send(caller);};return(callee);}; + c$KeyPath.m$step_through_with_assignment=function(path,set_value){$a(2,2,arguments,0);var set_method=$u,callee=$u,caller=$u;set_method=path.m$pop();callee=c$Object.m$module_eval_with_string_not_block(path.m$shift());while($T(caller=path.m$shift())){callee=callee.m$send(caller);};return(callee.m$send((this.m$accessor||window.m$accessor).call(this).m$_plus($q("=")),set_value));}; + _.m$target_object=function(){return c$KeyPath.m$step_through(this.i$path.m$split($q(".")).m$_brac(c$Range.m$new(0,-2,false)));}; + _.m$target_property_name=function(){return this.i$path.m$split($q(".")).m$last();}; + _.m$target_property=function(){return c$KeyPath.m$step_through(this.i$path.m$split($q(".")));}; +}); + +Red._class('Ribbon',c$Object,function(){ var _=c$Ribbon.prototype; + (this.m$attr_reader||window.m$attr_reader).call(this,$s("key_path"),$s("object"),$s("attribute")); + _.m$initialize=function(object,attribute,key_path){this.i$object=object;this.i$attribute=attribute;this.i$key_path=c$KeyPath.m$new(key_path);this.i$bound_object=this.i$key_path.m$target_object();this.i$bound_property=this.i$key_path.m$target_property_name();this.m$connect();}; + _.m$connect=function(){(this.m$puts||window.m$puts).call(this,this.i$bound_object.m$inspect());return this.i$bound_object.m$add_binding_for_attribute(this,this.i$bound_property);}; +}); + +Red._class('ArrangedObjects',c$Array,function(){ var _=c$ArrangedObjects.prototype; + (this.m$include||window.m$include).call(this,c$Bindable); + (this.m$include||window.m$include).call(this,c$KeyValueObserving); +}); + +Red._class('Controller',c$Object,function(){ var _=c$Controller.prototype; + (this.m$include||window.m$include).call(this,c$KeyValueObserving); + (this.m$include||window.m$include).call(this,c$Bindable); + c$Controller.m$kvc_accessor=function(){for(var l=arguments.length,i=0,accessors=[];i<l;++i){accessors.push(arguments[i]);};$a(0,-1,arguments,0);return accessors.m$each(function(accessor){c$Controller.m$define_method(accessor,function(){return c$Controller.m$instance_variable_get($q("@").m$_plus(accessor.m$to_s()));}.m$(this));c$Controller.m$define_method(accessor.m$to_s().m$_plus($q("=")).m$to_sym(),function(value){c$Controller.m$instance_variable_set($q("@").m$_plus(accessor.m$to_s()),value);return c$Controller.m$did_change_value_for(accessor.m$to_s());}.m$(this));m=c$Module.m$new(accessor.m$to_s().m$_plus($q("ControllerAttributeModule")));m.m$instance_eval(function(){c$Controller.m$define_method(accessor,function(){return c$Controller.m$shared_instance().m$send(accessor);}.m$(this));return c$Controller.m$define_method(accessor.m$to_s().m$_plus($q("=")).m$to_sym(),function(value){c$Controller.m$shared_instance().m$send(accessor.m$_plus($q("=")),value);return c$Controller.m$did_change_value_for(accessor.m$to_s());}.m$(this));});return c$Controller.m$extend(m);}.m$(this));}; + c$Controller.m$outlet=function(){for(var l=arguments.length,i=0,accessors=[];i<l;++i){accessors.push(arguments[i]);};$a(0,-1,arguments,0);if($T(this.i$outlets)){this.i$outlets.m$_plus(accessors);}else{this.i$outlets=accessors;};return accessors.m$each(function(accessor){c$Controller.m$define_method(accessor,function(){return c$Controller.m$instance_variable_get($q("@").m$_plus(accessor.m$to_s()));}.m$(this));c$Controller.m$define_method(accessor.m$to_s().m$_plus($q("=")).m$to_sym(),function(value){return c$Controller.m$instance_variable_set($q("@").m$_plus(accessor.m$to_s()),value);}.m$(this));m=c$Module.m$new(accessor.m$to_s().m$_plus($q("ControllerOutletModule")));m.m$instance_eval(function(){c$Controller.m$define_method(accessor,function(){return c$Controller.m$shared_instance().m$send(accessor);}.m$(this));return c$Controller.m$define_method(accessor.m$to_s().m$_plus($q("=")).m$to_sym(),function(value){return c$Controller.m$shared_instance().m$send(accessor.m$_plus($q("=")),value);}.m$(this));});return c$Controller.m$extend(m);}.m$(this));}; + c$Controller.m$outlets=function(){$a(0,0,arguments,0);return this.i$outlets;}; + c$Controller.m$shared_instance=function(){$a(0,0,arguments,0);this.i$arranged_objects=c$ArrangedObjects.m$new();return this.i$shared_instance=($T($.fa=this.i$shared_instance)?$.fa:c$Controller.m$new());}; +}); + +Red._class('ArrayController',c$Controller,function(){ var _=c$ArrayController.prototype; + this.m$kvc_accessor($s("arranged_objects"),$s("selection")); +}); + +Red._class('Model',c$Object,function(){ var _=c$Model.prototype; + (this.m$include||window.m$include).call(this,c$Bindable); + (this.m$include||window.m$include).call(this,c$KeyValueObserving); +}); + +Red._class('View',c$Object,function(){ var _=c$View.prototype; + var options=$u; + (this.m$include||window.m$include).call(this,c$KeyValueObserving); + (this.m$include||window.m$include).call(this,c$Bindable); + this.m$kvc_accessor($s("data_source")); + _.m$initialize=function(name,options){options=$T($.fb=options)?$.fb:c$Hash.m$_brac($s("bind"),c$Hash.m$_brac());options.m$_brac($s("bind")).m$each(function(property,path){return this.m$bind(property,path);}.m$(this));if($T(options.m$_brac($s("outlet")))){c$KeyPath.m$step_through_with_assignment(options.m$_brac($s("outlet")).m$split($q(".")),this);};}; + _.m$did_change_value_for=function(attribute){return (this.m$redraw||window.m$redraw).call(this);}; + _.m$redraw=function(){return nil;}; +}); + +Red._class('Note',c$Model,function(){ var _=c$Note.prototype; + (this.m$kvc_accessor||window.m$kvc_accessor).call(this,$s("name"),$s("body")); + this.i$data=c$ArrangedObjects.m$new([c$Note.m$new(),c$Note.m$new(),c$Note.m$new()]); + c$Note.m$all=function(){$a(0,0,arguments,0);return this.i$data;}; + c$Note.m$all_eql=function(ary){$a(1,1,arguments,0);this.i$data=ary;return c$Note.m$did_change_value_for($q("all"));}; +}); + +Red._class('NotesController',c$ArrayController,function(){ var _=c$NotesController.prototype; + (this.m$shared_instance||window.m$shared_instance).call(this); + this.m$bind($q("arranged_objects"),$q("Note.all")); + (this.m$outlet||window.m$outlet).call(this,$s("note_list")); +}); + +Red._class('ApplicationController',c$Object,function(){ var _=c$ApplicationController.prototype; + _.m$notes=function(){(this.m$will_change_value_for||window.m$will_change_value_for).call(this,$s("notes"));this.i$notes=($T($.fc=this.i$notes)?$.fc:c$Note.m$all());return (this.m$did_change_value_for||window.m$did_change_value_for).call(this,$s("notes"));}; +}); + +Red._class('SplitView',c$View,function(){ var _=c$SplitView.prototype; + ; +}); + +Red._class('ListView',c$View,function(){ var _=c$ListView.prototype; + ; +});c$WorkspaceView.m$new($q("main"),nil);c$SplitView.m$new($q(""),nil);c$ListView.m$new($q("notes_list"),c$Hash.m$_brac($s("data_source"),$q("NotesController.arranged_objects"))) \ No newline at end of file diff --git a/ribbon_notes/public/build/style.css b/ribbon_notes/public/build/style.css new file mode 100644 index 0000000..1a18b06 --- /dev/null +++ b/ribbon_notes/public/build/style.css @@ -0,0 +1,11 @@ +.workspace_view { + height: 100%; } + +.view { + height: 100%; + float: left; } + .view .split_view { + height: 100%; } + +p { + text_decoration: none; } diff --git a/ribbon_notes/ribbons.rb b/ribbon_notes/ribbons.rb new file mode 100644 index 0000000..a797e92 --- /dev/null +++ b/ribbon_notes/ribbons.rb @@ -0,0 +1,148 @@ +require 'rack/request' +require 'rack/response' +require 'rubygems' rescue nil +require 'haml' rescue nil +require 'sass' rescue nil +require 'red' +require 'red/executable' +require 'optparse' +require 'ftools' +require 'find' + +include Red + +class Ribbon + STYLE_FILE = 'public/build/style.css' + BEHAVIOR_FILE = 'public/build/behavior.js' + + attr_reader :styles, :behaviors + + def initialize + @styles = '' + @behaviors = '' + end + + def call(env) + Red.init(__FILE__) + Rack::Response.new([], 200, {"Content-Type" => "text/html"}) do |r| + r.write build_structure + end.finish + end + + def application_files + files_in('app') + end + + def framework_files + ::File.read('lib/ribbons.rb') + "\n" + end + + def files_in(name) + text = '' + ::Find.find(name) do |path| + if FileTest.directory?(path) + next + else + next unless File.extname(path) == '.red' || File.extname(path) == '.rb' + text << "\n" << ::File.read(path) + end + end + return text + end + + def redshift + "require 'redshift'\n" + end + + def reset + File.read('lib/assets/reset.sass') + end + + def write_style_file(styles) + File.open(STYLE_FILE, 'w') do |f| + f.write Sass::Engine.new(reset + styles).render + end + end + + def write_behavior_file(interface) + File.open(BEHAVIOR_FILE, 'w') do |f| + f.write translate_to_string_including_ruby(redshift + framework_files + application_files + interface.views + interface.initializations) + end + end + + def build_structure + context = ViewContext.new(self) + structure = Haml::Engine.new(::File.read('app/layouts/application.haml')).render(context) + write_style_file(context.styles) + write_behavior_file(context) + return structure + end +end + +class ViewContext + attr_reader :styles, :views, :initializations + def initialize(request) + @styles = '' + @views = '' + @initializations = '' + end + + def add_initialization(name, view_type, bindings) + cname = view_type.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } # camelize + @initializations << "\n" << "#{cname}.new(#{name.inspect},#{bindings.inspect})" + end + + def add_style_and_behavior_for(name) + @styles << "\n" << ::File.read("lib/views/#{name}/style.sass") + @views << "\n" << ::File.read("lib/views/#{name}/behavior.red") + end + + def parsed_view(name) + Haml::Engine.new(::File.read("lib/views/#{name}/structure.haml")) + end + + def workspace_view(name='', options={}, &block) + add_initialization(name, 'workspace_view', options[:bind]) + add_style_and_behavior_for('workspace_view') + haml_concat parsed_view('workspace_view').render(self,&block) + end + + def split_view(name='', options={}, &block) + add_initialization(name, 'split_view', options[:bind]) + add_style_and_behavior_for('split_view') + haml_concat parsed_view('split_view').render(self,&block) + end + + def list_view(name='',options={},&block) + add_initialization(name, 'list_view', options[:bind]) + add_style_and_behavior_for('list_view') + haml_concat parsed_view('list_view').render(self,&block) + end + + def list_item_view(options={}, &block) + add_style_and_behavior_for('list_item_view') + haml_concat parsed_view('list_item_view').render(self,&block) + end + + def splitter_view(&block) + add_style_and_behavior_for('splitter_view') + haml_concat parsed_view('splitter_view').render(self,&block) + end + + def text_view(options={}, &block) + add_style_and_behavior_for('text_view') + haml_concat parsed_view('text_view').render(self,&block) + end + + def identify + 'view_1' + end +end + +if $0 == __FILE__ + require 'rack' + require 'rack/showexceptions' + Rack::Handler::WEBrick.run \ + Rack::ShowExceptions.new(Rack::Lint.new(Rack::Herring.new)), + :Port => 9292 +end \ No newline at end of file